-
Notifications
You must be signed in to change notification settings - Fork 3
/
buffer.c
73 lines (61 loc) · 1.27 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
#include "buffer.h"
/**
* Create a buffer of given size.
*/
struct buffer *
buffer_create(size_t size)
{
struct buffer *buf = malloc(sizeof(*buf));
if (!buf)
return NULL;
buf->start = malloc(size);
if (!buf->start) {
free(buf);
return NULL;
}
buf->pos = buf->start;
buf->last = buf->start;
buf->end = buf->start + size;
return buf;
}
/**
* Shrink the buffer.
*
* Move string to starting point of buffer.
*/
void
buffer_shrink(struct buffer *buf)
{
memmove(buf->start, buf->pos, buf->last - buf->pos);
buf->last = buf->start + (buf->last - buf->pos);
buf->pos = buf->start;
}
/**
* Grow buffer extra size.
*/
int
buffer_grow(struct buffer *buf, size_t extra)
{
if (extra <= 0)
return 0;
size_t size = buffer_capacity(buf) + extra;
size_t pos_off = buf->pos - buf->start;
size_t last_off = buf->last - buf->start;
buf->start = realloc(buf->start, size);
if (buf->start == NULL)
return -1;
buf->pos = buf->start + pos_off;
buf->last = buf->start + last_off;
buf->end = buf->start + size;
return 0;
}
/**
* Delete the buffer.
*/
void
buffer_delete(struct buffer *buf)
{
if (buf->start) free(buf->start);
buf->start = NULL;
free(buf);
}