-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinebuffer.cpp
87 lines (75 loc) · 1.69 KB
/
linebuffer.cpp
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
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "linebuffer.h"
#include <Wire.h>
#include <Arduino.h>
int linebuffer_init(linebuffer_t *lb, size_t buf_len, linebuffer_per_line_func per_line_cb)
{
lb->per_line_cb = per_line_cb;
if (NULL == (lb->linebuf = (char *)malloc(buf_len+1)))
goto fail;
lb->userdata = NULL;
lb->size = buf_len;
linebuffer_reset(lb);
return 0;
fail:
return 1;
}
void linebuffer_reset(linebuffer_t *lb)
{
lb->linebuf_index = 0;
lb->linebuf[0] = 0;
}
void linebuffer_term(linebuffer_t *lb)
{
if (NULL != lb->linebuf)
free(lb->linebuf);
}
static int linebuffer_write_char(linebuffer_t *lb, char c)
{
int rc = 1;
if (c == '\n')
{
if (lb->linebuf_index < lb->size)
{
if (lb->linebuf_index && lb->linebuf[lb->linebuf_index-1] == '\r')
lb->linebuf[lb->linebuf_index-1] = 0;
lb->per_line_cb(lb, lb->linebuf, lb->userdata);
linebuffer_reset(lb);
rc = 0;
}
else
{
linebuffer_reset(lb);
}
}
else
if (lb->linebuf_index < lb->size)
{
if (isprint(c))
{
lb->linebuf[lb->linebuf_index++] = c;
lb->linebuf[lb->linebuf_index] = 0;
}
rc = 0;
}
return rc;
}
int linebuffer_write(linebuffer_t *lb, const char *buf, size_t len)
{
while(len--)
{
if (0 != linebuffer_write_char(lb, *buf++))
return 1;
}
return 0;
}
void linebuffer_set_userdata(linebuffer_t *lb, void *userdata)
{
lb->userdata = userdata;
}
void *linebuffer_get_userdata(linebuffer_t *lb)
{
return lb->userdata;
}