summaryrefslogtreecommitdiff
path: root/src/ser.c
blob: 998c81bd4f2bfa54ab45d87571d6f93fb2cd4878 (plain)
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
119
#include <stdlib.h>
#include <string.h>
#include <endian.h>
#include "ser.h"

void ser_bytes(strbuf *w, size_t len, uint8_t *x)
{
	while (w->buf.len + len > w->cap)
		w->buf.data = realloc(w->buf.data, w->cap = w->cap ? w->cap * 2 : 1);
	memcpy(w->buf.data, x, len);
	w->buf.len += len;
}

void ser_str(strbuf *w, str x)
{
	ser_u16(w, x.len);
	ser_bytes(w, x.len, (uint8_t *) x.data);
}

void ser_u8(strbuf *w, uint8_t x)
{
	ser_bytes(w, 1, &x);
}

void ser_u16(strbuf *w, uint16_t x)
{
	x = htole16(x);
	ser_bytes(w, 2, (uint8_t *) &x);
}

void ser_u32(strbuf *w, uint32_t x)
{
	x = htole32(x);
	ser_bytes(w, 4, (uint8_t *) &x);
}

void ser_u64(strbuf *w, uint64_t x)
{
	x = htole64(x);
	ser_bytes(w, 8, (uint8_t *) &x);
}

#define SER_SIGN(N) void ser_i##N(strbuf *w, int##N##_t x) { ser_u##N(w, x); };

SER_SIGN(16)
SER_SIGN(32)
SER_SIGN(64)

#undef SER_SIGN

bool deser_bytes(str *r, size_t len, uint8_t *buf)
{
	if (len > r->len)
		return false;

	memcpy(buf, r->data, len);
	*r = str_advance(*r, len);
	return true;
}

bool deser_str(str *r, str *buf)
{
	uint16_t len;
	if (!deser_u16(r, &len))
		return false;

	if (len > r->len)
		return false;

	*buf = (str) { len, r->data };
	*r = str_advance(*r, len);
	return true;
}

bool deser_u8(str *r, uint8_t *buf)
{
	return deser_bytes(r, 1, buf);
}

bool deser_u16(str *r, uint16_t *buf)
{
	if (!deser_bytes(r, 2, (uint8_t *) buf))
		return false;
	*buf = le16toh(*buf);
	return true;
}

bool deser_u32(str *r, uint32_t *buf)
{
	if (!deser_bytes(r, 4, (uint8_t *) buf))
		return false;
	*buf = le32toh(*buf);
	return true;
}

bool deser_u64(str *r, uint64_t *buf)
{
	if (!deser_bytes(r, 8, (uint8_t *) buf))
		return false;
	*buf = le64toh(*buf);
	return true;
}

#define DESER_SIGN(N) \
	bool deser_i##N(str *r, int##N##_t *buf) \
	{ \
		uint##N##_t x; \
		if (!deser_u##N(r, &x)) \
			return false; \
		*buf = x; \
		return true; \
	}

DESER_SIGN(8)
DESER_SIGN(16)
DESER_SIGN(32)
DESER_SIGN(64)

#undef DESER_SIGN