blob: e8ba5d99cecb1b959cd56da809d001dc2bce7d2f (
plain)
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
|
// Copyright (c) 2018-2026 Jean-Philippe Bruyère <jp_bruyere@hotmail.com>
//
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
#include <stddef.h>
#define CTOR_ARRAY_EXP(type, expansion) \
typedef struct { \
uint32_t count; \
uint32_t size; \
type *elements; \
} array_##type; \
static array_##type array_create_##type (uint32_t reservedSize) { \
type *elts = (type*)malloc(reservedSize * sizeof(type)); \
return (array_##type) {0, reservedSize, elts}; \
} \
static int array_add_##type (array_##type* arr, type elt) { \
if (arr->size <= arr->count) { \
uint32_t newSize = arr->size expansion; \
type *elts = (type*)realloc(arr->elements, newSize * sizeof(type)); \
if (elts == NULL) \
return -1; \
arr->elements = elts; \
arr->size = newSize; \
} \
arr->elements[arr->count++] = elt; \
return arr->count - 1; \
} \
static type* array_last_##type (array_##type* arr) { \
if (!arr->count) \
return NULL; \
return &arr->elements[arr->count - 1]; \
} \
static void array_destroy_##type (array_##type* arr) { \
if (arr && arr->size > 0) { \
free(arr->elements); \
arr->elements = NULL; \
arr->count = 0; \
arr->size = 0; \
} \
}
#define ARRAY_DEL_ELT(type) \
static void array_del_##type (array_##type* arr, type elt) { \
uint32_t i; \
for (i = 0; i < arr->count; i++) { \
if (arr->elements[i] == elt) \
break; \
} \
if (i == arr->count) { \
return; \
} \
if (i < arr->count - 1) \
memmove (&arr->elements[i], &arr->elements[i + 1], (arr->count - i - 1) * sizeof(type)); \
arr->count--; \
}
#define CTOR_ARRAY(type) CTOR_ARRAY_EXP(type,* 2)
#endif
|