NanoPBHelper.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "NanoPBHelper.h"
  2. #include <stdlib.h> // for malloc
  3. #include <string.h> // for strcpy, memcpy, strlen
  4. #include <algorithm> // for copy
  5. #include <cstdint> // for uint8_t
  6. #include "pb_encode.h" // for pb_ostream_s, pb_encode, pb_get_encoded_size
  7. static bool vectorWrite(pb_ostream_t* stream, const pb_byte_t* buf,
  8. size_t count) {
  9. size_t i;
  10. auto* dest = reinterpret_cast<std::vector<uint8_t>*>(stream->state);
  11. dest->insert(dest->end(), buf, buf + count);
  12. return true;
  13. }
  14. pb_ostream_t pb_ostream_from_vector(std::vector<uint8_t>& vec) {
  15. pb_ostream_t stream;
  16. stream.callback = &vectorWrite;
  17. stream.state = &vec;
  18. stream.max_size = 100000;
  19. stream.bytes_written = 0;
  20. return stream;
  21. }
  22. std::vector<uint8_t> pbEncode(const pb_msgdesc_t* fields,
  23. const void* src_struct) {
  24. std::vector<uint8_t> vecData(0);
  25. pb_ostream_t stream = pb_ostream_from_vector(vecData);
  26. pb_encode(&stream, fields, src_struct);
  27. return vecData;
  28. }
  29. void packString(char*& dst, std::string stringToPack) {
  30. dst = (char*)malloc((strlen(stringToPack.c_str()) + 1) * sizeof(char));
  31. strcpy(dst, stringToPack.c_str());
  32. }
  33. pb_bytes_array_t* vectorToPbArray(const std::vector<uint8_t>& vectorToPack) {
  34. auto size = static_cast<pb_size_t>(vectorToPack.size());
  35. auto result =
  36. static_cast<pb_bytes_array_t*>(malloc(PB_BYTES_ARRAY_T_ALLOCSIZE(size)));
  37. result->size = size;
  38. memcpy(result->bytes, vectorToPack.data(), size);
  39. return result;
  40. }
  41. void pbPutString(const std::string& stringToPack, char* dst) {
  42. stringToPack.copy(dst, stringToPack.size());
  43. dst[stringToPack.size()] = '\0';
  44. }
  45. void pbPutCharArray(const char* stringToPack, char* dst) {
  46. // copy stringToPack into dst
  47. strcpy(dst, stringToPack);
  48. //dst[sizeof(stringToPack)-1] = '\0';
  49. }
  50. void pbPutBytes(const std::vector<uint8_t>& data, pb_bytes_array_t& dst) {
  51. dst.size = data.size();
  52. std::copy(data.begin(), data.end(), dst.bytes);
  53. }
  54. std::vector<uint8_t> pbArrayToVector(pb_bytes_array_t* pbArray) {
  55. return std::vector<uint8_t>(pbArray->bytes, pbArray->bytes + pbArray->size);
  56. }
  57. const char* pb_encode_to_string(const pb_msgdesc_t* fields, const void* data) {
  58. size_t len;
  59. pb_get_encoded_size(&len, fields, data);
  60. auto* buf = static_cast<uint8_t*>(malloc(len + 1));
  61. auto ostream = pb_ostream_from_buffer(buf, len);
  62. pb_encode(&ostream, fields, data);
  63. buf[len] = '\0';
  64. return reinterpret_cast<const char*>(buf);
  65. }