common.c 963 B

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