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