From d874d01e8e9a30f0073a6e559cbae07244dec7bf Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Thu, 3 Oct 2024 00:36:26 +0200 Subject: Huge library overhaul --- lib/array/array_free.c | 12 ++++++++++++ lib/array/array_new.c | 29 +++++++++++++++++++++++++++++ lib/array/array_resz.c | 28 ++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 lib/array/array_free.c create mode 100644 lib/array/array_new.c create mode 100644 lib/array/array_resz.c (limited to 'lib/array') diff --git a/lib/array/array_free.c b/lib/array/array_free.c new file mode 100644 index 0000000..0e5560e --- /dev/null +++ b/lib/array/array_free.c @@ -0,0 +1,12 @@ +#include + +#include "array.h" +#include "alloc.h" + +void +(array_free)(void *vptr, ptrdiff_t elemsz, ptrdiff_t align) +{ + ptrdiff_t pad = -sizeof(_mlib_arr_hdr_t) & (align - 1); + _mlib_arr_hdr_t *hdr = _mlib_array_hdr(vptr, align); + delete(hdr->mem, (uint8_t *)hdr, sizeof(*hdr) + pad + hdr->cap*elemsz); +} diff --git a/lib/array/array_new.c b/lib/array/array_new.c new file mode 100644 index 0000000..7339ba5 --- /dev/null +++ b/lib/array/array_new.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +#include "array.h" +#include "alloc.h" + +void * +(array_new)(allocator_t mem, ptrdiff_t nmemb, ptrdiff_t elemsz, ptrdiff_t align) +{ + ptrdiff_t total, pad = -sizeof(_mlib_arr_hdr_t) & (align - 1); + + /* Overflow; just call the allocator with the maximum size to force + proper error handling */ + if (ckd_mul(&total, nmemb, elemsz) + || ckd_add(&total, total, pad) + || ckd_add(&total, total, sizeof(_mlib_arr_hdr_t))) + { + mem.alloc(mem, ALLOC_NEW, nullptr, 0, + PTRDIFF_MAX, PTRDIFF_MAX, PTRDIFF_MAX); + unreachable(); + } + + uint8_t *buf = new(mem, uint8_t, total); + _mlib_arr_hdr_t hdr = {0, nmemb, mem}; + memcpy(buf, &hdr, sizeof(hdr)); + return buf + sizeof(_mlib_arr_hdr_t) + pad; +} diff --git a/lib/array/array_resz.c b/lib/array/array_resz.c new file mode 100644 index 0000000..d28a7a0 --- /dev/null +++ b/lib/array/array_resz.c @@ -0,0 +1,28 @@ +#include +#include +#include + +#include "array.h" +#include "alloc.h" + +void * +(array_resz)(void *ptr, ptrdiff_t ncap, ptrdiff_t elemsz, ptrdiff_t align) +{ + ptrdiff_t newsz, pad = -sizeof(_mlib_arr_hdr_t) & (align - 1); + _mlib_arr_hdr_t *hdr = _mlib_array_hdr(ptr, align); + /* Overflow; just call the allocator with the maximum size to force + proper error handling */ + if (ckd_mul(&newsz, ncap, elemsz) + || ckd_add(&newsz, newsz, pad) + || ckd_add(&newsz, newsz, sizeof(_mlib_arr_hdr_t))) + { + hdr->mem.alloc(hdr->mem, ALLOC_NEW, nullptr, 0, + PTRDIFF_MAX, PTRDIFF_MAX, PTRDIFF_MAX); + unreachable(); + } + + ptrdiff_t oldsz = sizeof(_mlib_arr_hdr_t) + pad + hdr->cap*elemsz; + hdr = (_mlib_arr_hdr_t *)resz(hdr->mem, (uint8_t *)hdr, oldsz, newsz); + hdr->cap = ncap; + return (uint8_t *)hdr + sizeof(*hdr) + pad; +} -- cgit v1.2.3