NanoPBExtensions.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include "NanoPBExtensions.h"
  2. #include <optional> // for optional
  3. #include <string> // for string
  4. #include <vector> // for vector
  5. #include <pb_common.h>
  6. #include <pb_encode.h>
  7. bool bell::nanopb::encodeString(pb_ostream_t* stream, const pb_field_t* field,
  8. void* const* arg) {
  9. auto& str = *static_cast<std::string*>(*arg);
  10. if (str.size() > 0) {
  11. if (!pb_encode_tag_for_field(stream, field)) {
  12. return false;
  13. }
  14. if (!pb_encode_string(stream, (uint8_t*)str.c_str(), str.size())) {
  15. return false;
  16. }
  17. }
  18. return true;
  19. }
  20. bool bell::nanopb::encodeBoolean(pb_ostream_t* stream, const pb_field_t* field,
  21. void* const* arg) {
  22. auto& boolean = *static_cast<std::optional<bool>*>(*arg);
  23. if (boolean.has_value()) {
  24. if (!pb_encode_tag_for_field(stream, field)) {
  25. return false;
  26. }
  27. if (!pb_encode_varint(stream, boolean.value())) {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33. bool bell::nanopb::encodeVector(pb_ostream_t* stream, const pb_field_t* field,
  34. void* const* arg) {
  35. auto& vector = *static_cast<std::vector<uint8_t>*>(*arg);
  36. if (vector.size() > 0) {
  37. if (!pb_encode_tag_for_field(stream, field)) {
  38. return false;
  39. }
  40. if (!pb_encode_string(stream, vector.data(), vector.size())) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }