memarray.h
1 /*
2  * SPDX-FileCopyrightText: 2018 Tobias Heider <heidert@nm.ifi.lmu.de>
3  * SPDX-FileCopyrightText: 2020 Koen Zandberg <koen@bergzand.net>
4  * SPDX-License-Identifier: LGPL-2.1-only
5  */
6 
7 #pragma once
8 
20 #include <assert.h>
21 #include <stdint.h>
22 #include <stddef.h>
23 #include <string.h>
24 
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
32 typedef struct {
33  void *free_data;
34  size_t size;
35 } memarray_t;
36 
44 typedef struct memarray_element {
47 
61 void memarray_init(memarray_t *mem, void *data, size_t size, size_t num);
62 
75 static inline void *memarray_alloc(memarray_t *mem)
76 {
77  assert(mem != NULL);
78 
79  void *free = mem->free_data;
80  if (free) {
81  mem->free_data = *((void **)mem->free_data);
82  }
83  return free;
84 }
85 
96 static inline void *memarray_calloc(memarray_t *mem)
97 {
98  void *new = memarray_alloc(mem);
99  if (new) {
100  memset(new, 0, mem->size);
101  }
102  return new;
103 }
104 
114 static inline void memarray_free(memarray_t *mem, void *ptr)
115 {
116  assert((mem != NULL) && (ptr != NULL));
117 
118  memcpy(ptr, &mem->free_data, sizeof(void *));
119  mem->free_data = ptr;
120 }
121 
137 void memarray_extend(memarray_t *mem, void *data, size_t num);
138 
149 int memarray_reduce(memarray_t *mem, void *data, size_t num);
150 
159 
160 #ifdef __cplusplus
161 }
162 #endif
163 
POSIX.1-2008 compliant version of the assert macro.
#define assert(cond)
abort the program if assertion is false
Definition: assert.h:143
void free(void *ptr)
This is a no-op.
static void * memarray_calloc(memarray_t *mem)
Allocate and clear memory chunk in memarray pool.
Definition: memarray.h:96
static void * memarray_alloc(memarray_t *mem)
Allocate memory chunk in memarray pool.
Definition: memarray.h:75
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.
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:114
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:44
struct memarray_element * next
Pointer to the next element.
Definition: memarray.h:45
Memory pool.
Definition: memarray.h:32
void * free_data
memory pool data / head of the free list
Definition: memarray.h:33
size_t size
size of single list element
Definition: memarray.h:34