aboutsummaryrefslogtreecommitdiff
path: root/lib/alloc/static_scratch_alloc.c
blob: 2489b98b29bb0514b231e255fc66b898c7fdd4cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <errno.h>
#include <setjmp.h>
#include <stdckdint.h>
#include <stdint.h>

#include "alloc.h"
#include "errors.h"

[[noreturn]] static void oom(jmp_buf *env);

void *
static_scratch_alloc(allocator_t mem, alloc_mode_t mode, void *,
					 ptrdiff_t, ptrdiff_t newnmemb, ptrdiff_t elemsz,
					 ptrdiff_t align) 
{
	st_buf_t *ctx = mem.ctx;
	
	switch (mode) {
	case ALLOC_NEW:
	case ALLOC_RESIZE:
		ptrdiff_t pad, avail, total;
		if (ckd_mul(&total, newnmemb, elemsz))
			oom(mem.err);
		pad = -(uintptr_t)ctx->buf & (align - 1);
		avail = ctx->len - pad;
		if (avail < 0 || total > avail)
			oom(mem.err);
		return (char *)ctx->buf + pad;
	case ALLOC_FREE:
	case ALLOC_FREEALL:
		return nullptr;
	default:
		unreachable();
	}
}

void
oom(jmp_buf *env)
{
	errno = ENOMEM;
	if (env != nullptr)
		longjmp(*env, 1);
	err("static_scratch_alloc:");
}