1 /* 2 * Copyright 2021 Google 3 * SPDX-License-Identifier: MIT 4 */ 5 #pragma once 6 7 #include <inttypes.h> 8 #include <stddef.h> 9 #include <string.h> 10 11 namespace gfxstream { 12 namespace aemu { 13 14 // A generic memory allocator interface which could be used to allocate 15 // a certain size of memory region, or memory region for arrays / strings. 16 // How the memory are recycled / freed is up to derived classes. 17 class Allocator { 18 public: 19 Allocator() = default; 20 virtual ~Allocator() = default; 21 22 virtual void* alloc(size_t wantedSize) = 0; 23 24 // Convenience function to allocate an array 25 // of objects of type T. 26 template <class T> allocArray(size_t count)27 T* allocArray(size_t count) { 28 size_t bytes = sizeof(T) * count; 29 void* res = alloc(bytes); 30 return (T*)res; 31 } 32 strDup(const char * toCopy)33 char* strDup(const char* toCopy) { 34 size_t bytes = strlen(toCopy) + 1; 35 void* res = alloc(bytes); 36 memset(res, 0x0, bytes); 37 memcpy(res, toCopy, bytes); 38 return (char*)res; 39 } 40 strDupArray(const char * const * arrayToCopy,size_t count)41 char** strDupArray(const char* const* arrayToCopy, size_t count) { 42 char** res = allocArray<char*>(count); 43 44 for (size_t i = 0; i < count; i++) { 45 res[i] = strDup(arrayToCopy[i]); 46 } 47 48 return res; 49 } 50 dupArray(const void * buf,size_t bytes)51 void* dupArray(const void* buf, size_t bytes) { 52 void* res = alloc(bytes); 53 memcpy(res, buf, bytes); 54 return res; 55 } 56 }; 57 58 } // namespace aemu 59 } // namespace gfxstream 60