1 // **************************************************************************
2 // * This file is property of and copyright by the ALICE HLT Project *
3 // * All rights reserved. *
5 // * Primary Authors: *
6 // * Copyright 2009 Matthias Kretz <kretz@kde.org> *
8 // * Permission to use, copy, modify and distribute this software and its *
9 // * documentation strictly for non-commercial purposes is hereby granted *
10 // * without fee, provided that the above copyright notice appears in all *
11 // * copies and that both the copyright notice and this permission notice *
12 // * appear in the supporting documentation. The authors make no claims *
13 // * about the suitability of this software for any purpose. It is *
14 // * provided "as is" without express or implied warranty. *
15 // **************************************************************************
17 #ifndef MEMORYASSIGNMENTHELPERS_H
18 #define MEMORYASSIGNMENTHELPERS_H
22 template<unsigned int X>
23 static inline void AlignTo( char *&mem )
25 STATIC_ASSERT( ( X & ( X - 1 ) ) == 0, X_needs_to_be_a_multiple_of_2 );
26 const int offset = reinterpret_cast<unsigned long>( mem ) & ( X - 1 );
28 mem += ( X - offset );
30 //assert( ( reinterpret_cast<unsigned long>( mem ) & ( X - 1 ) ) == 0 );
33 template<unsigned int X>
34 static inline unsigned int NextMultipleOf( unsigned int value )
36 STATIC_ASSERT( ( X & ( X - 1 ) ) == 0, X_needs_to_be_a_multiple_of_2 );
37 const int offset = value & ( X - 1 );
39 return value + X - offset;
44 template<typename T, unsigned int Alignment> static T *AssignMemory( char *&mem, unsigned int size )
46 STATIC_ASSERT( ( Alignment & ( Alignment - 1 ) ) == 0, Alignment_needs_to_be_a_multiple_of_2 );
47 AlignTo<Alignment> ( mem );
48 T *r = reinterpret_cast<T *>( mem );
49 mem += size * sizeof( T );
53 template<typename T, unsigned int Alignment> static inline T *AssignMemory( char *&mem, unsigned int stride, unsigned int count )
55 assert( 0 == ( stride & ( Alignment - 1 ) ) );
56 return AssignMemory<T, Alignment>( mem, stride * count );
59 template<typename T, unsigned int Alignment> static T *_assignMemory( char *&mem, unsigned int size )
61 STATIC_ASSERT( ( Alignment & ( Alignment - 1 ) ) == 0, Alignment_needs_to_be_a_multiple_of_2 );
62 AlignTo<Alignment>( mem );
63 T *r = reinterpret_cast<T *>( mem );
64 mem += size * sizeof( T );
68 template<typename T> static inline void AssignMemory( T *&dst, char *&mem, int count )
70 dst = _assignMemory < T, ( sizeof( T ) & ( sizeof( T ) - 1 ) ) == 0 && sizeof( T ) <= 16 ? sizeof( T ) : sizeof( void * ) > ( mem, count );
73 #endif // MEMORYASSIGNMENTHELPERS_H