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