liballoc-c

C generic allocator interface
git clone https://git.sinitax.com/sinitax/liballoc-c
Log | Files | Refs | LICENSE | sfeed.txt

commit 0b36b80642e93ddbc0f6df08b5049ad4cb1d6cc0
parent d9428e9b2fa4e5e5c346475cafe0454a96018a4a
Author: Louis Burda <quent.burda@gmail.com>
Date:   Thu, 25 May 2023 13:01:09 +0200

Add strict allocator wrapper

Diffstat:
Minclude/allocator.h | 8++++++++
Mliballoc.api | 2++
Mliballoc.lds | 1+
Msrc/allocator.c | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 70 insertions(+), 0 deletions(-)

diff --git a/include/allocator.h b/include/allocator.h @@ -10,5 +10,13 @@ struct allocator { int (*free)(const struct allocator *allocator, void *p); }; +struct strict_allocator { + const struct allocator *allocator_ul; + struct allocator allocator; +}; + +void strict_allocator_init(struct strict_allocator *strict_allocator_init, + const struct allocator *allocator_ul); + extern const struct allocator stdlib_heap_allocator; extern const struct allocator stdlib_strict_heap_allocator; diff --git a/liballoc.api b/liballoc.api @@ -1,2 +1,4 @@ +strict_allocator_init + stdlib_heap_allocator stdlib_strict_heap_allocator diff --git a/liballoc.lds b/liballoc.lds @@ -1,5 +1,6 @@ LIBALLOC_2.1 { global: + strict_allocator_init; stdlib_heap_allocator; stdlib_strict_heap_allocator; local: *; diff --git a/src/allocator.c b/src/allocator.c @@ -89,3 +89,62 @@ stdlib_strict_heap_free(const struct allocator *allocator, void *p) return 0; } + +void * +strict_allocator_alloc(const struct allocator *allocator, size_t size, int *rc) +{ + const struct strict_allocator *strict_allocator; + void *p; + + strict_allocator = ((void *) allocator) + - offsetof(struct strict_allocator, allocator); + + p = strict_allocator->allocator_ul->alloc( + strict_allocator->allocator_ul, size, rc); + if (!p) abort(); + + return p; +} + +void * +strict_allocator_realloc(const struct allocator *allocator, + void *p, size_t size, int *rc) +{ + const struct strict_allocator *strict_allocator; + void *np; + + strict_allocator = ((void *) allocator) + - offsetof(struct strict_allocator, allocator); + + np = strict_allocator->allocator_ul->realloc( + strict_allocator->allocator_ul, p, size, rc); + if (!np) abort(); + + return np; +} + +int +strict_allocator_free(const struct allocator *allocator, void *p) +{ + const struct strict_allocator *strict_allocator; + int rc; + + strict_allocator = ((void *) allocator) + - offsetof(struct strict_allocator, allocator); + + rc = strict_allocator->allocator_ul->free( + strict_allocator->allocator_ul, p); + if (rc) abort(); + + return 0; +} + +void +strict_allocator_init(struct strict_allocator *strict_allocator, + const struct allocator *allocator_ul) +{ + strict_allocator->allocator_ul = allocator_ul; + strict_allocator->allocator.alloc = strict_allocator_alloc; + strict_allocator->allocator.realloc = strict_allocator_realloc; + strict_allocator->allocator.free = strict_allocator_free; +}