Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00034 #include "config.h"
00035 #include "shared/allocator.h"
00036 #include "shared/log.h"
00037
00038 #include <stdlib.h>
00039 #include <string.h>
00040
00041 static const char* allocator_str = "allocator";
00042
00047 allocator_type*
00048 allocator_create(void *(*allocator)(size_t size), void (*deallocator)(void *))
00049 {
00050 allocator_type* result =
00051 (allocator_type*) allocator(sizeof(allocator_type));
00052 if (!result) {
00053 ods_log_error("[%s] failed to create allocator", allocator_str);
00054 return NULL;
00055 }
00056 result->allocator = allocator;
00057 result->deallocator = deallocator;
00058 return result;
00059 }
00060
00061
00066 void*
00067 allocator_alloc(allocator_type* allocator, size_t size)
00068 {
00069 void* result;
00070
00071 ods_log_assert(allocator);
00072
00073 if (size == 0) {
00074 size = 1;
00075 }
00076 result = allocator->allocator(size);
00077 if (!result) {
00078 ods_fatal_exit("[%s] allocator failed: out of memory", allocator_str);
00079 return NULL;
00080 }
00081 return result;
00082 }
00083
00084
00089 void*
00090 allocator_alloc_zero(allocator_type *allocator, size_t size)
00091 {
00092 void *result = allocator_alloc(allocator, size);
00093 if (!result) {
00094 return NULL;
00095 }
00096 memset(result, 0, size);
00097 return result;
00098 }
00099
00100
00105 void*
00106 allocator_alloc_init(allocator_type *allocator, size_t size, const void *init)
00107 {
00108 void *result = allocator_alloc(allocator, size);
00109 if (!result) {
00110 return NULL;
00111 }
00112 memcpy(result, init, size);
00113 return result;
00114 }
00115
00116
00121 char*
00122 allocator_strdup(allocator_type *allocator, const char *string)
00123 {
00124 if (!string) {
00125 return NULL;
00126 }
00127 return (char*) allocator_alloc_init(allocator, strlen(string) + 1, string);
00128 }
00129
00130
00135 void
00136 allocator_deallocate(allocator_type *allocator, void* data)
00137 {
00138 ods_log_assert(allocator);
00139
00140 if (!data) {
00141 return;
00142 }
00143 allocator->deallocator(data);
00144 return;
00145 }
00146
00147
00152 void
00153 allocator_cleanup(allocator_type *allocator)
00154 {
00155 void (*deallocator)(void *);
00156 if (!allocator) {
00157 return;
00158 }
00159 deallocator = allocator->deallocator;
00160 deallocator(allocator);
00161 return;
00162 }
00163