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 <unordered_set> 17 18 #include <inttypes.h> 19 #include <stddef.h> 20 #include <string.h> 21 22 namespace android { 23 namespace base { 24 25 // Class to make it easier to set up memory regions where it is fast 26 // to allocate/deallocate buffers that have size within 27 // the specified range. 28 class Pool { 29 public: 30 // minSize/maxSize: the target range of sizes for which we want to 31 // make allocations fast. the greater the range, the more space 32 // traded off. 33 // chunksPerSize: the target maximum number of live objects of 34 // each size that are expected. the higher it is, the more space 35 // traded off. 36 // 37 // Rough space cost formula: 38 // O(chunksPerSize * log2(maxSize / minSize) * maxSize) 39 Pool(size_t minSize = 4, 40 size_t maxSize = 4096, 41 size_t chunksPerSize = 1024); 42 43 44 // All memory allocated by this pool 45 // is automatically deleted when the pool 46 // is deconstructed. 47 ~Pool(); 48 49 void* alloc(size_t wantedSize); 50 void free(void* ptr); 51 52 // Convenience function to free everything currently allocated. 53 void freeAll(); 54 55 // Convenience function to allocate an array 56 // of objects of type T. 57 template <class T> allocArray(size_t count)58 T* allocArray(size_t count) { 59 size_t bytes = sizeof(T) * count; 60 void* res = alloc(bytes); 61 return (T*) res; 62 } 63 strDup(const char * toCopy)64 char* strDup(const char* toCopy) { 65 size_t bytes = strlen(toCopy) + 1; 66 void* res = alloc(bytes); 67 memset(res, 0x0, bytes); 68 memcpy(res, toCopy, bytes); 69 return (char*)res; 70 } 71 strDupArray(const char * const * arrayToCopy,size_t count)72 char** strDupArray(const char* const* arrayToCopy, size_t count) { 73 char** res = allocArray<char*>(count); 74 75 for (size_t i = 0; i < count; i++) { 76 res[i] = strDup(arrayToCopy[i]); 77 } 78 79 return res; 80 } 81 dupArray(const void * buf,size_t bytes)82 void* dupArray(const void* buf, size_t bytes) { 83 void* res = alloc(bytes); 84 memcpy(res, buf, bytes); 85 return res; 86 } 87 88 private: 89 class Impl; 90 Impl* mImpl = nullptr; 91 92 std::unordered_set<void*> mFallbackPtrs; 93 }; 94 95 } // namespace base 96 } // namespace android 97