MOS Source Code
Loading...
Searching...
No Matches
decode_buffer.c
Go to the documentation of this file.
1/* A very simple decoding test case, using person.proto.
2 * Produces output compatible with protoc --decode.
3 * Reads the encoded data from stdin and prints the values
4 * to stdout as text.
5 *
6 * Run e.g. ./test_encode1 | ./test_decode1
7 */
8
9#include <stdio.h>
10#include <pb_decode.h>
11#include "person.pb.h"
12#include "test_helpers.h"
13
14/* This function is called once from main(), it handles
15 the decoding and printing. */
16bool print_person(pb_istream_t *stream)
17{
18 int i;
19 Person person = Person_init_zero;
20
21 if (!pb_decode(stream, Person_fields, &person))
22 return false;
23
24 /* Now the decoding is done, rest is just to print stuff out. */
25
26 printf("name: \"%s\"\n", person.name);
27 printf("id: %ld\n", (long)person.id);
28
29 if (person.has_email)
30 printf("email: \"%s\"\n", person.email);
31
32 for (i = 0; i < person.phone_count; i++)
33 {
34 Person_PhoneNumber *phone = &person.phone[i];
35 printf("phone {\n");
36 printf(" number: \"%s\"\n", phone->number);
37
38 if (phone->has_type)
39 {
40 switch (phone->type)
41 {
42 case Person_PhoneType_WORK:
43 printf(" type: WORK\n");
44 break;
45
46 case Person_PhoneType_HOME:
47 printf(" type: HOME\n");
48 break;
49
50 case Person_PhoneType_MOBILE:
51 printf(" type: MOBILE\n");
52 break;
53 }
54 }
55 printf("}\n");
56 }
57
58 return true;
59}
60
61int main()
62{
63 uint8_t buffer[Person_size];
64 pb_istream_t stream;
65 size_t count;
66
67 /* Read the data into buffer */
69 count = fread(buffer, 1, sizeof(buffer), stdin);
70
71 if (!feof(stdin))
72 {
73 printf("Message does not fit in buffer\n");
74 return 1;
75 }
76
77 /* Construct a pb_istream_t for reading from the buffer */
78 stream = pb_istream_from_buffer(buffer, count);
79
80 /* Decode and print out the stuff */
81 if (!print_person(&stream))
82 {
83 printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
84 return 1;
85 } else {
86 return 0;
87 }
88}
bool print_person(pb_istream_t *stream)
int main()
size_t fread(void *__restrict ptr, size_t size, size_t nmemb, FILE *__restrict stream)
#define stdin
Definition mos_stdio.h:30
#define PB_GET_ERROR(stream)
Definition pb.h:891
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
unsigned char uint8_t
Definition pb_syshdr.h:20
#define SET_BINARY_MODE(file)
static char buffer[2048]
Definition test_printf.c:7