MOS Source Code
Loading...
Searching...
No Matches
decode_map.c
Go to the documentation of this file.
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. */
13MyMessage_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
26int main(int argc, char **argv)
27{
28 uint8_t buffer[MyMessage_size];
29 size_t count;
30
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
MyMessage_NumbersEntry * find_entry(MyMessage *msg, const char *key)
Definition decode_map.c:13
MOSAPI s32 strcmp(const char *str1, const char *str2)
Definition mos_string.c:24
size_t fread(void *__restrict ptr, size_t size, size_t nmemb, FILE *__restrict stream)
#define stderr
Definition mos_stdio.h:32
#define stdin
Definition mos_stdio.h:30
const char ** argv
Definition kmain.c:44
size_t argc
Definition kmain.c:43
bool pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct)
Definition pb_decode.c:1182
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t msglen)
Definition pb_decode.c:143
#define NULL
Definition pb_syshdr.h:46
unsigned char uint8_t
Definition pb_syshdr.h:20
int main()
Definition simple.cpp:6
#define TEST(x)
Definition test.h:3
#define SET_BINARY_MODE(file)
static char buffer[2048]
Definition test_printf.c:7