-
Notifications
You must be signed in to change notification settings - Fork 45
/
buffer.c
133 lines (107 loc) · 2.66 KB
/
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
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
130
131
132
133
// copied from github.com/mreiferson/libevbuffsock
// (same original author as libnsq)
#include "evbuffsock.h"
#ifdef DEBUG
#define _DEBUG(...) fprintf(stdout, __VA_ARGS__)
#else
#define _DEBUG(...) do {;} while (0)
#endif
struct Buffer *new_buffer(size_t length, size_t capacity)
{
struct Buffer *buf;
buf = malloc(sizeof(struct Buffer));
buf->orig = malloc(length);
buf->data = buf->orig;
buf->offset = 0;
buf->length = length;
buf->capacity = capacity;
return buf;
}
void free_buffer(struct Buffer *buf)
{
if (buf) {
free(buf->orig);
free(buf);
}
}
void buffer_reset(struct Buffer *buf)
{
buf->data = buf->orig;
buf->offset = 0;
}
int buffer_expand(struct Buffer *buf, size_t need)
{
size_t pos = buf->data - buf->orig;
size_t expand = 0;
size_t new_size = 0;
_DEBUG("%s: need %lu, pos %lu\n", __FUNCTION__, need, pos);
if (need <= pos) {
_DEBUG("%s: re-aligning\n", __FUNCTION__);
// re-align
memmove(buf->orig, buf->data, buf->offset);
buf->data = buf->orig;
return 1;
}
expand = buf->length;
while (expand < need) {
expand = expand * 2;
}
_DEBUG("%s: expanding by %lu\n", __FUNCTION__, expand);
new_size = buf->length + expand;
if (buf->capacity > 0 && new_size > buf->capacity) {
return 0;
}
buf->orig = realloc(buf->orig, new_size);
buf->data = buf->orig + pos;
buf->length = new_size;
return 1;
}
int buffer_add(struct Buffer *buf, const void *source, size_t length)
{
size_t used = buf->data - buf->orig + buf->offset;
int32_t need = used + length - buf->length;
_DEBUG("%s: adding %lu - used %lu, need %d\n", __FUNCTION__, length, used, need);
if (need > 0) {
if (!buffer_expand(buf, need)) {
return 0;
}
}
memcpy(buf->data + buf->offset, source, length);
buf->offset += length;
return 1;
}
void buffer_drain(struct Buffer *buf, size_t length)
{
if (length >= buf->offset) {
buffer_reset(buf);
} else {
buf->data += length;
buf->offset -= length;
}
}
int buffer_read_fd(struct Buffer *buf, int fd)
{
int n;
int need;
if (ioctl(fd, FIONREAD, &n) == -1 || n > 4096) {
n = 4096;
}
need = n - BUFFER_AVAILABLE(buf);
if (need > 0 && !buffer_expand(buf, need)) {
return -1;
}
n = recv(fd, buf->data + buf->offset, n, 0);
if (n > 0) {
buf->offset += n;
}
return n;
}
int buffer_write_fd(struct Buffer *buf, int fd)
{
int n;
n = send(fd, buf->data, buf->offset, 0);
if (n > 0) {
buffer_drain(buf, n);
}
return n;
}