-
Notifications
You must be signed in to change notification settings - Fork 0
/
lhs_buf.c
90 lines (77 loc) · 1.82 KB
/
lhs_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
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
86
87
88
89
90
#include "lhs_buf.h"
#include "lhs_vm.h"
static int lhsbuf_grow(void* vm, LHSBuf* buf, size_t nsize)
{
if (buf->data == buf->buf)
{
buf->data = lhsmem_newobject(vm, nsize);
memcpy(buf->data, buf->buf, buf->usize);
}
else
{
buf->data = lhsmem_renewobject(vm, buf->data, buf->size, nsize);
}
buf->size = nsize;
return LHS_TRUE;
}
int lhsbuf_init(void* vm, LHSBuf* buf)
{
buf->usize = 0;
buf->size = sizeof(buf->buf);
buf->data = buf->buf;
return LHS_TRUE;
}
int lhsbuf_reset(void* vm, LHSBuf* buf)
{
buf->usize = 0;
return LHS_TRUE;
}
int lhsbuf_pushc(void* vm, LHSBuf* buf, char c)
{
if (buf->usize + sizeof(char) >= buf->size)
{
lhsbuf_grow(vm, buf, buf->size << 1);
}
buf->data[buf->usize++] = c;
buf->data[buf->usize] = 0;
return LHS_TRUE;
}
int lhsbuf_pushi(void* vm, LHSBuf* buf, int i)
{
return lhsbuf_pushls(vm, buf, (const char*)&i, sizeof(i));
}
int lhsbuf_pushl(void* vm, LHSBuf* buf, long long l)
{
return lhsbuf_pushls(vm, buf, (const char*)&l, sizeof(l));
}
int lhsbuf_pushf(void* vm, LHSBuf* buf, double n)
{
return lhsbuf_pushls(vm, buf, (const char*)&n, sizeof(n));
}
int lhsbuf_pushls(void* vm, LHSBuf* buf, const char* str, size_t l)
{
if (buf->usize + l + sizeof(char) >= buf->size)
{
lhsbuf_grow
(
vm,
buf,
((buf->usize + l + sizeof(char)) &
~(sizeof(buf->buf) - sizeof(char))) +
sizeof(buf->buf)
);
}
memcpy(buf->data + buf->usize, str, l);
buf->usize += l;
buf->data[buf->usize] = 0;
return LHS_TRUE;
}
void lhsbuf_uninit(void* vm, LHSBuf* buf)
{
if (buf->data != buf->buf)
{
lhsmem_freeobject(vm, buf->data, buf->size);
}
buf->size = 0;
buf->usize = 0;
}