-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytearray.c
130 lines (93 loc) · 2.09 KB
/
bytearray.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
129
#include "bytearray.h"
#include "panic.h"
#include <stdlib.h>
#include <strings.h>
#include <assert.h>
#include <string.h>
static inline int max(int a, int b)
{
return a > b ? a : b;
}
struct byte_array * byte_array_new(int capacity)
{
struct byte_array *b;
b = malloc(sizeof *b);
b->capacity = capacity;
b->size = 0;
b->data = calloc(capacity, sizeof (char));
b->end = b->data;
bzero(b->data, capacity * sizeof (char));
return b;
}
void byte_array_free(struct byte_array *b)
{
free(b->data);
free(b);
}
void byte_array_append(struct byte_array *b, const char *data, size_t size)
{
size_t new_size;
if (size <= 0)
return;
new_size = b->size + size;
if (new_size > b->capacity)
byte_array_resize(b, max(new_size + 1, b->capacity << 1));
memcpy(b->end, data, size);
b->end += size;
b->size += size;
}
void byte_array_append_char(struct byte_array *b, char ch)
{
byte_array_append(b, &ch, 1);
}
void byte_array_push(struct byte_array *b, char ch)
{
byte_array_append(b, &ch, 1);
}
void byte_array_resize(struct byte_array *b, size_t capacity)
{
char *ptr;
size_t old_capacity;
assert(capacity > 0);
ptr = (char *) realloc(b->data, capacity);
if (ptr == NULL)
panic("Not enough memory");
b->data = ptr;
old_capacity = b->capacity;
b->capacity = capacity;
if (b->size > capacity) {
b->size = capacity;
} else if (b->capacity > old_capacity) {
bzero((b->data + old_capacity), capacity - old_capacity);
}
b->end = b->data + b->size;
}
char byte_array_pop(struct byte_array *b)
{
if (b->size == 0)
return 0;
char ch = *(b->end);
*(b->end) = 0;
b->end--;
b->size--;
return ch;
}
char * byte_array_data(struct byte_array *b)
{
return b->data;
}
char * byte_array_detach(struct byte_array *b)
{
char *data;
data = b->data;
free(b);
return data;
}
size_t byte_array_size(struct byte_array *b)
{
return b->size;
}
size_t byte_array_capacity(struct byte_array *b)
{
return b->capacity;
}