]> git.tdb.fi Git - ext/openal.git/blob - common/almalloc.cpp
Tweak some types to work around an MSVC compile error
[ext/openal.git] / common / almalloc.cpp
1
2 #include "config.h"
3
4 #include "almalloc.h"
5
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
14
15
16 void *al_malloc(size_t alignment, size_t size)
17 {
18     assert((alignment & (alignment-1)) == 0);
19     alignment = std::max(alignment, alignof(std::max_align_t));
20
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)
32     {
33         void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
34         total_size -= sizeof(void*);
35
36         std::align(alignment, size, aligned_ptr, total_size);
37         *(static_cast<void**>(aligned_ptr)-1) = base;
38         base = aligned_ptr;
39     }
40     return base;
41 #endif
42 }
43
44 void *al_calloc(size_t alignment, size_t size)
45 {
46     void *ret{al_malloc(alignment, size)};
47     if(ret) std::memset(ret, 0, size);
48     return ret;
49 }
50
51 void al_free(void *ptr) noexcept
52 {
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
61 }