~nytpu/arena.c

arena.c/arena.h -rw-r--r-- 2.4 KiB
aec3da0bnytpu fix license issue 7 months ago
                                                                                
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// VERSION: 3.0.0
/* This file provides an implementation of an arena allocator that allows for
 * many allocations, which are then freed all at once.  It is particularly
 * useful for functions with lots of temporary allocations (string parsing and
 * modification?) as you don't have to keep track of every little allocation,
 * and can instead free all memory used afterwards.
 *
 * This implementation is very loosely based off of Zig's arena allocator:
 * https://github.com/ziglang/zig/blob/master/lib/std/heap/arena_allocator.zig
 *
 *
 * Copyright (c) 2021 nytpu <alex [at] nytpu.com>
 * SPDX-License-Identifier: MPL-2.0
 * The orginal source for this file is available at <https://git.sr.ht/~nytpu/arena.c>.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
 */

#pragma once
#ifndef SMOLLIBS_ARENA_H
#define SMOLLIBS_ARENA_H

#include <stddef.h>

// The arena type
typedef struct arena  arena;

// Initialize a new arena and return it.  Allows you to provide your own
// calloc, realloc, and free implementations.  If any of the three function
// pointers are NULL, then the function used will be the default.  Returns NULL
// on failure.
arena *arena_init_with_allocator(
	void *(*calloc)(size_t, size_t),
	void *(*realloc)(void *, size_t),
	void (*free)(void *)
);

// Initialize a new arena and return it.  Uses the default allocation functions
// from stdlib.h.  Returns NULL on failure.
arena *arena_init(void);

// Completely free all data in a given arena.  Will set *a to NULL to help
// prevent reuse.
void arena_deinit(arena **);

// Clear all allocations in an arena but do not free memory allocated from the
// host system; making an arena suitable for reuse without having to incur
// deallocation and reallocation overhead.  The memory IS NOT ZEROED.
void arena_clear(arena *);

// Allocate data of size in an arena.  Returns NULL on allocation failure.
// Existing data will not be modified if allocation fails.
void *arena_alloc(arena *, size_t size);

// Sensible default on most modern operating systems, probably don't need to
// change.  The page size will be autodetected on POSIX systems and Windows, so
// you also don't need to modify this for those systems either.
#define ARENA_DEFAULT_PAGE_SIZE 4096U

#endif // SMOLLIBS_ARENA_H