README.txt
1 Nanopb example "using_union_messages"
2 =====================================
3
4 Union messages is a common technique in Google Protocol Buffers used to
5 represent a group of messages, only one of which is passed at a time.
6 It is described in Google's documentation:
7 https://developers.google.com/protocol-buffers/docs/techniques#union
8
9 This directory contains an example on how to encode and decode union messages
10 with minimal memory usage. Usually, nanopb would allocate space to store
11 all of the possible messages at the same time, even though at most one of
12 them will be used at a time.
13
14 By using some of the lower level nanopb APIs, we can manually generate the
15 top level message, so that we only need to allocate the one submessage that
16 we actually want. Similarly when decoding, we can manually read the tag of
17 the top level message, and only then allocate the memory for the submessage
18 after we already know its type.
19
20 NOTE: There is a newer protobuf feature called `oneof` that is also supported
21 by nanopb. It might be a better option for new code.
22
23
24 Example usage
25 -------------
26
27 Type `make` to run the example. It will build it and run commands like
28 following:
29
30 ./encode 1 | ./decode
31 Got MsgType1: 42
32 ./encode 2 | ./decode
33 Got MsgType2: true
34 ./encode 3 | ./decode
35 Got MsgType3: 3 1415
36
37 This simply demonstrates that the "decode" program has correctly identified
38 the type of the received message, and managed to decode it.
39
40
41 Details of implementation
42 -------------------------
43
44 unionproto.proto contains the protocol used in the example. It consists of
45 three messages: MsgType1, MsgType2 and MsgType3, which are collected together
46 into UnionMessage.
47
48 encode.c takes one command line argument, which should be a number 1-3. It
49 then fills in and encodes the corresponding message, and writes it to stdout.
50
51 decode.c reads a UnionMessage from stdin. Then it calls the function
52 decode_unionmessage_type() to determine the type of the message. After that,
53 the corresponding message is decoded and the contents of it printed to the
54 screen.
55
56