-
Notifications
You must be signed in to change notification settings - Fork 4
/
sbuf.c
63 lines (55 loc) · 1.03 KB
/
sbuf.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
/*
* sbuf.c -- String buffer routines
*
* Copyright 2008 Dale Schumacher. ALL RIGHTS RESERVED.
*/
#include "sbuf.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
SBUF*
new_sbuf(size_t size)
{
SBUF* sbuf = (SBUF*)malloc(sizeof(SBUF));
assert(sbuf != NULL);
sbuf->limit = size - 1;
sbuf->offset = 0;
sbuf->buf = (char*)malloc(size);
return sbuf;
}
void
clear_sbuf(SBUF* sbuf)
{
sbuf->offset = 0;
strncpy(sbuf->buf, "", sbuf->limit + 1);
}
SBUF*
free_sbuf(SBUF* sbuf)
{
free(sbuf->buf);
free(sbuf);
return NULL;
}
void
sbuf_emit(char c, void* ctx)
{
SBUF* sbuf = (SBUF*)ctx;
if (sbuf->offset < sbuf->limit) {
sbuf->buf[sbuf->offset] = c;
++sbuf->offset;
sbuf->buf[sbuf->offset] = '\0';
}
}
void
sbuf_emits(char* s, size_t n, void* ctx)
{
char c;
SBUF* sbuf = (SBUF*)ctx;
if ((sbuf->offset + n) < sbuf->limit) {
while ((c = *s++) && (n-- > 0)) {
sbuf->buf[sbuf->offset] = c;
++sbuf->offset;
}
sbuf->buf[sbuf->offset] = '\0';
}
}