00001 #ifndef CVD_ALIGNED_MEM_H
00002 #define CVD_ALIGNED_MEM_H
00003 #include <cassert>
00004 #include <cvd/config.h>
00005
00006 namespace CVD {
00007 namespace Internal
00008 {
00009 template <class T, int N=20> struct placement_delete
00010 {
00011 enum { Size = (1<<N) };
00012
00013 struct Array {
00014 T data[Size];
00015 };
00016
00017 static inline void destruct(T* buf)
00018 {
00019 (*(Array*)buf).~Array();
00020 }
00021
00022 static inline void free(T* buf, size_t M)
00023 {
00024 if (M >= Size) {
00025 placement_delete<T,N>::free(buf+Size,M-Size);
00026 placement_delete<T,N>::destruct(buf);
00027 } else {
00028 placement_delete<T,N-1>::free(buf, M);
00029 }
00030 }
00031 };
00032
00033 template <class T> struct placement_delete<T,-1>
00034 {
00035 static inline void free(T*, size_t ) {}
00036 };
00037
00038 void * aligned_alloc(size_t count, size_t alignment);
00039 void aligned_free(void * memory);
00040
00041 template <class T>
00042 inline T * aligned_alloc(size_t count, size_t alignment){
00043 void * data = aligned_alloc(sizeof(T)* count, alignment);
00044 return new (data) T[count];
00045 }
00046
00047 template <class T>
00048 inline void aligned_free(T * memory, size_t count){
00049 placement_delete<T>::free(memory, count);
00050 aligned_free(memory);
00051 }
00052
00053 }
00054
00055 template <class T, int N> struct AlignedMem {
00056 T* mem;
00057 size_t count;
00058 AlignedMem(size_t c) : count(c) {
00059 mem = Internal::aligned_alloc<T>(count, N);
00060 }
00061 ~AlignedMem() {
00062 Internal::aligned_free<T>(mem, count);
00063 }
00064 T* data() { return mem; }
00065 const T* data() const { return mem; }
00066 };
00067 }
00068
00069 #endif