Created
December 19, 2016 09:17
-
-
Save benloong/9f430c14832a6f4dbec3df79d5e52bf4 to your computer and use it in GitHub Desktop.
aligned allocator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include<memory> | |
template<int alignment> | |
struct aligned_allocator | |
{ | |
static_assert((alignment&(alignment - 1)) == 0, "alignment must be power of 2."); | |
void* allocate(size_t size) { | |
size += alignment; | |
uint8_t* mem = (uint8_t*)std::malloc(size); | |
uint8_t* aligned = (uint8_t*) ((size_t) (mem + alignment) & (~(size_t)(alignment - 1))); | |
auto offset = aligned - mem; | |
aligned[-1] = (uint8_t)offset; | |
return aligned; | |
} | |
void free(void* addr) { | |
uint8_t* aligned = (uint8_t*)addr; | |
auto offset = aligned[-1]; | |
std::free(aligned - offset); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment