Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //MemoryAlignment.h
- #ifndef PlaneGC_MemoryAlignment_h
- #define PlaneGC_MemoryAlignment_h
- namespace PlaneGC {
- template<unsigned int X, unsigned int P=0> class RoundUpPowerOf2_CompileTime;
- template<unsigned int X> class RoundUpPowerOf2_CompileTime<X, (sizeof(unsigned int) * 8) - 1> {
- public: static const unsigned int V= 1u << ((sizeof(unsigned int) * 8) - 1);
- };
- template<unsigned int X, unsigned int P> class RoundUpPowerOf2_CompileTime {
- public: static const unsigned int V= X > (1u << P) ? RoundUpPowerOf2_CompileTime<X, P+1>::V : (1u << P);
- };
- template<unsigned int X, unsigned int P=31> class RoundDownPowerOf2_CompileTime;
- template<unsigned int X> class RoundDownPowerOf2_CompileTime<X, 1> {
- public: static const unsigned int V= 1;
- };
- template<unsigned int X, unsigned int P> class RoundDownPowerOf2_CompileTime {
- public: static const unsigned int V= X < (1u << P) ? RoundDownPowerOf2_CompileTime<X, P-1>::V : (1u << P);
- };
- #ifndef MEMORY_ALIGNMENT
- //This union helps determine the "worst case" for memory alignment.
- //Most systems will align memory to 4 or 8 bytes, this struct will probably be bigger than that
- union GuessMemoryAlignment_u {
- //long long l;
- double d;
- void* p;
- void(*fptr)();
- };
- const size_t MemoryAlignment= RoundUpPowerOf2_CompileTime<sizeof(GuessMemoryAlignment_u)>::V;
- #else //#ifndef MEMORY_ALIGNMENT
- const size_t MemoryAlignment= (size_t)MEMORY_ALIGNMENT;
- #endif //#ifndef MEMORY_ALIGNMENT
- template<unsigned int I, int M> struct IntegerCeiling_CompileTime {
- static const unsigned int value= (((I - 1) / M) + 1) * M;
- };
- template<size_t bytes> class ObjectPadding {
- static const size_t ___padding_size= bytes;
- char ___padding[bytes];
- };
- template<> class ObjectPadding<0> {
- static const size_t ___padding_size= 0;
- };
- template<size_t bytes, size_t ceiling= MemoryAlignment> struct GetPaddedSize {
- static const size_t value= IntegerCeiling_CompileTime<bytes, ceiling>::value;
- };
- template<size_t bytes, size_t ceiling= MemoryAlignment> struct GetPaddingNeeded {
- static const size_t value= IntegerCeiling_CompileTime<bytes, ceiling>::value - bytes;
- };
- inline size_t GetPaddedSize_f(size_t bytes, size_t ceiling= MemoryAlignment) {
- return ((bytes - 1) | (ceiling - 1)) + 1;
- };
- inline size_t GetPaddingNeeded_f(size_t bytes, size_t ceiling= MemoryAlignment) {
- --bytes;
- return (bytes | (ceiling - 1)) - bytes;
- };
- template<typename T, size_t ceiling= MemoryAlignment> struct PaddedObject:
- public T,
- ObjectPadding<GetPaddingNeeded<sizeof(T), ceiling>::value>
- {
- };
- } //end namespace
- #endif #ifndef PlaneGC_MemoryAlignment_h
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement