NanoPBHelper.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #pragma once
  2. #include <stdint.h> // for uint8_t
  3. #include <stdio.h> // for printf
  4. #include <string> // for string
  5. #include <vector> // for vector
  6. #include "pb.h" // for pb_msgdesc_t, pb_bytes_array_t, PB_GET_ERROR
  7. #include "pb_decode.h" // for pb_istream_from_buffer, pb_decode, pb_istream_s
  8. std::vector<uint8_t> pbEncode(const pb_msgdesc_t* fields,
  9. const void* src_struct);
  10. pb_bytes_array_t* vectorToPbArray(const std::vector<uint8_t>& vectorToPack);
  11. void packString(char*& dst, std::string stringToPack);
  12. std::vector<uint8_t> pbArrayToVector(pb_bytes_array_t* pbArray);
  13. template <typename T>
  14. T pbDecode(const pb_msgdesc_t* fields, std::vector<uint8_t>& data) {
  15. T result = {};
  16. // Create stream
  17. pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
  18. // Decode the message
  19. if (pb_decode(&stream, fields, &result) == false) {
  20. printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
  21. }
  22. return result;
  23. }
  24. template <typename T>
  25. void pbDecode(T& result, const pb_msgdesc_t* fields,
  26. std::vector<uint8_t>& data) {
  27. // Create stream
  28. pb_istream_t stream = pb_istream_from_buffer(&data[0], data.size());
  29. // Decode the message
  30. if (pb_decode(&stream, fields, &result) == false) {
  31. printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
  32. }
  33. }
  34. void pbPutString(const std::string& stringToPack, char* dst);
  35. void pbPutCharArray(const char* stringToPack, char* dst);
  36. void pbPutBytes(const std::vector<uint8_t>& data, pb_bytes_array_t& dst);
  37. const char* pb_encode_to_string(const pb_msgdesc_t* fields, const void* data);