NanoPBHelper.h 1.4 KB

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