• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1=====================
2Nanopb: API reference
3=====================
4
5.. include :: menu.rst
6
7.. contents ::
8
9
10
11
12Compilation options
13===================
14The following options can be specified in one of two ways:
15
161. Using the -D switch on the C compiler command line.
172. By #defining them at the top of pb.h.
18
19You must have the same settings for the nanopb library and all code that
20includes pb.h.
21
22============================  ================================================
23PB_NO_PACKED_STRUCTS           Disable packed structs. Increases RAM usage but
24                               is necessary on some platforms that do not
25                               support unaligned memory access.
26PB_ENABLE_MALLOC               Set this to enable dynamic allocation support
27                               in the decoder.
28PB_MAX_REQUIRED_FIELDS         Maximum number of required fields to check for
29                               presence. Default value is 64. Increases stack
30                               usage 1 byte per every 8 fields. Compiler
31                               warning will tell if you need this.
32PB_FIELD_16BIT                 Add support for tag numbers > 255 and fields
33                               larger than 255 bytes or 255 array entries.
34                               Increases code size 3 bytes per each field.
35                               Compiler error will tell if you need this.
36PB_FIELD_32BIT                 Add support for tag numbers > 65535 and fields
37                               larger than 65535 bytes or 65535 array entries.
38                               Increases code size 9 bytes per each field.
39                               Compiler error will tell if you need this.
40PB_NO_ERRMSG                   Disables the support for error messages; only
41                               error information is the true/false return
42                               value. Decreases the code size by a few hundred
43                               bytes.
44PB_BUFFER_ONLY                 Disables the support for custom streams. Only
45                               supports encoding and decoding with memory
46                               buffers. Speeds up execution and decreases code
47                               size slightly.
48PB_OLD_CALLBACK_STYLE          Use the old function signature (void\* instead
49                               of void\*\*) for callback fields. This was the
50                               default until nanopb-0.2.1.
51PB_SYSTEM_HEADER               Replace the standard header files with a single
52                               header file. It should define all the required
53                               functions and typedefs listed on the
54                               `overview page`_. Value must include quotes,
55                               for example *#define PB_SYSTEM_HEADER "foo.h"*.
56PB_WITHOUT_64BIT               Disable 64-bit support, for old compilers or
57                               for a slight speedup on 8-bit platforms.
58PB_ENCODE_ARRAYS_UNPACKED      Don't encode scalar arrays as packed.
59                               This is only to be used when the decoder on the
60                               receiving side cannot process packed scalar
61                               arrays. Such example is older protobuf.js.
62============================  ================================================
63
64The PB_MAX_REQUIRED_FIELDS, PB_FIELD_16BIT and PB_FIELD_32BIT settings allow
65raising some datatype limits to suit larger messages. Their need is recognized
66automatically by C-preprocessor #if-directives in the generated .pb.h files.
67The default setting is to use the smallest datatypes (least resources used).
68
69.. _`overview page`: index.html#compiler-requirements
70
71
72Proto file options
73==================
74The generator behaviour can be adjusted using these options, defined in the
75'nanopb.proto' file in the generator folder:
76
77============================  ================================================
78max_size                       Allocated size for *bytes* and *string* fields.
79max_count                      Allocated number of entries in arrays
80                               (*repeated* fields).
81int_size                       Override the integer type of a field.
82                               (To use e.g. uint8_t to save RAM.)
83type                           Type of the generated field. Default value
84                               is *FT_DEFAULT*, which selects automatically.
85                               You can use *FT_CALLBACK*, *FT_POINTER*,
86                               *FT_STATIC* or *FT_IGNORE* to
87                               force a callback field, a dynamically
88                               allocated field, a static field or to
89                               completely ignore the field.
90long_names                     Prefix the enum name to the enum value in
91                               definitions, i.e. *EnumName_EnumValue*. Enabled
92                               by default.
93packed_struct                  Make the generated structures packed.
94                               NOTE: This cannot be used on CPUs that break
95                               on unaligned accesses to variables.
96skip_message                   Skip the whole message from generation.
97no_unions                      Generate 'oneof' fields as optional fields
98                               instead of C unions.
99msgid                          Specifies a unique id for this message type.
100                               Can be used by user code as an identifier.
101anonymous_oneof                Generate 'oneof' fields as anonymous unions.
102fixed_length                   Generate 'bytes' fields with constant length
103                               (max_size must also be defined).
104fixed_count                    Generate arrays with constant length
105                               (max_count must also be defined).
106============================  ================================================
107
108These options can be defined for the .proto files before they are converted
109using the nanopb-generatory.py. There are three ways to define the options:
110
1111. Using a separate .options file.
112   This is the preferred way as of nanopb-0.2.1, because it has the best
113   compatibility with other protobuf libraries.
1142. Defining the options on the command line of nanopb_generator.py.
115   This only makes sense for settings that apply to a whole file.
1163. Defining the options in the .proto file using the nanopb extensions.
117   This is the way used in nanopb-0.1, and will remain supported in the
118   future. It however sometimes causes trouble when using the .proto file
119   with other protobuf libraries.
120
121The effect of the options is the same no matter how they are given. The most
122common purpose is to define maximum size for string fields in order to
123statically allocate them.
124
125Defining the options in a .options file
126---------------------------------------
127The preferred way to define options is to have a separate file
128'myproto.options' in the same directory as the 'myproto.proto'. ::
129
130    # myproto.proto
131    message MyMessage {
132        required string name = 1;
133        repeated int32 ids = 4;
134    }
135
136::
137
138    # myproto.options
139    MyMessage.name         max_size:40
140    MyMessage.ids          max_count:5
141
142The generator will automatically search for this file and read the
143options from it. The file format is as follows:
144
145* Lines starting with '#' or '//' are regarded as comments.
146* Blank lines are ignored.
147* All other lines should start with a field name pattern, followed by one or
148  more options. For example: *"MyMessage.myfield max_size:5 max_count:10"*.
149* The field name pattern is matched against a string of form *'Message.field'*.
150  For nested messages, the string is *'Message.SubMessage.field'*.
151* The field name pattern may use the notation recognized by Python fnmatch():
152
153  - *\** matches any part of string, like 'Message.\*' for all fields
154  - *\?* matches any single character
155  - *[seq]* matches any of characters 's', 'e' and 'q'
156  - *[!seq]* matches any other character
157
158* The options are written as *'option_name:option_value'* and several options
159  can be defined on same line, separated by whitespace.
160* Options defined later in the file override the ones specified earlier, so
161  it makes sense to define wildcard options first in the file and more specific
162  ones later.
163
164To debug problems in applying the options, you can use the *-v* option for the
165plugin. Plugin options are specified in front of the output path:
166
167    protoc ... --nanopb_out=-v:. message.proto
168
169Protoc doesn't currently pass include path into plugins. Therefore if your
170*.proto* is in a subdirectory, nanopb may have trouble finding the associated
171*.options* file. A workaround is to specify include path separately to the
172nanopb plugin, like:
173
174    protoc -Isubdir --nanopb_out=-Isubdir:. message.proto
175
176If preferred, the name of the options file can be set using plugin argument
177*-f*.
178
179Defining the options on command line
180------------------------------------
181The nanopb_generator.py has a simple command line option *-s OPTION:VALUE*.
182The setting applies to the whole file that is being processed.
183
184Defining the options in the .proto file
185---------------------------------------
186The .proto file format allows defining custom options for the fields.
187The nanopb library comes with *nanopb.proto* which does exactly that, allowing
188you do define the options directly in the .proto file::
189
190    import "nanopb.proto";
191
192    message MyMessage {
193        required string name = 1 [(nanopb).max_size = 40];
194        repeated int32 ids = 4   [(nanopb).max_count = 5];
195    }
196
197A small complication is that you have to set the include path of protoc so that
198nanopb.proto can be found. This file, in turn, requires the file
199*google/protobuf/descriptor.proto*. This is usually installed under
200*/usr/include*. Therefore, to compile a .proto file which uses options, use a
201protoc command similar to::
202
203    protoc -I/usr/include -Inanopb/generator -I. --nanopb_out=. message.proto
204
205The options can be defined in file, message and field scopes::
206
207    option (nanopb_fileopt).max_size = 20; // File scope
208    message Message
209    {
210        option (nanopb_msgopt).max_size = 30; // Message scope
211        required string fieldsize = 1 [(nanopb).max_size = 40]; // Field scope
212    }
213
214
215pb.h
216====
217
218pb_byte_t
219---------
220Type used for storing byte-sized data, such as raw binary input and bytes-type fields. ::
221
222    typedef uint_least8_t pb_byte_t;
223
224For most platforms this is equivalent to `uint8_t`. Some platforms however do not support
2258-bit variables, and on those platforms 16 or 32 bits need to be used for each byte.
226
227pb_type_t
228---------
229Type used to store the type of each field, to control the encoder/decoder behaviour. ::
230
231    typedef uint_least8_t pb_type_t;
232
233The low-order nibble of the enumeration values defines the function that can be used for encoding and decoding the field data:
234
235=========================== ===== ================================================
236LTYPE identifier            Value Storage format
237=========================== ===== ================================================
238PB_LTYPE_VARINT             0x00  Integer.
239PB_LTYPE_UVARINT            0x01  Unsigned integer.
240PB_LTYPE_SVARINT            0x02  Integer, zigzag encoded.
241PB_LTYPE_FIXED32            0x03  32-bit integer or floating point.
242PB_LTYPE_FIXED64            0x04  64-bit integer or floating point.
243PB_LTYPE_BYTES              0x05  Structure with *size_t* field and byte array.
244PB_LTYPE_STRING             0x06  Null-terminated string.
245PB_LTYPE_SUBMESSAGE         0x07  Submessage structure.
246PB_LTYPE_EXTENSION          0x08  Point to *pb_extension_t*.
247PB_LTYPE_FIXED_LENGTH_BYTES 0x09  Inline *pb_byte_t* array of fixed size.
248=========================== ===== ================================================
249
250The bits 4-5 define whether the field is required, optional or repeated:
251
252==================== ===== ================================================
253HTYPE identifier     Value Field handling
254==================== ===== ================================================
255PB_HTYPE_REQUIRED    0x00  Verify that field exists in decoded message.
256PB_HTYPE_OPTIONAL    0x10  Use separate *has_<field>* boolean to specify
257                           whether the field is present.
258                           (Unless it is a callback)
259PB_HTYPE_REPEATED    0x20  A repeated field with preallocated array.
260                           Separate *<field>_count* for number of items.
261                           (Unless it is a callback)
262==================== ===== ================================================
263
264The bits 6-7 define the how the storage for the field is allocated:
265
266==================== ===== ================================================
267ATYPE identifier     Value Allocation method
268==================== ===== ================================================
269PB_ATYPE_STATIC      0x00  Statically allocated storage in the structure.
270PB_ATYPE_CALLBACK    0x40  A field with dynamic storage size. Struct field
271                           actually contains a pointer to a callback
272                           function.
273==================== ===== ================================================
274
275
276pb_field_t
277----------
278Describes a single structure field with memory position in relation to others. The descriptions are usually autogenerated. ::
279
280    typedef struct pb_field_s pb_field_t;
281    struct pb_field_s {
282        pb_size_t tag;
283        pb_type_t type;
284        pb_size_t data_offset;
285        pb_ssize_t size_offset;
286        pb_size_t data_size;
287        pb_size_t array_size;
288        const void *ptr;
289    } pb_packed;
290
291:tag:           Tag number of the field or 0 to terminate a list of fields.
292:type:          LTYPE, HTYPE and ATYPE of the field.
293:data_offset:   Offset of field data, relative to the end of the previous field.
294:size_offset:   Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data.
295:data_size:     Size of a single data entry, in bytes. For PB_LTYPE_BYTES, the size of the byte array inside the containing structure. For PB_HTYPE_CALLBACK, size of the C data type if known.
296:array_size:    Maximum number of entries in an array, if it is an array type.
297:ptr:           Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE.
298
299The *uint8_t* datatypes limit the maximum size of a single item to 255 bytes and arrays to 255 items. Compiler will give error if the values are too large. The types can be changed to larger ones by defining *PB_FIELD_16BIT*.
300
301pb_bytes_array_t
302----------------
303An byte array with a field for storing the length::
304
305    typedef struct {
306        pb_size_t size;
307        pb_byte_t bytes[1];
308    } pb_bytes_array_t;
309
310In an actual array, the length of *bytes* may be different.
311
312pb_callback_t
313-------------
314Part of a message structure, for fields with type PB_HTYPE_CALLBACK::
315
316    typedef struct _pb_callback_t pb_callback_t;
317    struct _pb_callback_t {
318        union {
319            bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg);
320            bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
321        } funcs;
322
323        void *arg;
324    };
325
326A pointer to the *arg* is passed to the callback when calling. It can be used to store any information that the callback might need.
327
328Previously the function received just the value of *arg* instead of a pointer to it. This old behaviour can be enabled by defining *PB_OLD_CALLBACK_STYLE*.
329
330When calling `pb_encode`_, *funcs.encode* is used, and similarly when calling `pb_decode`_, *funcs.decode* is used. The function pointers are stored in the same memory location but are of incompatible types. You can set the function pointer to NULL to skip the field.
331
332pb_wire_type_t
333--------------
334Protocol Buffers wire types. These are used with `pb_encode_tag`_. ::
335
336    typedef enum {
337        PB_WT_VARINT = 0,
338        PB_WT_64BIT  = 1,
339        PB_WT_STRING = 2,
340        PB_WT_32BIT  = 5
341    } pb_wire_type_t;
342
343pb_extension_type_t
344-------------------
345Defines the handler functions and auxiliary data for a field that extends
346another message. Usually autogenerated by *nanopb_generator.py*::
347
348    typedef struct {
349        bool (*decode)(pb_istream_t *stream, pb_extension_t *extension,
350                   uint32_t tag, pb_wire_type_t wire_type);
351        bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension);
352        const void *arg;
353    } pb_extension_type_t;
354
355In the normal case, the function pointers are *NULL* and the decoder and
356encoder use their internal implementations. The internal implementations
357assume that *arg* points to a *pb_field_t* that describes the field in question.
358
359To implement custom processing of unknown fields, you can provide pointers
360to your own functions. Their functionality is mostly the same as for normal
361callback fields, except that they get called for any unknown field when decoding.
362
363pb_extension_t
364--------------
365Ties together the extension field type and the storage for the field value::
366
367    typedef struct {
368        const pb_extension_type_t *type;
369        void *dest;
370        pb_extension_t *next;
371        bool found;
372    } pb_extension_t;
373
374:type:      Pointer to the structure that defines the callback functions.
375:dest:      Pointer to the variable that stores the field value
376            (as used by the default extension callback functions.)
377:next:      Pointer to the next extension handler, or *NULL*.
378:found:     Decoder sets this to true if the extension was found.
379
380PB_GET_ERROR
381------------
382Get the current error message from a stream, or a placeholder string if
383there is no error message::
384
385    #define PB_GET_ERROR(stream) (string expression)
386
387This should be used for printing errors, for example::
388
389    if (!pb_decode(...))
390    {
391        printf("Decode failed: %s\n", PB_GET_ERROR(stream));
392    }
393
394The macro only returns pointers to constant strings (in code memory),
395so that there is no need to release the returned pointer.
396
397PB_RETURN_ERROR
398---------------
399Set the error message and return false::
400
401    #define PB_RETURN_ERROR(stream,msg) (sets error and returns false)
402
403This should be used to handle error conditions inside nanopb functions
404and user callback functions::
405
406    if (error_condition)
407    {
408        PB_RETURN_ERROR(stream, "something went wrong");
409    }
410
411The *msg* parameter must be a constant string.
412
413
414
415pb_encode.h
416===========
417
418pb_ostream_from_buffer
419----------------------
420Constructs an output stream for writing into a memory buffer. This is just a helper function, it doesn't do anything you couldn't do yourself in a callback function. It uses an internal callback that stores the pointer in stream *state* field. ::
421
422    pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize);
423
424:buf:           Memory buffer to write into.
425:bufsize:       Maximum number of bytes to write.
426:returns:       An output stream.
427
428After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer.
429
430pb_write
431--------
432Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. ::
433
434    bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);
435
436:stream:        Output stream to write to.
437:buf:           Pointer to buffer with the data to be written.
438:count:         Number of bytes to write.
439:returns:       True on success, false if maximum length is exceeded or an IO error happens.
440
441If an error happens, *bytes_written* is not incremented. Depending on the callback used, calling pb_write again after it has failed once may be dangerous. Nanopb itself never does this, instead it returns the error to user application. The builtin pb_ostream_from_buffer is safe to call again after failed write.
442
443pb_encode
444---------
445Encodes the contents of a structure as a protocol buffers message and writes it to output stream. ::
446
447    bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
448
449:stream:        Output stream to write to.
450:fields:        A field description array, usually autogenerated.
451:src_struct:    Pointer to the data that will be serialized.
452:returns:       True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false.
453
454Normally pb_encode simply walks through the fields description array and serializes each field in turn. However, submessages must be serialized twice: first to calculate their size and then to actually write them to output. This causes some constraints for callback fields, which must return the same data on every call.
455
456pb_encode_delimited
457-------------------
458Calculates the length of the message, encodes it as varint and then encodes the message. ::
459
460    bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
461
462(parameters are the same as for `pb_encode`_.)
463
464A common way to indicate the message length in Protocol Buffers is to prefix it with a varint.
465This function does this, and it is compatible with *parseDelimitedFrom* in Google's protobuf library.
466
467.. sidebar:: Encoding fields manually
468
469    The functions with names *pb_encode_\** are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_encode`_ will call your callback function, which in turn will call *pb_encode_\** functions repeatedly to write out values.
470
471    The tag of a field must be encoded separately with `pb_encode_tag_for_field`_. After that, you can call exactly one of the content-writing functions to encode the payload of the field. For repeated fields, you can repeat this process multiple times.
472
473    Writing packed arrays is a little bit more involved: you need to use `pb_encode_tag` and specify `PB_WT_STRING` as the wire type. Then you need to know exactly how much data you are going to write, and use `pb_encode_varint`_ to write out the number of bytes before writing the actual data. Substreams can be used to determine the number of bytes beforehand; see `pb_encode_submessage`_ source code for an example.
474
475pb_get_encoded_size
476-------------------
477Calculates the length of the encoded message. ::
478
479    bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct);
480
481:size:          Calculated size of the encoded message.
482:fields:        A field description array, usually autogenerated.
483:src_struct:    Pointer to the data that will be serialized.
484:returns:       True on success, false on detectable errors in field description or if a field encoder returns false.
485
486pb_encode_tag
487-------------
488Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. ::
489
490    bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number);
491
492:stream:        Output stream to write to. 1-5 bytes will be written.
493:wiretype:      PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT
494:field_number:  Identifier for the field, defined in the .proto file. You can get it from field->tag.
495:returns:       True on success, false on IO error.
496
497pb_encode_tag_for_field
498-----------------------
499Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. ::
500
501    bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
502
503:stream:        Output stream to write to. 1-5 bytes will be written.
504:field:         Field description structure. Usually autogenerated.
505:returns:       True on success, false on IO error or unknown field type.
506
507This function only considers the LTYPE of the field. You can use it from your field callbacks, because the source generator writes correct LTYPE also for callback type fields.
508
509Wire type mapping is as follows:
510
511============================================= ============
512LTYPEs                                        Wire type
513============================================= ============
514VARINT, UVARINT, SVARINT                      PB_WT_VARINT
515FIXED64                                       PB_WT_64BIT
516STRING, BYTES, SUBMESSAGE, FIXED_LENGTH_BYTES PB_WT_STRING
517FIXED32                                       PB_WT_32BIT
518============================================= ============
519
520pb_encode_varint
521----------------
522Encodes a signed or unsigned integer in the varint_ format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`::
523
524    bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
525
526:stream:        Output stream to write to. 1-10 bytes will be written.
527:value:         Value to encode. Just cast e.g. int32_t directly to uint64_t.
528:returns:       True on success, false on IO error.
529
530.. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
531
532pb_encode_svarint
533-----------------
534Encodes a signed integer in the 'zig-zagged' format. Works for fields of type `sint32` and `sint64`::
535
536    bool pb_encode_svarint(pb_ostream_t *stream, int64_t value);
537
538(parameters are the same as for `pb_encode_varint`_
539
540pb_encode_string
541----------------
542Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`::
543
544    bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size);
545
546:stream:        Output stream to write to.
547:buffer:        Pointer to string data.
548:size:          Number of bytes in the string. Pass `strlen(s)` for strings.
549:returns:       True on success, false on IO error.
550
551pb_encode_fixed32
552-----------------
553Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`::
554
555    bool pb_encode_fixed32(pb_ostream_t *stream, const void *value);
556
557:stream:    Output stream to write to.
558:value:     Pointer to a 4-bytes large C variable, for example `uint32_t foo;`.
559:returns:   True on success, false on IO error.
560
561pb_encode_fixed64
562-----------------
563Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`::
564
565    bool pb_encode_fixed64(pb_ostream_t *stream, const void *value);
566
567:stream:    Output stream to write to.
568:value:     Pointer to a 8-bytes large C variable, for example `uint64_t foo;`.
569:returns:   True on success, false on IO error.
570
571pb_encode_submessage
572--------------------
573Encodes a submessage field, including the size header for it. Works for fields of any message type::
574
575    bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
576
577:stream:        Output stream to write to.
578:fields:        Pointer to the autogenerated field description array for the submessage type, e.g. `MyMessage_fields`.
579:src:           Pointer to the structure where submessage data is.
580:returns:       True on success, false on IO errors, pb_encode errors or if submessage size changes between calls.
581
582In Protocol Buffers format, the submessage size must be written before the submessage contents. Therefore, this function has to encode the submessage twice in order to know the size beforehand.
583
584If the submessage contains callback fields, the callback function might misbehave and write out a different amount of data on the second call. This situation is recognized and *false* is returned, but garbage will be written to the output before the problem is detected.
585
586
587
588
589
590
591
592
593
594
595
596
597pb_decode.h
598===========
599
600pb_istream_from_buffer
601----------------------
602Helper function for creating an input stream that reads data from a memory buffer. ::
603
604    pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize);
605
606:buf:           Pointer to byte array to read from.
607:bufsize:       Size of the byte array.
608:returns:       An input stream ready to use.
609
610pb_read
611-------
612Read data from input stream. Always use this function, don't try to call the stream callback directly. ::
613
614    bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);
615
616:stream:        Input stream to read from.
617:buf:           Buffer to store the data to, or NULL to just read data without storing it anywhere.
618:count:         Number of bytes to read.
619:returns:       True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs.
620
621End of file is signalled by *stream->bytes_left* being zero after pb_read returns false.
622
623pb_decode
624---------
625Read and decode all fields of a structure. Reads until EOF on input stream. ::
626
627    bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
628
629:stream:        Input stream to read from.
630:fields:        A field description array. Usually autogenerated.
631:dest_struct:   Pointer to structure where data will be stored.
632:returns:       True on success, false on IO error, on detectable errors in field description, if a field encoder returns false or if a required field is missing.
633
634In Protocol Buffers binary format, EOF is only allowed between fields. If it happens anywhere else, pb_decode will return *false*. If pb_decode returns false, you cannot trust any of the data in the structure.
635
636In addition to EOF, the pb_decode implementation supports terminating a message with a 0 byte. This is compatible with the official Protocol Buffers because 0 is never a valid field tag.
637
638For optional fields, this function applies the default value and sets *has_<field>* to false if the field is not present.
639
640If *PB_ENABLE_MALLOC* is defined, this function may allocate storage for any pointer type fields.
641In this case, you have to call `pb_release`_ to release the memory after you are done with the message.
642On error return `pb_decode` will release the memory itself.
643
644pb_decode_noinit
645----------------
646Same as `pb_decode`_, except does not apply the default values to fields. ::
647
648    bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
649
650(parameters are the same as for `pb_decode`_.)
651
652The destination structure should be filled with zeros before calling this function. Doing a *memset* manually can be slightly faster than using `pb_decode`_ if you don't need any default values.
653
654In addition to decoding a single message, this function can be used to merge two messages, so that
655values from previous message will remain if the new message does not contain a field.
656
657This function *will not* release the message even on error return. If you use *PB_ENABLE_MALLOC*,
658you will need to call `pb_release`_ yourself.
659
660pb_decode_delimited
661-------------------
662Same as `pb_decode`_, except that it first reads a varint with the length of the message. ::
663
664    bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
665
666(parameters are the same as for `pb_decode`_.)
667
668A common method to indicate message size in Protocol Buffers is to prefix it with a varint.
669This function is compatible with *writeDelimitedTo* in the Google's Protocol Buffers library.
670
671pb_release
672----------
673Releases any dynamically allocated fields::
674
675    void pb_release(const pb_field_t fields[], void *dest_struct);
676
677:fields:        A field description array. Usually autogenerated.
678:dest_struct:   Pointer to structure where data is stored. If NULL, function does nothing.
679
680This function is only available if *PB_ENABLE_MALLOC* is defined. It will release any
681pointer type fields in the structure and set the pointers to NULL.
682
683pb_decode_tag
684-------------
685Decode the tag that comes before field in the protobuf encoding::
686
687    bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof);
688
689:stream:        Input stream to read from.
690:wire_type:     Pointer to variable where to store the wire type of the field.
691:tag:           Pointer to variable where to store the tag of the field.
692:eof:           Pointer to variable where to store end-of-file status.
693:returns:       True on success, false on error or EOF.
694
695When the message (stream) ends, this function will return false and set *eof* to true. On other
696errors, *eof* will be set to false.
697
698pb_skip_field
699-------------
700Remove the data for a field from the stream, without actually decoding it::
701
702    bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);
703
704:stream:        Input stream to read from.
705:wire_type:     Type of field to skip.
706:returns:       True on success, false on IO error.
707
708.. sidebar:: Decoding fields manually
709
710    The functions with names beginning with *pb_decode_* are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_decode`_ will call your callback function repeatedly, which can then store the values into e.g. filesystem in the order received in.
711
712    For decoding numeric (including enumerated and boolean) values, use `pb_decode_varint`_, `pb_decode_svarint`_, `pb_decode_fixed32`_ and `pb_decode_fixed64`_. They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage.
713
714    For decoding strings and bytes fields, the length has already been decoded. You can therefore check the total length in *stream->bytes_left* and read the data using `pb_read`_.
715
716    Finally, for decoding submessages in a callback, simply use `pb_decode`_ and pass it the *SubMessage_fields* descriptor array.
717
718pb_decode_varint
719----------------
720Read and decode a varint_ encoded integer. ::
721
722    bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);
723
724:stream:        Input stream to read from. 1-10 bytes will be read.
725:dest:          Storage for the decoded integer. Value is undefined on error.
726:returns:       True on success, false if value exceeds uint64_t range or an IO error happens.
727
728pb_decode_svarint
729-----------------
730Similar to `pb_decode_varint`_, except that it performs zigzag-decoding on the value. This corresponds to the Protocol Buffers *sint32* and *sint64* datatypes. ::
731
732    bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest);
733
734(parameters are the same as `pb_decode_varint`_)
735
736pb_decode_fixed32
737-----------------
738Decode a *fixed32*, *sfixed32* or *float* value. ::
739
740    bool pb_decode_fixed32(pb_istream_t *stream, void *dest);
741
742:stream:        Input stream to read from. 4 bytes will be read.
743:dest:          Pointer to destination *int32_t*, *uint32_t* or *float*.
744:returns:       True on success, false on IO errors.
745
746This function reads 4 bytes from the input stream.
747On big endian architectures, it then reverses the order of the bytes.
748Finally, it writes the bytes to *dest*.
749
750pb_decode_fixed64
751-----------------
752Decode a *fixed64*, *sfixed64* or *double* value. ::
753
754    bool pb_decode_fixed64(pb_istream_t *stream, void *dest);
755
756:stream:        Input stream to read from. 8 bytes will be read.
757:dest:          Pointer to destination *int64_t*, *uint64_t* or *double*.
758:returns:       True on success, false on IO errors.
759
760Same as `pb_decode_fixed32`_, except this reads 8 bytes.
761
762pb_make_string_substream
763------------------------
764Decode the length for a field with wire type *PB_WT_STRING* and create a substream for reading the data. ::
765
766    bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream);
767
768:stream:        Original input stream to read the length and data from.
769:substream:     New substream that has limited length. Filled in by the function.
770:returns:       True on success, false if reading the length fails.
771
772This function uses `pb_decode_varint`_ to read an integer from the stream. This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the length, and its callback function and state the same as the parent stream.
773
774pb_close_string_substream
775-------------------------
776Close the substream created with `pb_make_string_substream`_. ::
777
778    void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream);
779
780:stream:        Original input stream to read the length and data from.
781:substream:     Substream to close
782
783This function copies back the state from the substream to the parent stream.
784It must be called after done with the substream.
785