-
Notifications
You must be signed in to change notification settings - Fork 3
/
bsreader.c
104 lines (85 loc) · 1.73 KB
/
bsreader.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stddef.h>
#include <stdlib.h>
#include <bsreader.h>
#include <bstree.h>
#define MAX_LITERAL_SIZE 512
typedef struct
{
unsigned char* byte;
unsigned char bit;
char literal[ MAX_LITERAL_SIZE ];
}
stream_t;
static int getbit( stream_t* stream )
{
int bit = *stream->byte & stream->bit ? 1 : 0;
stream->bit >>= 1;
if ( !stream->bit )
{
stream->bit = 128;
stream->byte++;
}
return bit;
}
static int getbyte( stream_t* stream )
{
int byte = 0, i;
for ( i = 0; i < 8; i++ )
{
byte = byte << 1 | getbit( stream );
}
return byte;
}
static size_t getliteral( stream_t* stream, char* literal, size_t size )
{
int byte;
char* begin = literal;
char* end = literal + size;
if ( stream->bit == 128 )
{
getbit( stream );
}
do
{
byte = getbyte( stream );
*literal++ = byte;
}
while ( byte && literal < end );
return literal - begin - 1;
}
const char* bsread( lua_State* L, void* data, size_t* size )
{
(void)L;
stream_t* stream = (stream_t*)data;
int bit;
const char* literal;
const bsnode_t* node = BS_ROOT;
while ( node->token == -1 )
{
bit = getbit( stream );
node = bit ? node->right : node->left;
}
if ( node->token == BS_LITERAL )
{
literal = stream->literal;
*size = getliteral( stream, stream->literal, sizeof( stream->literal ) );
}
else if ( node->token != BS_EOF )
{
literal = tokens[ node->token ].literal;
*size = tokens[ node->token ].len;
}
else
{
literal = NULL;
*size = 0;
}
return literal;
}
void* bsnew( void* data )
{
stream_t* stream = (stream_t*)malloc( sizeof( *stream ) );
stream->byte = (unsigned char*)data;
stream->bit = 128;
return (void*)stream;
}