From 898f3890199c40780e40ca8e644ffe15a16b55b1 Mon Sep 17 00:00:00 2001 From: William Woodall Date: Wed, 16 Dec 2015 12:55:33 -0800 Subject: [PATCH] resolve reallocf todo --- rcl/include/rcl/allocator.h | 10 +++++++++- rcl/src/rcl/allocator.c | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/rcl/include/rcl/allocator.h b/rcl/include/rcl/allocator.h index d246ce7..e9014b6 100644 --- a/rcl/include/rcl/allocator.h +++ b/rcl/include/rcl/allocator.h @@ -43,10 +43,10 @@ typedef struct rcl_allocator_t void (* deallocate)(void * pointer, void * state); /// Reallocate if possible, otherwise it deallocates and allocates. /* If unsupported then do deallocate and then allocate. - * \TODO(wjwwood): should this behave as reallocf? * This should behave as realloc is described, as opposed to reallocf, i.e. * the memory given by pointer will not be free'd automatically if realloc * fails. + * For reallocf behavior use rcl_reallocf(). * This function must be able to take an input pointer of NULL and succeed. */ void * (*reallocate)(void * pointer, size_t size, void * state); @@ -64,6 +64,14 @@ RCL_PUBLIC rcl_allocator_t rcl_get_default_allocator(); +/// Emulate the behavior of reallocf. +/* This function will return NULL if the allocator is NULL or has NULL for + * function pointer fields. + */ +RCL_PUBLIC +void * +rcl_reallocf(void * pointer, size_t size, rcl_allocator_t * allocator); + #if __cplusplus } #endif diff --git a/rcl/src/rcl/allocator.c b/rcl/src/rcl/allocator.c index 14ec8b8..32c6406 100644 --- a/rcl/src/rcl/allocator.c +++ b/rcl/src/rcl/allocator.c @@ -15,6 +15,7 @@ #include #include "rcl/allocator.h" +#include "rcl/error_handling.h" static void * __default_allocate(size_t size, void * state) @@ -48,3 +49,17 @@ rcl_get_default_allocator() }; return default_allocator; } + +void * +rcl_reallocf(void * pointer, size_t size, rcl_allocator_t * allocator) +{ + if (!allocator || !allocator->reallocate || !allocator->deallocate) { + RCL_SET_ERROR_MSG("invalid allocator or allocator function pointers"); + return NULL; + } + void * new_pointer = allocator->reallocate(pointer, size, allocator->state); + if (!new_pointer) { + allocator->deallocate(pointer, allocator->state); + } + return new_pointer; +}