diff options
Diffstat (limited to 'src/ser.c')
-rw-r--r-- | src/ser.c | 45 |
1 files changed, 30 insertions, 15 deletions
@@ -7,52 +7,58 @@ #include <endian.h> #include "ser.h" -void ser_bytes(strbuf *w, size_t len, uint8_t *x) +void ser_bytes(strbuf *w, void *x, size_t len) { - 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; + while (w->len + len > w->cap) + w->data = realloc(w->data, w->cap = w->cap ? w->cap * 2 : 1); + memcpy(w->data + w->len, x, len); + w->len += len; +} + +void ser_bool(strbuf *w, bool x) +{ + ser_u8(w, x); } void ser_str(strbuf *w, str x) { ser_u16(w, x.len); - ser_bytes(w, x.len, (uint8_t *) x.data); + ser_bytes(w, x.data, x.len); } void ser_u8(strbuf *w, uint8_t x) { - ser_bytes(w, 1, &x); + ser_bytes(w, &x, 1); } void ser_u16(strbuf *w, uint16_t x) { x = htole16(x); - ser_bytes(w, 2, (uint8_t *) &x); + ser_bytes(w, &x, 2); } void ser_u32(strbuf *w, uint32_t x) { x = htole32(x); - ser_bytes(w, 4, (uint8_t *) &x); + ser_bytes(w, &x, 4); } void ser_u64(strbuf *w, uint64_t x) { x = htole64(x); - ser_bytes(w, 8, (uint8_t *) &x); + ser_bytes(w, &x, 8); } #define SER_SIGN(N) void ser_i##N(strbuf *w, int##N##_t x) { ser_u##N(w, x); }; +SER_SIGN(8) SER_SIGN(16) SER_SIGN(32) SER_SIGN(64) #undef SER_SIGN -bool deser_bytes(str *r, size_t len, uint8_t *buf) +bool deser_bytes(str *r, void *buf, size_t len) { if (len > r->len) return false; @@ -62,6 +68,15 @@ bool deser_bytes(str *r, size_t len, uint8_t *buf) return true; } +bool deser_bool(str *r, bool *buf) +{ + uint8_t x; + if (!deser_u8(r, &x)) + return false; + *buf = x != 0; + return true; +} + bool deser_str(str *r, str *buf) { uint16_t len; @@ -78,12 +93,12 @@ bool deser_str(str *r, str *buf) bool deser_u8(str *r, uint8_t *buf) { - return deser_bytes(r, 1, buf); + return deser_bytes(r, buf, 1); } bool deser_u16(str *r, uint16_t *buf) { - if (!deser_bytes(r, 2, (uint8_t *) buf)) + if (!deser_bytes(r, buf, 2)) return false; *buf = le16toh(*buf); return true; @@ -91,7 +106,7 @@ bool deser_u16(str *r, uint16_t *buf) bool deser_u32(str *r, uint32_t *buf) { - if (!deser_bytes(r, 4, (uint8_t *) buf)) + if (!deser_bytes(r, buf, 4)) return false; *buf = le32toh(*buf); return true; @@ -99,7 +114,7 @@ bool deser_u32(str *r, uint32_t *buf) bool deser_u64(str *r, uint64_t *buf) { - if (!deser_bytes(r, 8, (uint8_t *) buf)) + if (!deser_bytes(r, buf, 8)) return false; *buf = le64toh(*buf); return true; |