From 0a1b15b307c3194c8da703a3ba832ed9277b4c72 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Fri, 6 Nov 2026 05:56:27 +0300 Subject: feat(bump): add bump allocator --- src/bump.c | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/bump.c (limited to 'src/bump.c') diff --git a/src/bump.c b/src/bump.c new file mode 100644 index 0000000..f1522ab --- /dev/null +++ b/src/bump.c @@ -0,0 +1,82 @@ +// bump.c --- bump allocator -*- C -*- +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// This file is part of COSMOS Codebase. +// +// Commentary: +// +// Code: + +#include "bump.h" +#include "dbg.h" +#include "gpa.h" +#include "macros.h" +#include "bits.h" + +#include // TEMP(cmmm): remove libc dep + +#ifndef BUMP_NO_FEAT_GPA + +void * +gpa_fun_bump (void *_ctx, void *ptr, usz old_sz, usz new_sz, usz spec) +{ + DBG_ASSERT_NN (_ctx); + + struct buf *buf = _ctx; + DBG_ASSERT_BUF (*buf); + + // drop + if (!new_sz) { + // reclaim if last allocation + if (ptr + old_sz == buf->ptr) + buf->ptr = ptr; + + return ptr; + } + + // in-place resize + if (ptr + old_sz == buf->ptr) { + void *new_head = buf->ptr + new_sz - old_sz; + if (UNLIKELY (new_head > (void *) buf->end)) + return NULL; + buf->ptr = new_head; + return ptr; + } + + void *new_head = ALIGN_UPTO (buf->ptr, GPA_ALIGN_MASK & spec); + void *ret = new_head; + new_head += new_sz; + if (UNLIKELY (new_head > (void *) buf->end)) + return NULL; + + buf->ptr = new_head; + + if (ptr) { + if (new_sz > old_sz) { + memcpy (ret, ptr, old_sz); + if (spec & GPA_ZI) + memset (ret + old_sz, 0, new_sz - old_sz); + } else { + memcpy (ret, ptr, new_sz); + } + } else if (spec & GPA_ZI) { + memset (ret, 0, new_sz); + } + + return ret; +} + +struct gpa +gpa_from_bump (struct bump *bump) +{ + DBG_ASSERT_NN ( bump); + // DBG_ASSERT_BUMP (*bump); + return gpa_from (gpa_fun_bump, bump); +} + +#endif // BUMP_NO_FEAT_GPA + +// bump.c ends here -- cgit v1.3.1