-
Notifications
You must be signed in to change notification settings - Fork 10
/
stream.c
118 lines (96 loc) · 1.62 KB
/
stream.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "stream.h"
void
sinit(struct stream *s, char const *buf, size_t buflen, enum endianness endian)
{
s->buf = buf;
s->len = buflen;
s->endian = endian;
}
bool
sskip(struct stream *s, size_t count)
{
if (count > s->len) {
s->len = 0;
return false;
}
s->buf += count;
s->len -= count;
return true;
}
bool
sread(struct stream *s, void *buf, size_t count)
{
void const *d = s->buf;
if (!sskip(s, count)) {
return false;
}
memcpy(buf, d, count);
return true;
}
uint8_t
read_uint8(struct stream *s)
{
uint8_t *d = (uint8_t *) s->buf;
if (!sskip(s, 1)) {
return 0;
}
return d[0];
}
uint16_t
read_uint16be(struct stream *s)
{
uint8_t *d = (uint8_t *) s->buf;
if (!sskip(s, 2)) {
return 0;
}
return ((d[0] << 8) | (d[1] << 0));
}
uint16_t
read_uint16le(struct stream *s)
{
uint8_t *d = (uint8_t *) s->buf;
if (!sskip(s, 2)) {
return 0;
}
return ((d[0] << 0) | (d[1] << 8));
}
uint16_t
read_uint16(struct stream *s)
{
if (s->endian == ENDIAN_BIG) {
return read_uint16be(s);
} else {
return read_uint16le(s);
}
}
uint32_t
read_uint32be(struct stream *s)
{
uint8_t *d = (uint8_t *) s->buf;
if (!sskip(s, 4)) {
return 0;
}
return ((d[0] << 24) | (d[1] << 16) | (d[2] << 8) | (d[3] << 0));
}
uint32_t
read_uint32le(struct stream *s)
{
uint8_t *d = (uint8_t *) s->buf;
if (!sskip(s, 4)) {
return 0;
}
return ((d[0] << 0) | (d[1] << 8) | (d[2] << 16) | (d[3] << 24));
}
uint32_t
read_uint32(struct stream *s)
{
if (s->endian == ENDIAN_BIG) {
return read_uint32be(s);
} else {
return read_uint32le(s);
}
}