Move a couple types to the source they're used in
[openal-soft.git] / common / almalloc.cpp
blob842fb400f78aa7db3145855a9318a9a0655d2790
2 #include "config.h"
4 #include "almalloc.h"
6 #include <cassert>
7 #include <cstddef>
8 #include <cstdlib>
9 #include <cstring>
10 #ifdef HAVE_MALLOC_H
11 #include <malloc.h>
12 #endif
15 #define ALIGNED_ALLOC_AVAILABLE (__STDC_VERSION__ >= 201112L || __cplusplus >= 201703L)
17 void *al_malloc(size_t alignment, size_t size)
19 assert((alignment & (alignment-1)) == 0);
20 alignment = std::max(alignment, alignof(std::max_align_t));
22 #if ALIGNED_ALLOC_AVAILABLE
23 size = (size+(alignment-1))&~(alignment-1);
24 return aligned_alloc(alignment, size);
25 #elif defined(HAVE_POSIX_MEMALIGN)
26 void *ret;
27 if(posix_memalign(&ret, alignment, size) == 0)
28 return ret;
29 return nullptr;
30 #elif defined(HAVE__ALIGNED_MALLOC)
31 return _aligned_malloc(size, alignment);
32 #else
33 auto *ret = static_cast<char*>(malloc(size+alignment));
34 if(ret != nullptr)
36 *(ret++) = 0x00;
37 while((reinterpret_cast<uintptr_t>(ret)&(alignment-1)) != 0)
38 *(ret++) = 0x55;
40 return ret;
41 #endif
44 void *al_calloc(size_t alignment, size_t size)
46 void *ret = al_malloc(alignment, size);
47 if(ret) memset(ret, 0, size);
48 return ret;
51 void al_free(void *ptr) noexcept
53 #if ALIGNED_ALLOC_AVAILABLE || defined(HAVE_POSIX_MEMALIGN)
54 free(ptr);
55 #elif defined(HAVE__ALIGNED_MALLOC)
56 _aligned_free(ptr);
57 #else
58 if(ptr != nullptr)
60 auto *finder = static_cast<char*>(ptr);
61 do {
62 --finder;
63 } while(*finder == 0x55);
64 free(finder);
66 #endif