1c8d43a5c7041c7195a11cad540f3440942ed24b
[apps/agl-service-can-low-level.git] / tests / test_decode_callbacks.c
1 /* Decoding testcase for callback fields.
2  * Run e.g. ./test_encode_callbacks | ./test_decode_callbacks
3  */
4
5 #include <stdio.h>
6 #include <pb_decode.h>
7 #include "callbacks.pb.h"
8
9 bool print_string(pb_istream_t *stream, const pb_field_t *field, void *arg)
10 {
11     uint8_t buffer[1024];
12     
13     /* We could read block-by-block to avoid the large buffer... */
14     if (stream->bytes_left > sizeof(buffer))
15         return false;
16     
17     if (!pb_read(stream, buffer, stream->bytes_left))
18         return false;
19     
20     /* Print the string, in format comparable with protoc --decode. */
21     printf("%s: \"%s\"\n", (char*)arg, buffer);
22     return true;
23 }
24
25 int main()
26 {
27     uint8_t buffer[1024];
28     size_t length = fread(buffer, 1, 1024, stdin);
29     pb_istream_t stream = pb_istream_from_buffer(buffer, length);
30     
31     /* Note: empty initializer list initializes the struct with all-0.
32      * This is recommended so that unused callbacks are set to NULL instead
33      * of crashing at runtime.
34      */
35     TestMessage testmessage = {};
36     
37     testmessage.stringvalue.funcs.decode = &print_string;
38     testmessage.stringvalue.arg = "stringvalue";
39     
40     if (!pb_decode(&stream, TestMessage_fields, &testmessage))
41         return 1;
42     
43     return 0;
44 }