1 /* Decoding testcase for callback fields.
2 * Run e.g. ./test_encode_callbacks | ./test_decode_callbacks
7 #include "callbacks.pb.h"
8 #include "test_helpers.h"
10 bool print_string(pb_istream_t *stream, const pb_field_t *field, void **arg)
12 uint8_t buffer[1024] = {0};
14 /* We could read block-by-block to avoid the large buffer... */
15 if (stream->bytes_left > sizeof(buffer) - 1)
18 if (!pb_read(stream, buffer, stream->bytes_left))
21 /* Print the string, in format comparable with protoc --decode.
22 * Format comes from the arg defined in main().
24 printf((char*)*arg, buffer);
28 bool print_int32(pb_istream_t *stream, const pb_field_t *field, void **arg)
31 if (!pb_decode_varint(stream, &value))
34 printf((char*)*arg, (long)value);
38 bool print_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg)
41 if (!pb_decode_fixed32(stream, &value))
44 printf((char*)*arg, (long)value);
48 bool print_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg)
51 if (!pb_decode_fixed64(stream, &value))
54 printf((char*)*arg, (long)value);
63 /* Note: empty initializer list initializes the struct with all-0.
64 * This is recommended so that unused callbacks are set to NULL instead
65 * of crashing at runtime.
67 TestMessage testmessage = {{{NULL}}};
69 SET_BINARY_MODE(stdin);
70 length = fread(buffer, 1, 1024, stdin);
71 stream = pb_istream_from_buffer(buffer, length);
73 testmessage.submsg.stringvalue.funcs.decode = &print_string;
74 testmessage.submsg.stringvalue.arg = "submsg {\n stringvalue: \"%s\"\n";
75 testmessage.submsg.int32value.funcs.decode = &print_int32;
76 testmessage.submsg.int32value.arg = " int32value: %ld\n";
77 testmessage.submsg.fixed32value.funcs.decode = &print_fixed32;
78 testmessage.submsg.fixed32value.arg = " fixed32value: %ld\n";
79 testmessage.submsg.fixed64value.funcs.decode = &print_fixed64;
80 testmessage.submsg.fixed64value.arg = " fixed64value: %ld\n}\n";
82 testmessage.stringvalue.funcs.decode = &print_string;
83 testmessage.stringvalue.arg = "stringvalue: \"%s\"\n";
84 testmessage.int32value.funcs.decode = &print_int32;
85 testmessage.int32value.arg = "int32value: %ld\n";
86 testmessage.fixed32value.funcs.decode = &print_fixed32;
87 testmessage.fixed32value.arg = "fixed32value: %ld\n";
88 testmessage.fixed64value.funcs.decode = &print_fixed64;
89 testmessage.fixed64value.arg = "fixed64value: %ld\n";
90 testmessage.repeatedstring.funcs.decode = &print_string;
91 testmessage.repeatedstring.arg = "repeatedstring: \"%s\"\n";
93 if (!pb_decode(&stream, TestMessage_fields, &testmessage))