Advertisement
tinyevil

Untitled

Aug 23rd, 2019
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1.  
  2. struct sizeless_tag {};
  3. constexpr static sizeless_tag sizeless;
  4.  
  5. template<class Derived>
  6. class Allocator {
  7. public:
  8.     u8* allocate(uword size) {
  9.         return Derived::allocate(size, sizeless_tag);
  10.     }
  11.  
  12.     u8* reallocate(u8* ptr, uword old_size, uword new_size) {
  13.         return Derived::reallocate(ptr, sizeless_tag, new_size);
  14.     }
  15.  
  16.     void free(u8* ptr, uword size) {
  17.         Derived::free(ptr, sizeless_tag);
  18.     }
  19.  
  20.     u8* allocate(uword size, sizeless_tag) {
  21.         uword total_size = size + sizeof(uword);
  22.         u8* pbase = Derived::allocate(total_size, sizeless);
  23.         if (!pbase) {
  24.             return nullptr;
  25.         }
  26.         *(uword*)pbase = total_size;
  27.         return pbase + sizeof(uword);
  28.     }
  29.  
  30.     u8* reallocate(u8* ptr, sizeless_tag, uword new_size) {
  31.         u8* pbase = ptr - sizeof(uword);
  32.         uword total_size = *(uword*)pbase;
  33.         uword new_total_size = new_size + sizeof(uword);
  34.         u8* new_pbase = Derived::reallocate(ptr, total_size, new_total_size);
  35.         if (!new_pbase) {
  36.             return nullptr;
  37.         }
  38.         *(uword*)new_pbase = new_total_size;
  39.         return new_pbase + sizeof(uword);
  40.     }
  41.  
  42.     void free(u8* ptr, sizeless_tag) {
  43.         u8* pbase = ptr - sizeof(uword);
  44.         uword total_size = *(uword*)pbase;
  45.         Derived::free(pbase, total_size);
  46.     }
  47. };
  48.  
  49. struct Mallocator: public Allocator<Mallocator> {
  50.     u8* allocate(uword size, sizeless_tag) {
  51.         return (u8*)::malloc(size);
  52.     }
  53.  
  54.     u8* reallocate(u8* ptr, sizeless_tag, uword new_size) {
  55.         return (u8*)::realloc(ptr, new_size);
  56.     }
  57.  
  58.     void free(u8* ptr, sizeless_tag) {
  59.         ::free(ptr);
  60.     }
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement