O2S C Library 1.8.2
Provide high-level data-structures and other fundamental tools for C projects
Loading...
Searching...
No Matches
memory.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* ____ _ _____ ____ _ _ _ _____ _ _ ____ ____ */
3/* / ___| / \ | ___| _ \ / \ | \ | | |_ _| || | | _ \/ ___| */
4/* \___ \ / _ \ | |_ | |_) | / _ \ | \| | | | | || |_| | | \___ \ */
5/* ___) / ___ \| _| | _ < / ___ \| |\ | | | |__ _| |_| |___) | */
6/* |____/_/ \_|_| |_| \_/_/ \_|_| \_| |_| |_| |____/|____/ */
7/* */
14/* ************************************************************************** */
15
16#include "private.h"
17
18#include "o2s/array.h"
19
20#include <stdlib.h> // reallocarray
21
23size_t array_offset(const array_t* self, size_t count)
24{
25 return (count * self->type_size);
26}
27
32static bool array_realloc(array_t* self, size_t capacity_to_alloc)
33{
34 void* new_storage = reallocarray(self->start, capacity_to_alloc, self->type_size);
35 if (new_storage == NULL)
36 return false;
37 self->start = new_storage;
38 self->capacity = capacity_to_alloc;
39 return true;
40}
41
47bool array_reserve(array_t* self, size_t count)
48{
49 const size_t wanted = self->count + count;
50 size_t required = self->capacity;
51
52 if (wanted <= self->capacity)
53 return true;
54 if (required == 0)
55 required = ARRAY_INITIAL_SIZE;
56 while (required < wanted)
57 required *= ARRAY_GROWTH_FACTOR;
58 return array_realloc(self, required);
59}
60
66{
67 return array_realloc(self, self->count);
68}
Internal state of a dynamic array.
#define ARRAY_INITIAL_SIZE
Number of elements allocated at minimum.
Definition private.h:22
#define ARRAY_GROWTH_FACTOR
Factor used to multiply the capacity with.
Definition private.h:24
Dynamic arrays.
bool array_trim(array_t *self)
Resizes the underlying storage to fit exactly the current elements count.
Definition memory.c:65
size_t array_offset(const array_t *self, size_t count)
The size in memory of count elements.
Definition memory.c:23
bool array_reserve(array_t *self, size_t count)
Ensures the array has enough capacity to fit count new elements, reallocating if needed.
Definition memory.c:47
O2S array implementation.
Definition array.h:24
void * start
Underlying storage.
Definition array.h:25
size_t type_size
Size in bytes of a single element.
Definition array.h:26
size_t count
Number of elements currently stored.
Definition array.h:27
size_t capacity
Number of elements that can fit in the storage.
Definition array.h:28