-
Notifications
You must be signed in to change notification settings - Fork 11
/
c-shared-varray.c
128 lines (103 loc) · 2.22 KB
/
c-shared-varray.c
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* Dynamically growing array implementation
*
* Copyright (C) Navaneeth.K.N
*
* This is part of libvarnam licensed under MPL-2.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "c-shared-varray.h"
#include "c-shared-util.h"
varray*
varray_init()
{
varray *array = (varray*) malloc (sizeof(varray));
array->memory = NULL;
array->allocated = 0;
array->used = 0;
array->index = -1;
return array;
}
void
varray_push(varray *array, void *data)
{
size_t toallocate;
size_t size = sizeof(void*);
if (data == NULL) return;
if ((array->allocated - array->used) < size) {
toallocate = array->allocated == 0 ? size : (array->allocated * 2);
array->memory = realloc(array->memory, toallocate);
array->allocated = toallocate;
}
array->memory[++array->index] = data;
array->used = array->used + size;
}
int
varray_length(varray *array)
{
if (array == NULL)
return 0;
return array->index + 1;
}
bool
varray_is_empty (varray *array)
{
return (varray_length (array) == 0);
}
void
varray_clear(varray *array)
{
int i;
for(i = 0; i < varray_length(array); i++)
{
array->memory[i] = NULL;
}
array->used = 0;
array->index = -1;
}
void
varray_free(varray *array, void (*destructor)(void*))
{
int i;
void *item;
if (array == NULL)
return;
if (destructor != NULL)
{
for(i = 0; i < varray_length(array); i++)
{
item = varray_get (array, i);
if (item != NULL) destructor(item);
}
}
if (array->memory != NULL)
free(array->memory);
free(array);
}
void*
varray_get(varray *array, int index)
{
if (index < 0 || index > array->index)
return NULL;
assert(array->memory);
return array->memory[index];
}
void
varray_insert(varray *array, int index, void *data)
{
if (index < 0 || index > array->index)
return;
array->memory[index] = data;
}
bool
varray_exists (varray *array, void *item, bool (*equals)(void *left, void *right))
{
int i;
for (i = 0; i < varray_length (array); i++)
{
if (equals(varray_get (array, i), item))
return true;
}
return false;
}