1 // Copyright 2021 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 gfxstream { 21 namespace guest { 22 23 // A generic memory allocator interface which could be used to allocate 24 // a certain size of memory region, or memory region for arrays / strings. 25 // How the memory are recycled / freed is up to derived classes. 26 class Allocator { 27 public: 28 Allocator() = default; 29 virtual ~Allocator() = default; 30 31 virtual void* alloc(size_t wantedSize) = 0; 32 33 // Convenience function to allocate an array 34 // of objects of type T. 35 template <class T> allocArray(size_t count)36 T* allocArray(size_t count) { 37 size_t bytes = sizeof(T) * count; 38 void* res = alloc(bytes); 39 return (T*)res; 40 } 41 strDup(const char * toCopy)42 char* strDup(const char* toCopy) { 43 size_t bytes = strlen(toCopy) + 1; 44 void* res = alloc(bytes); 45 memset(res, 0x0, bytes); 46 memcpy(res, toCopy, bytes); 47 return (char*)res; 48 } 49 strDupArray(const char * const * arrayToCopy,size_t count)50 char** strDupArray(const char* const* arrayToCopy, size_t count) { 51 char** res = allocArray<char*>(count); 52 53 for (size_t i = 0; i < count; i++) { 54 res[i] = strDup(arrayToCopy[i]); 55 } 56 57 return res; 58 } 59 dupArray(const void * buf,size_t bytes)60 void* dupArray(const void* buf, size_t bytes) { 61 void* res = alloc(bytes); 62 memcpy(res, buf, bytes); 63 return res; 64 } 65 }; 66 67 } // namespace base 68 } // namespace android 69