Don't assume round-to-zero for fastf2i
[openal-soft.git] / common / almalloc.c
blob0d982ca19c10acd605d651d3f4cb0e526cd593f5
2 #include "config.h"
4 #include "almalloc.h"
6 #include <stdlib.h>
7 #include <string.h>
8 #ifdef HAVE_MALLOC_H
9 #include <malloc.h>
10 #endif
11 #ifdef HAVE_WINDOWS_H
12 #include <windows.h>
13 #else
14 #include <unistd.h>
15 #endif
18 #ifdef __GNUC__
19 #define LIKELY(x) __builtin_expect(!!(x), !0)
20 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
21 #else
22 #define LIKELY(x) (!!(x))
23 #define UNLIKELY(x) (!!(x))
24 #endif
27 void *al_malloc(size_t alignment, size_t size)
29 #if defined(HAVE_ALIGNED_ALLOC)
30 size = (size+(alignment-1))&~(alignment-1);
31 return aligned_alloc(alignment, size);
32 #elif defined(HAVE_POSIX_MEMALIGN)
33 void *ret;
34 if(posix_memalign(&ret, alignment, size) == 0)
35 return ret;
36 return NULL;
37 #elif defined(HAVE__ALIGNED_MALLOC)
38 return _aligned_malloc(size, alignment);
39 #else
40 char *ret = malloc(size+alignment);
41 if(ret != NULL)
43 *(ret++) = 0x00;
44 while(((ptrdiff_t)ret&(alignment-1)) != 0)
45 *(ret++) = 0x55;
47 return ret;
48 #endif
51 void *al_calloc(size_t alignment, size_t size)
53 void *ret = al_malloc(alignment, size);
54 if(ret) memset(ret, 0, size);
55 return ret;
58 void al_free(void *ptr)
60 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
61 free(ptr);
62 #elif defined(HAVE__ALIGNED_MALLOC)
63 _aligned_free(ptr);
64 #else
65 if(ptr != NULL)
67 char *finder = ptr;
68 do {
69 --finder;
70 } while(*finder == 0x55);
71 free(finder);
73 #endif
76 size_t al_get_page_size(void)
78 static size_t psize = 0;
79 if(UNLIKELY(!psize))
81 #ifdef HAVE_SYSCONF
82 #if defined(_SC_PAGESIZE)
83 if(!psize) psize = sysconf(_SC_PAGESIZE);
84 #elif defined(_SC_PAGE_SIZE)
85 if(!psize) psize = sysconf(_SC_PAGE_SIZE);
86 #endif
87 #endif /* HAVE_SYSCONF */
88 #ifdef _WIN32
89 if(!psize)
91 SYSTEM_INFO sysinfo;
92 memset(&sysinfo, 0, sizeof(sysinfo));
94 GetSystemInfo(&sysinfo);
95 psize = sysinfo.dwPageSize;
97 #endif
98 if(!psize) psize = DEF_ALIGN;
100 return psize;
103 int al_is_sane_alignment_allocator(void)
105 #if defined(HAVE_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN) || defined(HAVE__ALIGNED_MALLOC)
106 return 1;
107 #else
108 return 0;
109 #endif