-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchar_buf.c
59 lines (45 loc) · 1023 Bytes
/
char_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
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "char_buf.h"
CharBuf *create_char_buf(size_t cap)
{
CharBuf *cv = (CharBuf *)malloc(sizeof(CharBuf));
if (cv == NULL)
{
perror("Failed to allocate CharBuf: ");
exit(1); // TODO: shutdown server properly
}
char *buf = (char *)malloc(cap);
if (cv == NULL)
{
perror("Failed to allocate CharBuf buffer: ");
exit(1); // TODO: shutdown server properly
}
cv->buf = buf;
cv->cap = cap;
cv->len = 0;
return cv;
}
void clear_char_buf(CharBuf *cv)
{
cv->len = 0;
}
int append_str_char_buf(CharBuf *cv, char *s)
{
if (strlen(s) > (cv->cap - cv->len))
return -1;
while (*s)
cv->buf[cv->len++] = *(s++);
return 0;
}
int append_bytes_char_buf(CharBuf *cv, char *b, size_t n)
{
if (n > (cv->cap - cv->len))
return -1;
int idx = 0;
while (idx < n)
cv->buf[cv->len++] = *(b + idx++);
return 0;
}