blob: 8cf020cf01551f8560c9c1e479f174e8be762f3d (
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
|
#include <mpack.h>
#include "pb-msg.h"
#include "pb-serial.h"
#include "pb-mem.h"
#include "mpack-config.h"
pb_buf_t pb_msg_write(const pb_msg_t * msg) {
pb_buf_t buf = { 0 };
if (msg == NULL) return buf;
buf.data = pb_malloc(MPACK_BUFFER_SIZE);
if (buf.data == NULL) return buf;
mpack_writer_t writer;
mpack_writer_init(&writer, buf.data, buf.size);
pb_ser_w(&writer, msg);
buf.size = mpack_writer_buffer_used(&writer);
if (mpack_writer_destroy(&writer) != mpack_ok) {
pb_free(buf.data);
buf.data = NULL;
buf.size = 0;
}
return buf;
}
pb_msg_t * pb_msg_read(const pb_buf_t * buf) {
mpack_reader_t reader;
mpack_reader_init_data(&reader, buf->data, buf->size);
pb_msg_t * msg = pb_malloc(sizeof(pb_msg_t));
pb_ser_r(&reader, msg);
mpack_reader_destroy(&reader);
return msg;
}
void pb_msg_free(pb_msg_t * msg) {
// free message fields recursively
pb_ser_free(msg);
// free message container that was created in \p pb_msg_read
pb_free(msg);
}
|