Line data Source code
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 4 : MyMessage_NumbersEntry *find_entry(MyMessage *msg, const char *key) 14 : { 15 : int i; 16 10 : for (i = 0; i < msg->numbers_count; i++) 17 : { 18 9 : if (strcmp(msg->numbers[i].key, key) == 0) 19 : { 20 3 : return &msg->numbers[i]; 21 : } 22 : } 23 1 : return NULL; 24 : } 25 : 26 1 : int main(int argc, char **argv) 27 : { 28 : uint8_t buffer[MyMessage_size]; 29 : size_t count; 30 : 31 : SET_BINARY_MODE(stdin); 32 1 : count = fread(buffer, 1, sizeof(buffer), stdin); 33 : 34 1 : if (!feof(stdin)) 35 : { 36 0 : printf("Message does not fit in buffer\n"); 37 0 : return 1; 38 : } 39 : 40 : { 41 1 : int status = 0; 42 1 : MyMessage msg = MyMessage_init_zero; 43 : MyMessage_NumbersEntry *e; 44 1 : pb_istream_t stream = pb_istream_from_buffer(buffer, count); 45 : 46 1 : if (!pb_decode(&stream, MyMessage_fields, &msg)) 47 : { 48 0 : fprintf(stderr, "Decoding failed\n"); 49 0 : return 2; 50 : } 51 : 52 1 : TEST((e = find_entry(&msg, "one")) && e->value == 1); 53 1 : TEST((e = find_entry(&msg, "two")) && e->value == 2); 54 1 : TEST((e = find_entry(&msg, "seven")) && e->value == 7); 55 1 : TEST(!find_entry(&msg, "zero")); 56 : 57 1 : return status; 58 : } 59 : } 60 :