1 /* Encoding testcase for callback fields */
2 
3 #include <stdio.h>
4 #include <string.h>
5 #include <pb_encode.h>
6 #include "callbacks.pb.h"
7 #include "test_helpers.h"
8 
9 bool encode_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
10 {
11     char *str = "Hello world!";
12 
13     if (!pb_encode_tag_for_field(stream, field))
14         return false;
15 
16     return pb_encode_string(stream, (uint8_t*)str, strlen(str));
17 }
18 
19 bool encode_int32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
20 {
21     if (!pb_encode_tag_for_field(stream, field))
22         return false;
23 
24     return pb_encode_varint(stream, 42);
25 }
26 
27 bool encode_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
28 {
29     uint32_t value = 42;
30 
31     if (!pb_encode_tag_for_field(stream, field))
32         return false;
33 
34     return pb_encode_fixed32(stream, &value);
35 }
36 
37 bool encode_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
38 {
39     uint64_t value = 42;
40 
41     if (!pb_encode_tag_for_field(stream, field))
42         return false;
43 
44     return pb_encode_fixed64(stream, &value);
45 }
46 
47 bool encode_repeatedstring(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
48 {
49     char *str[4] = {"Hello world!", "", "Test", "Test2"};
50     int i;
51 
52     for (i = 0; i < 4; i++)
53     {
54         if (!pb_encode_tag_for_field(stream, field))
55             return false;
56 
57         if (!pb_encode_string(stream, (uint8_t*)str[i], strlen(str[i])))
58             return false;
59     }
60     return true;
61 }
62 
63 int main()
64 {
65     uint8_t buffer[1024];
66     pb_ostream_t stream;
67     TestMessage testmessage = {{{NULL}}};
68 
69     stream = pb_ostream_from_buffer(buffer, 1024);
70 
71     testmessage.stringvalue.funcs.encode = &encode_string;
72     testmessage.int32value.funcs.encode = &encode_int32;
73     testmessage.fixed32value.funcs.encode = &encode_fixed32;
74     testmessage.fixed64value.funcs.encode = &encode_fixed64;
75 
76     testmessage.has_submsg = true;
77     testmessage.submsg.stringvalue.funcs.encode = &encode_string;
78     testmessage.submsg.int32value.funcs.encode = &encode_int32;
79     testmessage.submsg.fixed32value.funcs.encode = &encode_fixed32;
80     testmessage.submsg.fixed64value.funcs.encode = &encode_fixed64;
81 
82     testmessage.repeatedstring.funcs.encode = &encode_repeatedstring;
83 
84     if (!pb_encode(&stream, TestMessage_fields, &testmessage))
85         return 1;
86 
87     SET_BINARY_MODE(stdout);
88     if (fwrite(buffer, stream.bytes_written, 1, stdout) != 1)
89         return 2;
90 
91     return 0;
92 }
93