forked from hmgle/socks5_c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.c
61 lines (54 loc) · 985 Bytes
/
buffer.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
#include "buffer.h"
struct buf *buf_create(size_t init_size)
{
struct buf *ret;
assert(init_size > 0);
ret = malloc(sizeof(*ret));
if (ret) {
ret->data = calloc(init_size, sizeof(uint8_t));
if (ret->data == NULL) {
free(ret);
return NULL;
}
ret->max = init_size;
ret->used = 0;
}
return ret;
}
void buf_release(struct buf *buf)
{
assert(buf && buf->data);
free(buf->data);
free(buf);
}
int buf_grow(struct buf *buf)
{
size_t new_size;
void *new_ptr;
if (buf->max == 0)
new_size = 1;
else
new_size = buf->max * 2;
new_ptr = realloc(buf->data, new_size);
if (new_ptr == NULL)
return -1;
buf->data = new_ptr;
buf->max = new_size;
return 0;
}
int buf_resize(struct buf *buf, size_t new_size)
{
void *new_ptr;
assert(new_size >= 0);
if (new_size == 0) {
free(buf->data);
buf->max = 0;
} else {
new_ptr = realloc(buf->data, new_size);
if (new_ptr == NULL)
return -1;
buf->data = new_ptr;
buf->max = new_size;
}
return 0;
}