-
Notifications
You must be signed in to change notification settings - Fork 0
/
klinebuf.c
76 lines (64 loc) · 1.1 KB
/
klinebuf.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
74
75
76
#include "kdebug.h"
#include "klinebuf.h"
#include "kserial.h"
void LBReset(LineBuf* lbuf)
{
lbuf->m_len = 0;
lbuf->m_frozen = false;
}
int LBLength(const LineBuf* lbuf)
{
return lbuf->m_len;
}
int LBCharAt(const LineBuf* lbuf, int index)
{
KASSERT(0 <= index && index < lbuf->m_len);
return lbuf->m_buf[index] & 0xff;
}
char* LBFreeze(LineBuf* lbuf)
{
lbuf->m_frozen = true;
lbuf->m_buf[lbuf->m_len] = 0;
return lbuf->m_buf;
}
void LBErase(LineBuf* lbuf)
{
if (lbuf->m_len > 0)
--lbuf->m_len;
}
void LBPut(LineBuf* lbuf, char c)
{
if (lbuf->m_frozen)
LBReset(lbuf);
KASSERT(lbuf->m_len < sizeof(lbuf->m_buf));
lbuf->m_buf[lbuf->m_len++] = c;
}
#define ERASE 0x7f
char* LBGetLine(LineBuf* lbuf)
{
char* result = NULL;
char c;
while (result == 0 && s_read(&c, 1, 0) > 0)
{
if (c == '\r')
{
s_println("");
result = LBFreeze(lbuf);
}
else if (c == ERASE)
{
static const char erase[] = { 8, 32, 8 }; // BS, SP, BS
if (lbuf->m_len > 0)
{
s_write(erase, sizeof(erase));
LBErase(lbuf);
}
}
else
{
s_write(&c, 1);
LBPut(lbuf, c);
}
}
return result;
}