• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #pragma once
15 
16 #include <inttypes.h>
17 #include <stddef.h>
18 #include <string.h>
19 
20 namespace android {
21 namespace base {
22 
23 // Class to create sub-allocations in an existing buffer. Similar interface to
24 // Pool, but underlying mechanism is different as it's difficult to combine
25 // same-size heaps in Pool with a preallocated buffer.
26 class SubAllocator {
27 public:
28     // |pageSize| determines both the alignment of pointers returned
29     // and the multiples of space occupied.
30     SubAllocator(
31         void* buffer,
32         uint64_t totalSize,
33         uint64_t pageSize);
34 
35     // Memory is freed from the perspective of the user of
36     // SubAllocator, but the prealloced buffer is not freed.
37     ~SubAllocator();
38 
39     // returns null if the allocation cannot be satisfied.
40     void* alloc(size_t wantedSize);
41     void free(void* ptr);
42     void freeAll();
43     uint64_t getOffset(void* ptr);
44 
45     // Convenience function to allocate an array
46     // of objects of type T.
47     template <class T>
allocArray(size_t count)48     T* allocArray(size_t count) {
49         size_t bytes = sizeof(T) * count;
50         void* res = alloc(bytes);
51         return (T*) res;
52     }
53 
strDup(const char * toCopy)54     char* strDup(const char* toCopy) {
55         size_t bytes = strlen(toCopy) + 1;
56         void* res = alloc(bytes);
57         memset(res, 0x0, bytes);
58         memcpy(res, toCopy, bytes);
59         return (char*)res;
60     }
61 
strDupArray(const char * const * arrayToCopy,size_t count)62     char** strDupArray(const char* const* arrayToCopy, size_t count) {
63         char** res = allocArray<char*>(count);
64 
65         for (size_t i = 0; i < count; i++) {
66             res[i] = strDup(arrayToCopy[i]);
67         }
68 
69         return res;
70     }
71 
dupArray(const void * buf,size_t bytes)72     void* dupArray(const void* buf, size_t bytes) {
73         void* res = alloc(bytes);
74         memcpy(res, buf, bytes);
75         return res;
76     }
77 
78 private:
79     class Impl;
80     Impl* mImpl = nullptr;
81 };
82 
83 } // namespace base
84 } // namespace android
85