StRoot  1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
MemoryAssignmentHelpers.h
1 #ifndef MEMORYASSIGNMENTHELPERS_H
2 #define MEMORYASSIGNMENTHELPERS_H
3 
4 #include <assert.h>
5 
6 template<unsigned int X>
7 static inline void AlignTo( char *&mem )
8 {
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 );
11  if ( offset > 0 ) {
12  mem += ( X - offset );
13  }
14  //assert( ( reinterpret_cast<unsigned long>( mem ) & ( X - 1 ) ) == 0 );
15 }
16 
17 template<unsigned int X>
18 static inline unsigned int NextMultipleOf( unsigned int value )
19 {
20  STATIC_ASSERT( ( X & ( X - 1 ) ) == 0, X_needs_to_be_a_multiple_of_2 );
21  const int offset = value & ( X - 1 );
22  if ( offset > 0 ) {
23  return value + X - offset;
24  }
25  return value;
26 }
27 
28 template<typename T, unsigned int Alignment> static T *AssignMemory( char *&mem, unsigned int size )
29 {
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 );
34  return r;
35 }
36 
37 template<typename T, unsigned int Alignment> static inline T *AssignMemory( char *&mem, unsigned int stride, unsigned int count )
38 {
39  assert( 0 == ( stride & ( Alignment - 1 ) ) );
40  return AssignMemory<T, Alignment>( mem, stride * count );
41 }
42 
43 template<typename T, unsigned int Alignment> static T *_assignMemory( char *&mem, unsigned int size )
44 {
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 );
49  return r;
50 }
51 
52 template<typename T> static inline void AssignMemory( T *&dst, char *&mem, int count )
53 {
54  dst = _assignMemory<T, ( sizeof( T ) & ( sizeof( T ) - 1 ) ) == 0 && sizeof( T ) <= 16 ? sizeof( T ) : sizeof( void * )>( mem, count );
55 }
56 
57 template<unsigned int Alignment, typename T> static inline void AssignMemoryAligned( T *&dst, char *&mem, int count )
58 {
59  dst = _assignMemory<T, Alignment>( mem, count );
60 }
61 
62 template<typename T> static inline int RequiredMemory( const T *const, int count )
63 {
64  enum {
65  Alignment = ( sizeof( T ) & ( sizeof( T ) - 1 ) ) == 0 && sizeof( T ) <= 16 ? sizeof( T ) : sizeof( void * )
66  };
67  return Alignment + count * sizeof( T );
68 }
69 
70 #endif // MEMORYASSIGNMENTHELPERS_H