diff options
author | ThomasintAnker <thomasintanker1@gmail.com> | 2024-06-18 16:23:51 +0200 |
---|---|---|
committer | ThomasintAnker <thomasintanker1@gmail.com> | 2024-06-18 16:23:51 +0200 |
commit | a55d0bed6240c54f6173b1e38e80212c02c302de (patch) | |
tree | 07c15eebc8cd84e1071a3f72d3c74475017372f3 /lib/i2ctcp/i2ctcpv1.c | |
parent | b45b5d04daa29fcdd456233a931dcbb5b287769f (diff) | |
parent | 245fde65808ce902064ab438296f04f691d007e7 (diff) |
Merge branch 'master' into wip/handover
Diffstat (limited to 'lib/i2ctcp/i2ctcpv1.c')
-rw-r--r-- | lib/i2ctcp/i2ctcpv1.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/i2ctcp/i2ctcpv1.c b/lib/i2ctcp/i2ctcpv1.c new file mode 100644 index 0000000..f70cbb1 --- /dev/null +++ b/lib/i2ctcp/i2ctcpv1.c @@ -0,0 +1,43 @@ +#include <mpack.h> +#ifndef MIN +#define MIN(a,b) (((a) < (b)) ? (a) : (b)) +#endif + +#include "i2ctcpv1.h" + +int i2ctcp_read(i2ctcp_msg_t * target, const char * buf, size_t buf_sz) { + mpack_reader_t reader; + mpack_reader_init_data(&reader, buf, buf_sz); + + // at start of message + if (target->_rdata == 0) { + target->addr = mpack_expect_u16(&reader); + target->length = target->_rdata = mpack_expect_bin(&reader); + if (mpack_reader_error(&reader) != mpack_ok) return -1; + target->data = (char *) malloc(target->length); + } + + // continue reading chunks of target->data until the amount of bytes + // specified in target->length + char * data = target->data + target->length - target->_rdata; + target->_rdata -= mpack_read_remaining_bytes(&reader, data, target->_rdata); + + // if rdata = 0, the message was completely read + return target->_rdata; +} + +void i2ctcp_read_reset(i2ctcp_msg_t * target) { + target->_rdata = 0; +} + +bool i2ctcp_write(const i2ctcp_msg_t * target, char ** buf, size_t * buf_sz) { + mpack_writer_t writer; + mpack_writer_init_growable(&writer, buf, buf_sz); + + mpack_write_u16(&writer, target->addr); + mpack_write_bin(&writer, target->data, target->length); + + // finish writing + return mpack_writer_destroy(&writer) == mpack_ok; +} + |