-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjak_da.c
105 lines (61 loc) · 1.5 KB
/
jak_da.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
#include "jak_da.h"
#include "jak_dbg.h"
#include <stdlib.h>
#include <string.h>
jak_da_t * jak_da_new( unsigned int initial_size, float growth_factor, unsigned int el_size ) {
jak_da_t * a;
if( growth_factor == -1.0f ) growth_factor = 1.618f;
check( growth_factor > 1.0f, final_cleanup );
a = malloc( sizeof( jak_da_t ) );
check( a, final_cleanup );
a->el = malloc( initial_size * el_size );
check( a->el, a_cleanup );
a->len = 0;
a->max_len = initial_size;
a->factor = growth_factor;
a->el_size = el_size;
return a;
a_cleanup:
free( a );
final_cleanup:
return NULL;
}
int jak_da_push( jak_da_t * a, void * el ) {
int rc;
rc = jak_da_resize( a, a->len + 1 );
check( rc == 0, final_cleanup );
memcpy( (char *)a->el + ( a->len - 1 ) * a->el_size, el, a->el_size );
return 0;
final_cleanup:
return -1;
}
void jak_da_free( jak_da_t * a ) {
if( a ) {
free( a->el );
free( a );
}
}
int jak_da_resize( jak_da_t * a, unsigned int i ) {
unsigned int new_len;
void * tmp;
if( i > 0 && ( i > a->max_len || (float)( i ) * a->factor < a->max_len ) ) {
new_len = i * a->factor;
tmp = realloc( a->el, new_len * a->el_size );
check( tmp, final_cleanup );
a->el = tmp;
a->max_len = new_len;
}
a->len = i;
return 0;
final_cleanup:
return -1;
}
int jak_da_pop( jak_da_t * a ) {
check( a->len > 0, final_cleanup );
return jak_da_resize( a, a->len - 1 );
final_cleanup:
return -1;
}
void jak_da_zero_out( jak_da_t * a ) {
memset( a->el, 0, a->el_size * a->len );
}