• 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
20
21Example usage
22-------------
23
24Type `make` to run the example. It will build it and run commands like
25following:
26
27./encode 1 | ./decode
28Got MsgType1: 42
29./encode 2 | ./decode
30Got MsgType2: true
31./encode 3 | ./decode
32Got MsgType3: 3 1415
33
34This simply demonstrates that the "decode" program has correctly identified
35the type of the received message, and managed to decode it.
36
37
38Details of implementation
39-------------------------
40
41unionproto.proto contains the protocol used in the example. It consists of
42three messages: MsgType1, MsgType2 and MsgType3, which are collected together
43into UnionMessage.
44
45encode.c takes one command line argument, which should be a number 1-3. It
46then fills in and encodes the corresponding message, and writes it to stdout.
47
48decode.c reads a UnionMessage from stdin. Then it calls the function
49decode_unionmessage_type() to determine the type of the message. After that,
50the corresponding message is decoded and the contents of it printed to the
51screen.
52
53