Make a couple more operator bools explicit
[openal-soft.git] / common / almalloc.cpp
blobad1dc6be082ecd1fc131cbe6c50477461f7dcdfc
2 #include "config.h"
4 #include "almalloc.h"
6 #include <cassert>
7 #include <cstddef>
8 #include <cstdlib>
9 #include <cstring>
10 #include <memory>
11 #ifdef HAVE_MALLOC_H
12 #include <malloc.h>
13 #endif
16 void *al_malloc(size_t alignment, size_t size)
18 assert((alignment & (alignment-1)) == 0);
19 alignment = std::max(alignment, alignof(std::max_align_t));
21 #if defined(HAVE_POSIX_MEMALIGN)
22 void *ret{};
23 if(posix_memalign(&ret, alignment, size) == 0)
24 return ret;
25 return nullptr;
26 #elif defined(HAVE__ALIGNED_MALLOC)
27 return _aligned_malloc(size, alignment);
28 #else
29 size_t total_size{size + alignment-1 + sizeof(void*)};
30 void *base{std::malloc(total_size)};
31 if(base != nullptr)
33 void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
34 total_size -= sizeof(void*);
36 std::align(alignment, size, aligned_ptr, total_size);
37 *(static_cast<void**>(aligned_ptr)-1) = base;
38 base = aligned_ptr;
40 return base;
41 #endif
44 void *al_calloc(size_t alignment, size_t size)
46 void *ret{al_malloc(alignment, size)};
47 if(ret) std::memset(ret, 0, size);
48 return ret;
51 void al_free(void *ptr) noexcept
53 #if defined(HAVE_POSIX_MEMALIGN)
54 std::free(ptr);
55 #elif defined(HAVE__ALIGNED_MALLOC)
56 _aligned_free(ptr);
57 #else
58 if(ptr != nullptr)
59 std::free(*(static_cast<void**>(ptr) - 1));
60 #endif