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
|
#ifndef INCLUDED_BUFFER_H
#define INCLUDED_BUFFER_H
#define BUFFER_SIZE 4096
#define BUFFER_END(BUFFER) ((BUFFER).data + BUFFER_SIZE)
#define BUFFER_SPACE_WRITE(BUFFER) (BUFFER_SIZE - ((BUFFER).head_write - (BUFFER).data))
struct buffer {
char *head_read;
char *head_write;
char data[BUFFER_SIZE];
};
void
buffer__align (struct buffer *buf)
{
if (buf->head_read == buf->data)
return;
size_t size = buf->head_write - buf->head_read;
memmove (buf->data, buf->head_read, size);
buf->head_read = buf->data;
buf->head_write = buf->data + size;
}
int
buffer__peek (struct buffer *buf, int *fd)
{
if (buf->head_read < buf->head_write)
return *buf->head_read;
buf->head_read = buf->data;
buf->head_write = buf->data;
ssize_t bytes_read = read (*fd, buf->head_write, BUFFER_SPACE_WRITE (*buf));
if (bytes_read <= 0) {
*fd = -1;
return EOF;
}
buf->head_write += bytes_read;
return *buf->head_read;
}
int
buffer__consume_one (struct buffer *buf, int *fd)
{
int c = buffer__peek (buf, fd);
if (c == EOF) return EOF;
buf->head_read += 1;
return c;
}
char *
buffer__consume_until (struct buffer *buf, int *fd, char c)
{
char *ret = buf->head_read;
for (;;) {
int r = buffer__consume_one (buf, fd);
if (r == EOF) return NULL;
if (r == c ) return ret;
}
}
char *
buffer__consume_until_one_of (struct buffer *buf, int *fd, char *cs)
{
char *ret = buf->head_read;
for (;;) {
int r = buffer__consume_one (buf, fd);
if (r == EOF) return NULL;
if (strchr (cs, r)) return ret;
}
}
char *
buffer__consume_while_one_of (struct buffer *buf, int *fd, char *cs)
{
char *ret = buf->head_read;
for (;;) {
int r = buffer__peek (buf, fd);
if (r == EOF) return NULL;
if (!strchr (cs, r)) return ret;
buffer__consume_one (buf, fd);
}
}
bool
buffer__skip_n (struct buffer *buf, int *fd, ssize_t n)
{
buffer__align (buf);
while (n > 0) {
ssize_t bytes_read = read (*fd, buf->head_write,
n > BUFFER_SPACE_WRITE (*buf)
? BUFFER_SPACE_WRITE (*buf) : n);
if (bytes_read <= 0) {
*fd = -1;
return false;
}
n -= bytes_read;
}
return true;
}
#endif // INCLUDED_BUFFER_H
|