-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.c
66 lines (55 loc) · 1.13 KB
/
vector.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
#include <stdlib.h>
#include <stdint.h>
#include "vector.h"
vector *new_vector_sized(uint64_t size)
{
vector *new = (vector *)malloc(sizeof(vector));
new->length = 0;
new->size = 128;
new->items = malloc(size * sizeof(int));
return new;
}
vector *new_vector()
{
return new_vector_sized(VEC_ALLOC_SIZE);
}
void free_vector(vector *v)
{
free(v->items);
free(v);
}
int vector_at(vector *v, uint64_t i, int32_t *ret)
{
if (i < 0 || i > v->length)
return 0;
else
{
*ret = v->items[i];
return 1;
}
}
int vector_set(vector *v, uint64_t i, int32_t val)
{
if (i >= v->size)
{
uint64_t new_len = v->size;
while (i > new_len)
{
new_len *= 2;
}
v->items = realloc(v->items, new_len * sizeof(int32_t));
if (v->items == NULL)
return 0;
}
v->items[i] = val;
return 1;
}
void vector_push(vector *v, int32_t val)
{
if (v->length + 1 >= v->size)
{
// Reallocate memory
v->items = realloc(v->items, (v->size * 2) * sizeof(int32_t));
}
v->items[v->length++] = val;
}