-
Notifications
You must be signed in to change notification settings - Fork 1
/
buf.c
121 lines (85 loc) · 1.93 KB
/
buf.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
#include <stdio.h>
#include <string.h>
#include "buf.h"
buf_t *buf_alloc(size_t size) {
buf_t *b;
b = (buf_t *)calloc(1, sizeof(buf_t) + size);
b->size = size;
return b;
}
void buf_free(buf_t *b) {
free(b);
}
void buf_clear(buf_t *b) {
b->len = 0;
b->read_offset = 0;
memset(b->data, 0, b->size);
}
size_t buf_size(buf_t *b) {
return b->size;
}
size_t buf_avail(buf_t *b) {
return b->size - b->len;
}
size_t buf_len(buf_t *b) {
return b->len;
}
int buf_append(buf_t *b, unsigned char *data, size_t len) {
if(buf_avail(b) < len)
return -1;
memmove(b->data + b->len, data, len);
b->len += len;
return 0;
}
int buf_append_u8(buf_t *b, unsigned char value) {
return buf_append(b, &value, 1);
}
int buf_append_u16(buf_t *b, unsigned short value) {
unsigned char buf[2];
buf[0] = (value >> 8) & 0xff;
buf[1] = (value >> 0) & 0xff;
return buf_append(b, buf, 2);
}
int buf_append_u24(buf_t *b, unsigned int value) {
unsigned char buf[3];
buf[0] = (value >> 16) & 0xff;
buf[1] = (value >> 8) & 0xff;
buf[2] = (value >> 0) & 0xff;
return buf_append(b, buf, 3);
}
int buf_append_u32(buf_t *b, unsigned int value) {
unsigned char buf[4];
buf[0] = (value >> 24) & 0xff;
buf[1] = (value >> 16) & 0xff;
buf[2] = (value >> 8) & 0xff;
buf[3] = (value >> 0) & 0xff;
return buf_append(b, buf, 4);
}
unsigned char *buf_ptr(buf_t *b) {
return b->data + b->len;
}
unsigned char *buf_read_next(buf_t *b, size_t len, size_t *limit) {
unsigned char *p;
if(b->len - b->read_offset < len)
return NULL;
if(limit) {
if(len > *limit)
return NULL;
*limit -= len;
}
p = b->data + b->read_offset;
b->read_offset += len;
return p;
}
void buf_read_done(buf_t *b) {
b->len -= b->read_offset;
memmove(b->data, b->data + b->read_offset, b->len);
b->read_offset = 0;
}
unsigned char *buf_peek(buf_t *b, size_t offset, size_t len) {
unsigned char *p;
if(offset + len > b->len)
return NULL;
p = b->data + offset;
return p;
}