Add 'CAN-binder/libs/nanopb/' from commit '278ffb890e3d8722e4c7d824baaf221a1e375fc4'
[apps/agl-service-can-low-level.git] / CAN-binder / libs / nanopb / examples / network_server / common.c
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
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
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     result = recv(fd, buf, count, MSG_WAITALL);
23     
24     if (result == 0)
25         stream->bytes_left = 0; /* EOF */
26     
27     return result == count;
28 }
29
30 pb_ostream_t pb_ostream_from_socket(int fd)
31 {
32     pb_ostream_t stream = {&write_callback, (void*)(intptr_t)fd, SIZE_MAX, 0};
33     return stream;
34 }
35
36 pb_istream_t pb_istream_from_socket(int fd)
37 {
38     pb_istream_t stream = {&read_callback, (void*)(intptr_t)fd, SIZE_MAX};
39     return stream;
40 }