MOS Source Code
Loading...
Searching...
No Matches
encode_oneof.c
Go to the documentation of this file.
1/* Encode a message using oneof fields */
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <pb_encode.h>
6#include "oneof.pb.h"
7#include "test_helpers.h"
8
9int main(int argc, char **argv)
10{
11 uint8_t buffer[OneOfMessage_size];
12 OneOfMessage msg = OneOfMessage_init_zero;
13 pb_ostream_t stream;
14 int option;
15
16 if (argc != 2)
17 {
18 fprintf(stderr, "Usage: encode_oneof [number]\n");
19 return 1;
20 }
21 option = atoi(argv[1]);
22
23 /* Prefix and suffix are used to test that the union does not disturb
24 * other fields in the same message. */
25 msg.prefix = 123;
26
27 /* We encode one of the 'values' fields based on command line argument */
28 if (option == 1)
29 {
30 msg.which_values = OneOfMessage_first_tag;
31 msg.values.first = 999;
32 }
33 else if (option == 2)
34 {
35 msg.which_values = OneOfMessage_second_tag;
36 strcpy(msg.values.second, "abcd");
37 }
38 else if (option == 3)
39 {
40 msg.which_values = OneOfMessage_third_tag;
41 msg.values.third.array_count = 5;
42 msg.values.third.array[0] = 1;
43 msg.values.third.array[1] = 2;
44 msg.values.third.array[2] = 3;
45 msg.values.third.array[3] = 4;
46 msg.values.third.array[4] = 5;
47 }
48
49 msg.suffix = 321;
50
51 stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
52
53 if (pb_encode(&stream, OneOfMessage_fields, &msg))
54 {
56 fwrite(buffer, 1, stream.bytes_written, stdout);
57 return 0;
58 }
59 else
60 {
61 fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
62 return 1;
63 }
64}
MOSAPI char * strcpy(char *__restrict dest, const char *__restrict src)
Definition mos_string.c:184
#define stdout
Definition mos_stdio.h:31
#define stderr
Definition mos_stdio.h:32
size_t fwrite(const void *__restrict ptr, size_t size, size_t nmemb, FILE *__restrict stream)
MOSAPI s32 atoi(const char *nptr)
Definition mos_stdlib.c:36
const char ** argv
Definition kmain.c:44
size_t argc
Definition kmain.c:43
#define PB_GET_ERROR(stream)
Definition pb.h:891
pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
Definition pb_encode.c:63
bool pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct)
Definition pb_encode.c:512
unsigned char uint8_t
Definition pb_syshdr.h:20
int main()
Definition simple.cpp:6
#define SET_BINARY_MODE(file)
static char buffer[2048]
Definition test_printf.c:7