1 /* Simple binding of nanopb streams to TCP sockets.
2  */
3 
4 #include <sys/socket.h>
5 #include <sys/types.h>
6 #include <pb_encode.h>
7 #include <pb_decode.h>
8 
9 #include "common.h"
10 
write_callback(pb_ostream_t * stream,const uint8_t * buf,size_t count)11 static bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
12 {
13     int fd = (intptr_t)stream->state;
14     return send(fd, buf, count, 0) == count;
15 }
16 
read_callback(pb_istream_t * stream,uint8_t * buf,size_t count)17 static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count)
18 {
19     int fd = (intptr_t)stream->state;
20     int result;
21 
22     if (count == 0)
23         return true;
24 
25     result = recv(fd, buf, count, MSG_WAITALL);
26 
27     if (result == 0)
28         stream->bytes_left = 0; /* EOF */
29 
30     return result == count;
31 }
32 
pb_ostream_from_socket(int fd)33 pb_ostream_t pb_ostream_from_socket(int fd)
34 {
35     pb_ostream_t stream = {&write_callback, (void*)(intptr_t)fd, SIZE_MAX, 0};
36     return stream;
37 }
38 
pb_istream_from_socket(int fd)39 pb_istream_t pb_istream_from_socket(int fd)
40 {
41     pb_istream_t stream = {&read_callback, (void*)(intptr_t)fd, SIZE_MAX};
42     return stream;
43 }
44