Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct sizeless_tag {};
- constexpr static sizeless_tag sizeless;
- template<class Derived>
- class Allocator {
- public:
- u8* allocate(uword size) {
- return Derived::allocate(size, sizeless_tag);
- }
- u8* reallocate(u8* ptr, uword old_size, uword new_size) {
- return Derived::reallocate(ptr, sizeless_tag, new_size);
- }
- void free(u8* ptr, uword size) {
- Derived::free(ptr, sizeless_tag);
- }
- u8* allocate(uword size, sizeless_tag) {
- uword total_size = size + sizeof(uword);
- u8* pbase = Derived::allocate(total_size, sizeless);
- if (!pbase) {
- return nullptr;
- }
- *(uword*)pbase = total_size;
- return pbase + sizeof(uword);
- }
- u8* reallocate(u8* ptr, sizeless_tag, uword new_size) {
- u8* pbase = ptr - sizeof(uword);
- uword total_size = *(uword*)pbase;
- uword new_total_size = new_size + sizeof(uword);
- u8* new_pbase = Derived::reallocate(ptr, total_size, new_total_size);
- if (!new_pbase) {
- return nullptr;
- }
- *(uword*)new_pbase = new_total_size;
- return new_pbase + sizeof(uword);
- }
- void free(u8* ptr, sizeless_tag) {
- u8* pbase = ptr - sizeof(uword);
- uword total_size = *(uword*)pbase;
- Derived::free(pbase, total_size);
- }
- };
- struct Mallocator: public Allocator<Mallocator> {
- u8* allocate(uword size, sizeless_tag) {
- return (u8*)::malloc(size);
- }
- u8* reallocate(u8* ptr, sizeless_tag, uword new_size) {
- return (u8*)::realloc(ptr, new_size);
- }
- void free(u8* ptr, sizeless_tag) {
- ::free(ptr);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement