]> wimlib.net Git - wimlib/commitdiff
Add aligned malloc and free
authorEric Biggers <ebiggers3@gmail.com>
Thu, 12 Jun 2014 04:15:40 +0000 (23:15 -0500)
committerEric Biggers <ebiggers3@gmail.com>
Thu, 12 Jun 2014 04:20:22 +0000 (23:20 -0500)
Don't make dependent on OS support, since that would break the custom
memory allocation functions and also would need to be different between
UNIX and Windows anyway.

include/wimlib/util.h
src/util.c

index 869388fe298fa6101dae494aa51f537a79bd64df..91bed5a4aec32e340c4fefffed9066c774ef3675 100644 (file)
@@ -72,12 +72,20 @@ wimlib_wcsdup(const wchar_t *str) _malloc_attribute;
 extern char *
 wimlib_strdup(const char *str) _malloc_attribute;
 
 extern char *
 wimlib_strdup(const char *str) _malloc_attribute;
 
+extern void *
+wimlib_aligned_malloc(size_t size, size_t alignment) _malloc_attribute;
+
+extern void
+wimlib_aligned_free(void *ptr);
+
 #define        MALLOC  wimlib_malloc
 #define        FREE    wimlib_free_memory
 #define        REALLOC wimlib_realloc
 #define        CALLOC  wimlib_calloc
 #define        STRDUP  wimlib_strdup
 #define        WCSDUP  wimlib_wcsdup
 #define        MALLOC  wimlib_malloc
 #define        FREE    wimlib_free_memory
 #define        REALLOC wimlib_realloc
 #define        CALLOC  wimlib_calloc
 #define        STRDUP  wimlib_strdup
 #define        WCSDUP  wimlib_wcsdup
+#define        ALIGNED_MALLOC  wimlib_aligned_malloc
+#define        ALIGNED_FREE    wimlib_aligned_free
 
 extern void *
 memdup(const void *mem, size_t size) _malloc_attribute;
 
 extern void *
 memdup(const void *mem, size_t size) _malloc_attribute;
index fceae14b026b4aa196547dc0f815dad22622f668..54e29444655ada8905f3ca5f377a89e099821dbd 100644 (file)
@@ -37,6 +37,7 @@
 #endif
 
 #include "wimlib.h"
 #endif
 
 #include "wimlib.h"
+#include "wimlib/assert.h"
 #include "wimlib/compiler.h"
 #include "wimlib/encoding.h"
 #include "wimlib/error.h"
 #include "wimlib/compiler.h"
 #include "wimlib/encoding.h"
 #include "wimlib/error.h"
@@ -432,6 +433,36 @@ wimlib_wcsdup(const wchar_t *str)
 }
 #endif
 
 }
 #endif
 
+void *
+wimlib_aligned_malloc(size_t size, size_t alignment)
+{
+       u8 *raw_ptr;
+       u8 *ptr;
+       uintptr_t mask;
+
+       wimlib_assert(alignment != 0 && is_power_of_2(alignment) &&
+                     alignment <= 4096);
+       mask = alignment - 1;
+
+       raw_ptr = MALLOC(size + alignment - 1 + sizeof(size_t));
+       if (!raw_ptr)
+               return NULL;
+
+       ptr = (u8 *)raw_ptr + sizeof(size_t);
+       while ((uintptr_t)ptr & mask)
+               ptr++;
+       *((size_t *)ptr - 1) = (ptr - raw_ptr);
+
+       return ptr;
+}
+
+void
+wimlib_aligned_free(void *ptr)
+{
+       if (ptr)
+               FREE((u8 *)ptr - *((size_t *)ptr - 1));
+}
+
 void *
 memdup(const void *mem, size_t size)
 {
 void *
 memdup(const void *mem, size_t size)
 {