Loading...
Searching...
No Matches
memarray.h
1/*
2 * Copyright (C) 2018 Tobias Heider <heidert@nm.ifi.lmu.de>
3 * 2020 Koen Zandberg <koen@bergzand.net>
4 *
5 * This file is subject to the terms and conditions of the GNU Lesser
6 * General Public License v2.1. See the file LICENSE in the top level
7 * directory for more details.
8 */
20#ifndef MEMARRAY_H
21#define MEMARRAY_H
22
23#include <assert.h>
24#include <stdint.h>
25#include <stddef.h>
26#include <string.h>
27
28#ifdef __cplusplus
29extern "C" {
30#endif
31
35typedef struct {
36 void *free_data;
37 size_t size;
39
50
64void memarray_init(memarray_t *mem, void *data, size_t size, size_t num);
65
78static inline void *memarray_alloc(memarray_t *mem)
79{
80 assert(mem != NULL);
81
82 void *free = mem->free_data;
83 if (free) {
84 mem->free_data = *((void **)mem->free_data);
85 }
86 return free;
87}
88
99static inline void *memarray_calloc(memarray_t *mem)
100{
101 void *new = memarray_alloc(mem);
102 if (new) {
103 memset(new, 0, mem->size);
104 }
105 return new;
106}
107
117static inline void memarray_free(memarray_t *mem, void *ptr)
118{
119 assert((mem != NULL) && (ptr != NULL));
120
121 memcpy(ptr, &mem->free_data, sizeof(void *));
122 mem->free_data = ptr;
123}
124
140void memarray_extend(memarray_t *mem, void *data, size_t num);
141
152int memarray_reduce(memarray_t *mem, void *data, size_t num);
153
162
163#ifdef __cplusplus
164}
165#endif
166
167#endif /* MEMARRAY_H */
168
POSIX.1-2008 compliant version of the assert macro.
#define assert(cond)
abort the program if assertion is false
Definition assert.h:136
void free(void *ptr)
This is a no-op.
static void * memarray_alloc(memarray_t *mem)
Allocate memory chunk in memarray pool.
Definition memarray.h:78
void memarray_init(memarray_t *mem, void *data, size_t size, size_t num)
Initialize memarray pool with free list.
size_t memarray_available(memarray_t *mem)
Returns the number of blocks available.
static void * memarray_calloc(memarray_t *mem)
Allocate and clear memory chunk in memarray pool.
Definition memarray.h:99
int memarray_reduce(memarray_t *mem, void *data, size_t num)
Reduce the memarray space, subtracting the memory pool.
static void memarray_free(memarray_t *mem, void *ptr)
Free memory chunk in memarray pool.
Definition memarray.h:117
struct memarray_element memarray_element_t
Memory pool element.
void memarray_extend(memarray_t *mem, void *data, size_t num)
Extend the memarray with a new memory region.
Memory pool element.
Definition memarray.h:47
struct memarray_element * next
Pointer to the next element.
Definition memarray.h:48
Memory pool.
Definition memarray.h:35
void * free_data
memory pool data / head of the free list
Definition memarray.h:36
size_t size
size of single list element
Definition memarray.h:37