1 #ifndef MEMORYASSIGNMENTHELPERS_H
2 #define MEMORYASSIGNMENTHELPERS_H
6 template<
unsigned int X>
7 static inline void AlignTo(
char *&mem )
9 STATIC_ASSERT( ( X & ( X - 1 ) ) == 0, X_needs_to_be_a_multiple_of_2 );
10 const int offset =
reinterpret_cast<unsigned long>( mem ) & ( X - 1 );
12 mem += ( X - offset );
17 template<
unsigned int X>
18 static inline unsigned int NextMultipleOf(
unsigned int value )
20 STATIC_ASSERT( ( X & ( X - 1 ) ) == 0, X_needs_to_be_a_multiple_of_2 );
21 const int offset = value & ( X - 1 );
23 return value + X - offset;
28 template<
typename T,
unsigned int Alignment>
static T *AssignMemory(
char *&mem,
unsigned int size )
30 STATIC_ASSERT( ( Alignment & ( Alignment - 1 ) ) == 0, Alignment_needs_to_be_a_multiple_of_2 );
31 AlignTo<Alignment> ( mem );
32 T *r =
new( mem ) T[size];
33 mem += size *
sizeof( T );
37 template<
typename T,
unsigned int Alignment>
static inline T *AssignMemory(
char *&mem,
unsigned int stride,
unsigned int count )
39 assert( 0 == ( stride & ( Alignment - 1 ) ) );
40 return AssignMemory<T, Alignment>( mem, stride * count );
43 template<
typename T,
unsigned int Alignment>
static T *_assignMemory(
char *&mem,
unsigned int size )
45 STATIC_ASSERT( ( Alignment & ( Alignment - 1 ) ) == 0, Alignment_needs_to_be_a_multiple_of_2 );
46 AlignTo<Alignment>( mem );
47 T *r =
new( mem ) T[size];
48 mem += size *
sizeof( T );
52 template<
typename T>
static inline void AssignMemory( T *&dst,
char *&mem,
int count )
54 dst = _assignMemory<T, (
sizeof( T ) & (
sizeof( T ) - 1 ) ) == 0 &&
sizeof( T ) <= 16 ?
sizeof( T ) :
sizeof(
void * )>( mem, count );
57 template<
unsigned int Alignment,
typename T>
static inline void AssignMemoryAligned( T *&dst,
char *&mem,
int count )
59 dst = _assignMemory<T, Alignment>( mem, count );
62 template<
typename T>
static inline int RequiredMemory(
const T *
const,
int count )
65 Alignment = (
sizeof( T ) & (
sizeof( T ) - 1 ) ) == 0 &&
sizeof( T ) <= 16 ?
sizeof( T ) :
sizeof(
void * )
67 return Alignment + count *
sizeof( T );
70 #endif // MEMORYASSIGNMENTHELPERS_H