decode_map.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* Decode a message using map field */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pb_decode.h>
  6. #include "map.pb.h"
  7. #include "test_helpers.h"
  8. #include "unittests.h"
  9. /* Helper function to find an entry in the list. Not as efficient as a real
  10. * hashmap or similar would be, but suitable for small arrays. */
  11. MyMessage_NumbersEntry *find_entry(MyMessage *msg, const char *key)
  12. {
  13. int i;
  14. for (i = 0; i < msg->numbers_count; i++)
  15. {
  16. if (strcmp(msg->numbers[i].key, key) == 0)
  17. {
  18. return &msg->numbers[i];
  19. }
  20. }
  21. return NULL;
  22. }
  23. int main(int argc, char **argv)
  24. {
  25. uint8_t buffer[MyMessage_size];
  26. size_t count;
  27. SET_BINARY_MODE(stdin);
  28. count = fread(buffer, 1, sizeof(buffer), stdin);
  29. if (!feof(stdin))
  30. {
  31. printf("Message does not fit in buffer\n");
  32. return 1;
  33. }
  34. {
  35. int status = 0;
  36. MyMessage msg = MyMessage_init_zero;
  37. MyMessage_NumbersEntry *e;
  38. pb_istream_t stream = pb_istream_from_buffer(buffer, count);
  39. if (!pb_decode(&stream, MyMessage_fields, &msg))
  40. {
  41. fprintf(stderr, "Decoding failed\n");
  42. return 2;
  43. }
  44. TEST((e = find_entry(&msg, "one")) && e->value == 1);
  45. TEST((e = find_entry(&msg, "two")) && e->value == 2);
  46. TEST((e = find_entry(&msg, "seven")) && e->value == 7);
  47. TEST(!find_entry(&msg, "zero"));
  48. return status;
  49. }
  50. }