1# Nanopb: API reference 2 3## Compilation options 4 5Compilation options affect the functionality included in the nanopb core C code. 6The options can be specified in one of two ways: 7 81. Using the -D switch on the C compiler command line. 92. Using a `#define` at the top of pb.h. 10 11> **NOTE:** You must have the same compilation options for the nanopb library and all code that 12includes nanopb headers. 13 14* `PB_ENABLE_MALLOC`: Enable dynamic allocation support in the decoder. 15* `PB_MAX_REQUIRED_FIELDS`: Maximum number of proto2 `required` fields to check for presence. Default value is 64. Compiler warning will tell if you need this. 16* `PB_FIELD_32BIT`: Add support for field tag numbers over 65535, fields larger than 64 kiB and arrays larger than 65535 entries. Compiler warning will tell if you need this. 17* `PB_NO_ERRMSG`: Disable error message support to save code size. Only error information is the `true`/`false` return value. 18* `PB_BUFFER_ONLY`: Disable support for custom streams. Only supports encoding and decoding with memory buffers. Speeds up execution and slightly decreases code size. 19* `PB_SYSTEM_HEADER`: Replace the standards header files with a single system-specific header file. Value must include quotes, for example `#define PB_SYSTEM_HEADER "foo.h"`. See [extra/pb_syshdr.h](https://github.com/nanopb/nanopb/blob/master/extra/pb_syshdr.h) for an example. 20* `PB_WITHOUT_64BIT`: Disable support of 64-bit integer fields, for old compilers or for a slight speedup on 8-bit platforms. 21* `PB_ENCODE_ARRAYS_UNPACKED`: Encode scalar arrays in the unpacked format, which takes up more space. Only to be used when the decoder on the receiving side cannot process packed arrays, such as [protobuf.js versions before 2020](https://github.com/protocolbuffers/protobuf/issues/1701). 22* `PB_CONVERT_DOUBLE_FLOAT`: Convert doubles to floats for platforms that do not support 64-bit `double` datatype. Mainly `AVR` processors. 23* `PB_VALIDATE_UTF8`: Check whether incoming strings are valid UTF-8 sequences. Adds a small performance and code size penalty. 24* `PB_C99_STATIC_ASSERT`: Use C99 style negative array trick for static assertions. For compilers that do not support C11 standard. 25* `PB_NO_STATIC_ASSERT`: Disable static assertions at compile time. Only for compilers with limited support of C standards. 26 27The `PB_MAX_REQUIRED_FIELDS` and `PB_FIELD_32BIT` settings allow 28raising some datatype limits to suit larger messages. Their need is 29recognized automatically by C-preprocessor `#if`-directives in the 30generated `.pb.c` files. The default setting is to use the smallest 31datatypes (least resources used). 32 33## Generator options 34 35Generator options affect how the `.proto` files get converted to `.pb.c` and `.pb.h.` files. 36 37Most options are related to specific message or field in `.proto` file. 38The full set of available options is defined in [nanopb.proto](https://github.com/nanopb/nanopb/blob/master/generator/proto/nanopb.proto). Here is a list of the most common options, but see the file for a full list: 39 40* `max_size`: Allocated maximum size for `bytes` and `string` fields. For strings, this includes the terminating zero. 41* `max_length`: Maximum length for `string` fields. Setting this is equivalent to setting `max_size` to a value of length + 1. 42* `max_count`: Allocated maximum number of entries in arrays (`repeated` fields). 43* `type`: Select how memory is allocated for the generated field. Default value is `FT_DEFAULT`, which defaults to `FT_STATIC` when possible and `FT_CALLBACK` if not possible. You can use `FT_CALLBACK`, `FT_POINTER`, `FT_STATIC` or `FT_IGNORE` to select a callback field, a dynamically allocate dfield, a statically allocated field or to completely ignore the field. 44* `long_names`: Prefix the enum name to the enum value in definitions, i.e. `EnumName_EnumValue`. Enabled by default. 45* `packed_struct`: Make the generated structures packed, which saves some RAM space but slows down execution. This can only be used if the CPU supports unaligned access to variables. 46* `skip_message`: Skip a whole message from generation. Can be used to remove message types that are not needed in an application. 47* `no_unions`: Generate `oneof` fields as multiple optional fields instead of a C `union {}`. 48* `anonymous_oneof`: Generate `oneof` fields as an anonymous union. 49* `msgid`: Specifies a unique id for this message type. Can be used by user code as an identifier. 50* `fixed_length`: Generate `bytes` fields with a constant length defined by `max_size`. A separate `.size` field will then not be generated. 51* `fixed_count`: Generate arrays with constant length defined by `max_count`. 52* `package`: Package name that applies only for nanopb generator. Defaults to name defined by `package` keyword in .proto file, which applies for all languages. 53* `int_size`: Override the integer type of a field. For example, specify `int_size = IS_8` to convert `int32` from protocol definition into `int8_t` in the structure. When used with enum types, the size of the generated enum can be specified (C++ only) 54 55These options can be defined for the .proto files before they are 56converted using the nanopb-generator.py. There are three ways to define 57the options: 58 591. Using a separate .options file. This allows using wildcards for 60 applying same options to multiple fields. 612. Defining the options on the command line of nanopb_generator.py. 62 This only makes sense for settings that apply to a whole file. 633. Defining the options in the .proto file using the nanopb extensions. 64 This keeps the options close to the fields they apply to, but can be 65 problematic if the same .proto file is shared with many projects. 66 67The effect of the options is the same no matter how they are given. The 68most common purpose is to define maximum size for string fields in order 69to statically allocate them. 70 71### Defining the options in a .options file 72 73The preferred way to define options is to have a separate file 74'myproto.options' in the same directory as the 'myproto.proto'. : 75 76 # myproto.proto 77 message MyMessage { 78 required string name = 1; 79 repeated int32 ids = 4; 80 } 81 82 # myproto.options 83 MyMessage.name max_size:40 84 MyMessage.ids max_count:5 85 86The generator will automatically search for this file and read the 87options from it. The file format is as follows: 88 89- Lines starting with `#` or `//` are regarded as comments. 90- Blank lines are ignored. 91- All other lines should start with a field name pattern, followed by 92 one or more options. For example: `MyMessage.myfield max_size:5 max_count:10`. 93- The field name pattern is matched against a string of form 94 `Message.field`. For nested messages, the string is 95 `Message.SubMessage.field`. A whole file can be matched by its 96 filename `dir/file.proto`. 97- The field name pattern may use the notation recognized by Python 98 fnmatch(): 99 - `*` matches any part of string, like `Message.*` for all 100 fields 101 - `?` matches any single character 102 - `[seq]` matches any of characters `s`, `e` and `q` 103 - `[!seq]` matches any other character 104- The options are written as `option_name:option_value` and 105 several options can be defined on same line, separated by 106 whitespace. 107- Options defined later in the file override the ones specified 108 earlier, so it makes sense to define wildcard options first in the 109 file and more specific ones later. 110 111To debug problems in applying the options, you can use the `-v` option 112for the nanopb generator. With protoc, plugin options are specified with 113`--nanopb_opt`: 114 115 nanopb_generator -v message.proto # When invoked directly 116 protoc ... --nanopb_opt=-v --nanopb_out=. message.proto # When invoked through protoc 117 118Protoc doesn't currently pass include path into plugins. Therefore if 119your `.proto` is in a subdirectory, nanopb may have trouble finding the 120associated `.options` file. A workaround is to specify include path 121separately to the nanopb plugin, like: 122 123 protoc -Isubdir --nanopb_opt=-Isubdir --nanopb_out=. message.proto 124 125If preferred, the name of the options file can be set using generator 126argument `-f`. 127 128### Defining the options in the .proto file 129 130The .proto file format allows defining custom options for the fields. 131The nanopb library comes with *nanopb.proto* which does exactly that, 132allowing you do define the options directly in the .proto file: 133 134~~~~ protobuf 135import "nanopb.proto"; 136 137message MyMessage { 138 required string name = 1 [(nanopb).max_size = 40]; 139 repeated int32 ids = 4 [(nanopb).max_count = 5]; 140} 141~~~~ 142 143A small complication is that you have to set the include path of protoc 144so that nanopb.proto can be found. Therefore, to compile a .proto file 145which uses options, use a protoc command similar to: 146 147 protoc -Inanopb/generator/proto -I. --nanopb_out=. message.proto 148 149The options can be defined in file, message and field scopes: 150 151~~~~ protobuf 152option (nanopb_fileopt).max_size = 20; // File scope 153message Message 154{ 155 option (nanopb_msgopt).max_size = 30; // Message scope 156 required string fieldsize = 1 [(nanopb).max_size = 40]; // Field scope 157} 158~~~~ 159 160### Defining the options on command line 161 162The nanopb_generator.py has a simple command line option `-s OPTION:VALUE`. 163The setting applies to the whole file that is being processed. 164 165There are also a few command line options that cannot be applied using the 166other mechanisms, as they affect the whole generation: 167 168* `--c-style`: Modify symbol names to better match C naming conventions. 169* `--custom-style`: Modify symbol names by providing your own styler implementation. 170* `--no-timestamp`: Do not add timestamp to generated files. 171* `--strip-path`: Remove relative path from generated `#include` directives. 172* `--cpp-descriptors`: Generate extra convenience definitions for use from C++ 173 174For a full list of generator command line options, use `nanopb_generator.py --help`: 175 176 Usage: nanopb_generator.py [options] file.pb ... 177 178 Options: 179 -h, --help show this help message and exit 180 -V, --version Show version info and exit (add -v for protoc version 181 info) 182 -x FILE Exclude file from generated #include list. 183 -e EXTENSION, --extension=EXTENSION 184 Set extension to use instead of '.pb' for generated 185 files. [default: .pb] 186 -H EXTENSION, --header-extension=EXTENSION 187 Set extension to use for generated header files. 188 [default: .h] 189 -S EXTENSION, --source-extension=EXTENSION 190 Set extension to use for generated source files. 191 [default: .c] 192 -f FILE, --options-file=FILE 193 Set name of a separate generator options file. 194 -I DIR, --options-path=DIR, --proto-path=DIR 195 Search path for .options and .proto files. Also 196 determines relative paths for output directory 197 structure. 198 --error-on-unmatched Stop generation if there are unmatched fields in 199 options file 200 --no-error-on-unmatched 201 Continue generation if there are unmatched fields in 202 options file (default) 203 -D OUTPUTDIR, --output-dir=OUTPUTDIR 204 Output directory of .pb.h and .pb.c files 205 -Q FORMAT, --generated-include-format=FORMAT 206 Set format string to use for including other .pb.h 207 files. Value can be 'quote', 'bracket' or a format 208 string. [default: #include "%s"] 209 -L FORMAT, --library-include-format=FORMAT 210 Set format string to use for including the nanopb pb.h 211 header. Value can be 'quote', 'bracket' or a format 212 string. [default: #include <%s>] 213 --strip-path Strip directory path from #included .pb.h file name 214 --no-strip-path Opposite of --strip-path (default since 0.4.0) 215 --cpp-descriptors Generate C++ descriptors to lookup by type (e.g. 216 pb_field_t for a message) 217 -T, --no-timestamp Don't add timestamp to .pb.h and .pb.c preambles 218 (default since 0.4.0) 219 -t, --timestamp Add timestamp to .pb.h and .pb.c preambles 220 -q, --quiet Don't print anything except errors. 221 -v, --verbose Print more information. 222 -s OPTION:VALUE Set generator option (max_size, max_count etc.). 223 --protoc-opt=OPTION Pass an option to protoc when compiling .proto files 224 --protoc-insertion-points 225 Include insertion point comments in output for use by 226 custom protoc plugins 227 -C, --c-style Use C naming convention. 228 --custom-style=MODULE.CLASS 229 Use a custom naming convention from a module/class 230 that defines the methods from the NamingStyle class to 231 be overridden. When paired with the -C/--c-style 232 option, the NamingStyleC class is the fallback, 233 otherwise it's the NamingStyle class. 234 235 Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. Output will 236 be written to file.pb.h and file.pb.c. 237 238## pb.h 239 240### pb_byte_t 241 242Type used for storing byte-sized data, such as raw binary input and 243bytes-type fields. 244 245 typedef uint_least8_t pb_byte_t; 246 247For most platforms this is equivalent to `uint8_t`. Some platforms 248however do not support 8-bit variables, and on those platforms 16 or 32 249bits need to be used for each byte. 250 251### pb_size_t 252 253Type used for storing tag numbers and sizes of message fields. By 254default the type is 16-bit: 255 256 typedef uint_least16_t pb_size_t; 257 258If tag numbers or fields larger than 65535 are needed, `PB_FIELD_32BIT` 259option can be used to change the type to 32-bit value. 260 261### pb_type_t 262 263Type used to store the type of each field, to control the 264encoder/decoder behaviour. 265 266 typedef uint_least8_t pb_type_t; 267 268The low-order nibble of the enumeration values defines the function that 269can be used for encoding and decoding the field data: 270 271| LTYPE identifier |Value |Storage format 272| ---------------------------------|-------|------------------------------------------------ 273| `PB_LTYPE_BOOL` |0x00 |Boolean. 274| `PB_LTYPE_VARINT` |0x01 |Integer. 275| `PB_LTYPE_UVARINT` |0x02 |Unsigned integer. 276| `PB_LTYPE_SVARINT` |0x03 |Integer, zigzag encoded. 277| `PB_LTYPE_FIXED32` |0x04 |32-bit integer or floating point. 278| `PB_LTYPE_FIXED64` |0x05 |64-bit integer or floating point. 279| `PB_LTYPE_BYTES` |0x06 |Structure with `size_t` field and byte array. 280| `PB_LTYPE_STRING` |0x07 |Null-terminated string. 281| `PB_LTYPE_SUBMESSAGE` |0x08 |Submessage structure. 282| `PB_LTYPE_SUBMSG_W_CB` |0x09 |Submessage with pre-decoding callback. 283| `PB_LTYPE_EXTENSION` |0x0A |Pointer to `pb_extension_t`. 284| `PB_LTYPE_FIXED_LENGTH_BYTES` |0x0B |Inline `pb_byte_t` array of fixed size. 285 286The bits 4-5 define whether the field is required, optional or repeated. 287There are separate definitions for semantically different modes, even 288though some of them share values and are distinguished based on values 289of other fields: 290 291 |HTYPE identifier |Value |Field handling 292 |---------------------|-------|-------------------------------------------------------------------------------------------- 293 |`PB_HTYPE_REQUIRED` |0x00 |Verify that field exists in decoded message. 294 |`PB_HTYPE_OPTIONAL` |0x10 |Use separate `has_<field>` boolean to specify whether the field is present. 295 |`PB_HTYPE_SINGULAR` |0x10 |Proto3 field, which is present when its value is non-zero. 296 |`PB_HTYPE_REPEATED` |0x20 |A repeated field with preallocated array. Separate `<field>_count` for number of items. 297 |`PB_HTYPE_FIXARRAY` |0x20 |A repeated field that has constant length. 298 |`PB_HTYPE_ONEOF` |0x30 |Oneof-field, only one of each group can be present. 299 300The bits 6-7 define the how the storage for the field is allocated: 301 302|ATYPE identifier |Value |Allocation method 303|---------------------|-------|-------------------------------------------------------------------------------------------- 304|`PB_ATYPE_STATIC` |0x00 |Statically allocated storage in the structure. 305|`PB_ATYPE_POINTER` |0x80 |Dynamically allocated storage. Struct field contains a pointer to the storage. 306|`PB_ATYPE_CALLBACK` |0x40 |A field with dynamic storage size. Struct field contains a pointer to a callback function. 307 308### pb_msgdesc_t 309 310Autogenerated structure that contains information about a message and 311pointers to the field descriptors. Use functions defined in 312`pb_common.h` to process the field information. 313 314 typedef struct pb_msgdesc_s pb_msgdesc_t; 315 struct pb_msgdesc_s { 316 pb_size_t field_count; 317 const uint32_t *field_info; 318 const pb_msgdesc_t * const * submsg_info; 319 const pb_byte_t *default_value; 320 321 bool (*field_callback)(pb_istream_t *istream, pb_ostream_t *ostream, const pb_field_iter_t *field); 322 }; 323 324| | | 325|-----------------|--------------------------------------------------------| 326|`field_count` | Total number of fields in the message. 327|`field_info` | Pointer to compact representation of the field information. 328|`submsg_info` | Pointer to array of pointers to descriptors for submessages. 329|`default_value` | Default values for this message as an encoded protobuf message. 330|`field_callback` | Function used to handle all callback fields in this message. By default `pb_default_field_callback()` which loads per-field callbacks from a `pb_callback_t` structure. 331 332### pb_field_iter_t 333 334Describes a single structure field with memory position in relation to 335others. The field information is stored in a compact format and loaded 336into `pb_field_iter_t` by the functions defined in `pb_common.h`. 337 338 typedef struct pb_field_iter_s pb_field_iter_t; 339 struct pb_field_iter_s { 340 const pb_msgdesc_t *descriptor; 341 void *message; 342 343 pb_size_t index; 344 pb_size_t field_info_index; 345 pb_size_t required_field_index; 346 pb_size_t submessage_index; 347 348 pb_size_t tag; 349 pb_size_t data_size; 350 pb_size_t array_size; 351 pb_type_t type; 352 353 void *pField; 354 void *pData; 355 void *pSize; 356 357 const pb_msgdesc_t *submsg_desc; 358 }; 359 360| | | 361|----------------------|--------------------------------------------------------| 362| descriptor | Pointer to `pb_msgdesc_t` for the message that contains this field. 363| message | Pointer to the start of the message structure. 364| index | Index of the field inside the message 365| field_info_index | Index to the internal `field_info` array 366| required_field_index | Index that counts only the required fields 367| submessage_index | Index that counts only submessages 368| tag | Tag number defined in `.proto` file for this field. 369| data_size | `sizeof()` of the field in the structure. For repeated fields this is for a single array entry. 370| array_size | Maximum number of items in a statically allocated array. 371| type | Type ([pb_type_t](#pb_type_t)) of the field. 372| pField | Pointer to the field storage in the structure. 373| pData | Pointer to data contents. For arrays and pointers this can be different than `pField`. 374| pSize | Pointer to count or has field, or NULL if this field doesn't have such. 375| submsg_desc | For submessage fields, points to the descriptor for the submessage. 376 377By default [pb_size_t](#pb_size_t) is 16-bit, limiting the sizes and 378tags to 65535. The limit can be raised by defining `PB_FIELD_32BIT`. 379 380### pb_bytes_array_t 381 382An byte array with a field for storing the length: 383 384 typedef struct { 385 pb_size_t size; 386 pb_byte_t bytes[1]; 387 } pb_bytes_array_t; 388 389In an actual array, the length of `bytes` may be different. The macros 390`PB_BYTES_ARRAY_T()` and `PB_BYTES_ARRAY_T_ALLOCSIZE()` 391are used to allocate variable length storage for bytes fields. 392 393### pb_callback_t 394 395Part of a message structure, for fields with type PB_HTYPE_CALLBACK: 396 397 typedef struct _pb_callback_t pb_callback_t; 398 struct _pb_callback_t { 399 union { 400 bool (*decode)(pb_istream_t *stream, const pb_field_iter_t *field, void **arg); 401 bool (*encode)(pb_ostream_t *stream, const pb_field_iter_t *field, void * const *arg); 402 } funcs; 403 404 void *arg; 405 }; 406 407A pointer to the *arg* is passed to the callback when calling. It can be 408used to store any information that the callback might need. Note that 409this is a double pointer. If you set `field.arg` to point to 410`&data` in your main code, in the callback you can access it like this: 411 412 myfunction(*arg); /* Gives pointer to data as argument */ 413 myfunction(*(data_t*)*arg); /* Gives value of data as argument */ 414 *arg = newdata; /* Alters value of field.arg in structure */ 415 416When calling [pb_encode](#pb_encode), `funcs.encode` is used, and 417similarly when calling [pb_decode](#pb_decode), `funcs.decode` is used. 418The function pointers are stored in the same memory location but are of 419incompatible types. You can set the function pointer to NULL to skip the 420field. 421 422### pb_wire_type_t 423 424Protocol Buffers wire types. These are used with 425[pb_encode_tag](#pb_encode_tag). : 426 427 typedef enum { 428 PB_WT_VARINT = 0, 429 PB_WT_64BIT = 1, 430 PB_WT_STRING = 2, 431 PB_WT_32BIT = 5 432 } pb_wire_type_t; 433 434### pb_extension_type_t 435 436Defines the handler functions and auxiliary data for a field that 437extends another message. Usually autogenerated by 438`nanopb_generator.py`. 439 440 typedef struct { 441 bool (*decode)(pb_istream_t *stream, pb_extension_t *extension, 442 uint32_t tag, pb_wire_type_t wire_type); 443 bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension); 444 const void *arg; 445 } pb_extension_type_t; 446 447In the normal case, the function pointers are `NULL` and the decoder and 448encoder use their internal implementations. The internal implementations 449assume that `arg` points to a [pb_field_iter_t](#pb_field_iter_t) 450that describes the field in question. 451 452To implement custom processing of unknown fields, you can provide 453pointers to your own functions. Their functionality is mostly the same 454as for normal callback fields, except that they get called for any 455unknown field when decoding. 456 457### pb_extension_t 458 459Ties together the extension field type and the storage for the field 460value. For message structs that have extensions, the generator will 461add a `pb_extension_t*` field. It should point to a linked list of 462extensions. 463 464 typedef struct { 465 const pb_extension_type_t *type; 466 void *dest; 467 pb_extension_t *next; 468 bool found; 469 } pb_extension_t; 470 471| | | 472|----------------------|--------------------------------------------------------| 473| type | Pointer to the structure that defines the callback functions. 474| dest | Pointer to the variable that stores the field value (as used by the default extension callback functions.) 475| next | Pointer to the next extension handler, or `NULL` for last handler. 476| found | Decoder sets this to true if the extension was found. 477 478### PB_GET_ERROR 479 480Get the current error message from a stream, or a placeholder string if 481there is no error message: 482 483 #define PB_GET_ERROR(stream) (string expression) 484 485This should be used for printing errors, for example: 486 487 if (!pb_decode(...)) 488 { 489 printf("Decode failed: %s\n", PB_GET_ERROR(stream)); 490 } 491 492The macro only returns pointers to constant strings (in code memory), so 493that there is no need to release the returned pointer. 494 495### PB_RETURN_ERROR 496 497Set the error message and return false: 498 499 #define PB_RETURN_ERROR(stream,msg) (sets error and returns false) 500 501This should be used to handle error conditions inside nanopb functions 502and user callback functions: 503 504 if (error_condition) 505 { 506 PB_RETURN_ERROR(stream, "something went wrong"); 507 } 508 509The *msg* parameter must be a constant string. 510 511### PB_BIND 512 513This macro generates the [pb_msgdesc_t](#pb_msgdesc_t) and associated 514arrays, based on a list of fields in [X-macro](https://en.wikipedia.org/wiki/X_Macro) format. : 515 516 #define PB_BIND(msgname, structname, width) ... 517 518| | | 519|----------------------|--------------------------------------------------------| 520| msgname | Name of the message type. Expects `msgname_FIELDLIST` macro to exist. 521| structname | Name of the C structure to bind to. 522| width | Number of words per field descriptor, or `AUTO` to use minimum size possible. 523 524This macro is automatically invoked inside the autogenerated `.pb.c` 525files. User code can also call it to bind message types with custom 526structures or class types. 527 528## pb_encode.h 529 530### pb_ostream_from_buffer 531 532Constructs an output stream for writing into a memory buffer. It uses an internal callback that 533stores the pointer in stream `state` field. : 534 535 pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize); 536 537| | | 538|----------------------|--------------------------------------------------------| 539| buf | Memory buffer to write into. 540| bufsize | Maximum number of bytes to write. 541| returns | An output stream. 542 543After writing, you can check `stream.bytes_written` to find out how 544much valid data there is in the buffer. This should be passed as the 545message length on decoding side. 546 547### pb_write 548 549Writes data to an output stream. Always use this function, instead of 550trying to call stream callback manually. : 551 552 bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); 553 554| | | 555|----------------------|--------------------------------------------------------| 556| stream | Output stream to write to. 557| buf | Pointer to buffer with the data to be written. 558| count | Number of bytes to write. 559| returns | True on success, false if maximum length is exceeded or an IO error happens. 560 561> **NOTE:** If an error happens, *bytes_written* is not incremented. Depending on 562the callback used, calling pb_write again after it has failed once may 563cause undefined behavior. Nanopb itself never does this, instead it 564returns the error to user application. The builtin 565`pb_ostream_from_buffer` is safe to call again after failed write. 566 567### pb_encode 568 569Encodes the contents of a structure as a protocol buffers message and 570writes it to output stream. : 571 572 bool pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct); 573 574| | | 575|----------------------|--------------------------------------------------------| 576| stream | Output stream to write to. 577| fields | Message descriptor, usually autogenerated. 578| src_struct | Pointer to the message structure. Must match `fields` descriptor. 579| returns | True on success, false on any error condition. Error message is set to `stream->errmsg`. 580 581Normally pb_encode simply walks through the fields description array 582and serializes each field in turn. However, submessages must be 583serialized twice: first to calculate their size and then to actually 584write them to output. This causes some constraints for callback fields, 585which must return the same data on every call. 586 587### pb_encode_ex 588 589Encodes the message, with extended behavior set by flags: 590 591 bool pb_encode_ex(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct, unsigned int flags); 592 593| | | 594|----------------------|--------------------------------------------------------| 595| stream | Output stream to write to. 596| fields | Message descriptor, usually autogenerated. 597| src_struct | Pointer to the message structure. Must match `fields` descriptor. 598| flags | Extended options, see below. 599| returns | True on success, false on any error condition. Error message is set to `stream->errmsg`. 600 601The options that can be defined are: 602 603* `PB_ENCODE_DELIMITED`: Indicate the length of the message by prefixing with a varint-encoded length. Compatible with `parseDelimitedFrom` in Google's protobuf library. 604* `PB_ENCODE_NULLTERMINATED`: Indicate the length of the message by appending a zero tag value after it. Supported by nanopb decoder, but not by most other protobuf libraries. 605 606### pb_get_encoded_size 607 608Calculates the length of the encoded message. 609 610 bool pb_get_encoded_size(size_t *size, const pb_msgdesc_t *fields, const void *src_struct); 611 612| | | 613|----------------------|--------------------------------------------------------| 614| size | Calculated size of the encoded message. 615| fields | Message descriptor, usually autogenerated. 616| src_struct | Pointer to the data that will be serialized. 617| returns | True on success, false on detectable errors in field description or if a field encoder returns false. 618 619### Callback field encoders 620The functions with names `pb_encode_<datatype>` are used when dealing with 621callback fields. The typical reason for using callbacks is to have an 622array of unlimited size. In that case, [pb_encode](#pb_encode) will 623call your callback function, which in turn will call `pb_encode_<datatype>` 624functions repeatedly to write out values. 625 626The tag of a field must be encoded first with 627[pb_encode_tag_for_field](#pb_encode_tag_for_field). After that, you 628can call exactly one of the content-writing functions to encode the 629payload of the field. For repeated fields, you can repeat this process 630multiple times. 631 632Writing packed arrays is a little bit more involved: you need to use 633`pb_encode_tag` and specify `PB_WT_STRING` as the wire 634type. Then you need to know exactly how much data you are going to 635write, and use [pb_encode_varint](#pb_encode_varint) to write out the 636number of bytes before writing the actual data. Substreams can be used 637to determine the number of bytes beforehand; see 638[pb_encode_submessage](#pb_encode_submessage) source code for an 639example. 640 641See [Google Protobuf Encoding Format Documentation](https://developers.google.com/protocol-buffers/docs/encoding) 642for background information on the Protobuf wire format. 643 644#### pb_encode_tag 645 646Starts a field in the Protocol Buffers binary format: encodes the field 647number and the wire type of the data. 648 649 bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number); 650 651| | | 652|----------------------|--------------------------------------------------------| 653| stream | Output stream to write to. 1-5 bytes will be written. 654| wiretype | `PB_WT_VARINT`, `PB_WT_64BIT`, `PB_WT_STRING` or `PB_WT_32BIT` 655| field_number | Identifier for the field, defined in the .proto file. You can get it from `field->tag`. 656| returns | True on success, false on IO error. 657 658#### pb_encode_tag_for_field 659 660Same as [pb_encode_tag](#pb_encode_tag), except takes the parameters 661from a `pb_field_iter_t` structure. 662 663 bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_iter_t *field); 664 665| | | 666|----------------------|--------------------------------------------------------| 667| stream | Output stream to write to. 1-5 bytes will be written. 668| field | Field iterator for this field. 669| returns | True on success, false on IO error or unknown field type. 670 671This function only considers the `PB_LTYPE` of the field. You can use it from 672your field callbacks, because the source generator writes correct `LTYPE` 673also for callback type fields. 674 675Wire type mapping is as follows: 676 677| LTYPEs | Wire type 678|--------------------------------------------------|----------------- 679| BOOL, VARINT, UVARINT, SVARINT | PB_WT_VARINT 680| FIXED64 | PB_WT_64BIT 681| STRING, BYTES, SUBMESSAGE, FIXED_LENGTH_BYTES | PB_WT_STRING 682| FIXED32 | PB_WT_32BIT 683 684#### pb_encode_varint 685 686Encodes a signed or unsigned integer in the 687[varint](http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints) 688format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`: 689 690 bool pb_encode_varint(pb_ostream_t *stream, uint64_t value); 691 692| | | 693|----------------------|--------------------------------------------------------| 694| stream | Output stream to write to. 1-10 bytes will be written. 695| value | Value to encode, cast to `uint64_t`. 696| returns | True on success, false on IO error. 697 698> **NOTE:** Value will be converted to `uint64_t` in the argument. 699> To encode signed values, the argument should be cast to `int64_t` first for correct sign extension. 700 701#### pb_encode_svarint 702 703Encodes a signed integer in the [zig-zagged](https://developers.google.com/protocol-buffers/docs/encoding#signed_integers) format. 704Works for fields of type `sint32` and `sint64`: 705 706 bool pb_encode_svarint(pb_ostream_t *stream, int64_t value); 707 708(parameters are the same as for [pb_encode_varint](#pb_encode_varint) 709 710#### pb_encode_string 711 712Writes the length of a string as varint and then contents of the string. 713Works for fields of type `bytes` and `string`: 714 715 bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size); 716 717| | | 718|----------------------|--------------------------------------------------------| 719| stream | Output stream to write to. 720| buffer | Pointer to string data. 721| size | Number of bytes in the string. Pass `strlen(s)` for strings. 722| returns | True on success, false on IO error. 723 724#### pb_encode_fixed32 725 726Writes 4 bytes to stream and swaps bytes on big-endian architectures. 727Works for fields of type `fixed32`, `sfixed32` and `float`: 728 729 bool pb_encode_fixed32(pb_ostream_t *stream, const void *value); 730 731| | | 732|----------------------|--------------------------------------------------------| 733| stream | Output stream to write to. 4 bytes will be written. 734| value | Pointer to a 4-bytes large C variable, for example `uint32_t foo;`. 735| returns | True on success, false on IO error. 736 737#### pb_encode_fixed64 738 739Writes 8 bytes to stream and swaps bytes on big-endian architecture. 740Works for fields of type `fixed64`, `sfixed64` and `double`: 741 742 bool pb_encode_fixed64(pb_ostream_t *stream, const void *value); 743 744| | | 745|----------------------|--------------------------------------------------------| 746| stream | Output stream to write to. 8 bytes will be written. 747| value | Pointer to a 8-bytes large C variable, for example `uint64_t foo;`. 748| returns | True on success, false on IO error. 749 750#### pb_encode_float_as_double 751 752Encodes a 32-bit `float` value so that it appears like a 64-bit `double` in the encoded message. 753This is sometimes needed when platforms like AVR that do not support 64-bit `double` need to communicate using a 754message type that contains `double` fields. 755 756 bool pb_encode_float_as_double(pb_ostream_t *stream, float value); 757 758| | | 759|----------------------|--------------------------------------------------------| 760| stream | Output stream to write to. 8 bytes will be written. 761| value | Float value to encode. 762| returns | True on success, false on IO error. 763 764#### pb_encode_submessage 765 766Encodes a submessage field, including the size header for it. Works for 767fields of any message type. 768 769 bool pb_encode_submessage(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct); 770 771| | | 772|----------------------|--------------------------------------------------------| 773| stream | Output stream to write to. 774| fields | Pointer to the autogenerated message descriptor for the submessage type, e.g. `MyMessage_fields`. 775| src | Pointer to the structure where submessage data is. 776| returns | True on success, false on IO errors, pb_encode errors or if submessage size changes between calls. 777 778In Protocol Buffers format, the submessage size must be written before 779the submessage contents. Therefore, this function has to encode the 780submessage twice in order to know the size beforehand. 781 782If the submessage contains callback fields, the callback function might 783misbehave and write out a different amount of data on the second call. 784This situation is recognized and `false` is returned, but garbage will 785be written to the output before the problem is detected. 786 787## pb_decode.h 788 789### pb_istream_from_buffer 790 791Helper function for creating an input stream that reads data from a 792memory buffer. 793 794 pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize); 795 796| | | 797|----------------------|--------------------------------------------------------| 798| buf | Pointer to byte array to read from. 799| bufsize | Size of the byte array. Typically length of the message to be decoded. 800| returns | An input stream ready to use. 801 802### pb_read 803 804Read data from input stream. Always use this function, don't try to 805call the stream callback directly. 806 807 bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); 808 809| | | 810|----------------------|--------------------------------------------------------| 811| stream | Input stream to read from. 812| buf | Buffer to store the data to, or `NULL` to just read data without storing it anywhere. 813| count | Number of bytes to read. 814| returns | True on success, false if `stream->bytes_left` is less than `count` or if an IO error occurs. 815 816End of file is signalled by `stream->bytes_left` being zero after pb_read returns false. 817 818### pb_decode 819 820Read and decode all fields of a structure. Reads until EOF on input 821stream. 822 823 bool pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct); 824 825| | | 826|----------------------|--------------------------------------------------------| 827| stream | Input stream to read from. 828| fields | Message descriptor, usually autogenerated. 829| dest_struct | Pointer to message structure where data will be stored. 830| returns | True on success, false on any error condition. Error message will be in `stream->errmsg`. 831 832In Protocol Buffers binary format, end-of-file is only allowed between fields. 833If it happens anywhere else, pb_decode will return `false`. If 834pb_decode returns `false`, you cannot trust any of the data in the 835structure. 836 837For optional fields, this function applies the default value and sets 838`has_<field>` to false if the field is not present. 839 840If `PB_ENABLE_MALLOC` is defined, this function may allocate storage 841for any pointer type fields. In this case, you have to call 842[pb_release](#pb_release) to release the memory after you are done with 843the message. On error return `pb_decode` will release the memory itself. 844 845### pb_decode_ex 846 847Same as [pb_decode](#pb_decode), but allows extended options. 848 849 bool pb_decode_ex(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags); 850 851| | | 852|----------------------|--------------------------------------------------------| 853| stream | Input stream to read from. 854| fields | Message descriptor, usually autogenerated. 855| dest_struct | Pointer to message structure where data will be stored. 856| flags | Extended options, see below 857| returns | True on success, false on any error condition. Error message will be in `stream->errmsg`. 858 859The following options can be defined and combined with bitwise `|` operator: 860 861* `PB_DECODE_NOINIT`: Do not initialize structure before decoding. This can be used to combine multiple messages, or if you have already initialized the message structure yourself. 862 863* `PB_DECODE_DELIMITED`: Expect a length prefix in varint format before message. The counterpart of `PB_ENCODE_DELIMITED`. 864 865* `PB_DECODE_NULLTERMINATED`: Expect the message to be terminated with zero tag. The counterpart of `PB_ENCODE_NULLTERMINATED`. 866 867If `PB_ENABLE_MALLOC` is defined, this function may allocate storage 868for any pointer type fields. In this case, you have to call 869[pb_release](#pb_release) to release the memory after you are done with 870the message. On error return `pb_decode_ex` will release the memory 871itself. 872 873### pb_release 874 875Releases any dynamically allocated fields: 876 877 void pb_release(const pb_msgdesc_t *fields, void *dest_struct); 878 879| | | 880|----------------------|--------------------------------------------------------| 881| fields | Message descriptor, usually autogenerated. 882| dest_struct | Pointer to structure where data is stored. If `NULL`, function does nothing. 883 884This function is only available if `PB_ENABLE_MALLOC` is defined. It 885will release any pointer type fields in the structure and set the 886pointers to `NULL`. 887 888This function is safe to call multiple times, calling it again does nothing. 889 890### pb_decode_tag 891 892Decode the tag that comes before field in the protobuf encoding: 893 894 bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof); 895 896| | | 897|----------------------|--------------------------------------------------------| 898| stream | Input stream to read from. 899| wire_type | Pointer to variable where to store the wire type of the field. 900| tag | Pointer to variable where to store the tag of the field. 901| eof | Pointer to variable where to store end-of-file status. 902| returns | True on success, false on error or EOF. 903 904When the message (stream) ends, this function will return `false` and set 905`eof` to true. On other errors, `eof` will be set to false. 906 907### pb_skip_field 908 909Remove the data for a field from the stream, without actually decoding it: 910 911 bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type); 912 913| | | 914|----------------------|--------------------------------------------------------| 915| stream | Input stream to read from. 916| wire_type | Type of field to skip. 917| returns | True on success, false on IO error. 918 919This function determines the amount of bytes to read based on the wire type. 920For `PB_WT_STRING`, it will read the length prefix of a string or submessage 921to determine its length. 922 923### Callback field decoders 924The functions with names `pb_decode_<datatype>` are used when dealing with callback fields. 925The typical reason for using callbacks is to have an array of unlimited size. 926In that case, [pb_decode](#pb_decode) will call your callback function repeatedly, 927which can then store the values into e.g. filesystem in the order received in. 928 929For decoding numeric (including enumerated and boolean) values, use 930[pb_decode_varint](#pb_decode_varint), [pb_decode_svarint](#pb_decode_svarint), 931[pb_decode_fixed32](#pb_decode_fixed32) and [pb_decode_fixed64](#pb_decode_fixed64). 932They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage. 933 934For decoding strings and bytes fields, the length has already been decoded and the callback function is given a length-limited substream. 935You can therefore check the total length in `stream->bytes_left` and read the data using [pb_read](#pb_read). 936 937Finally, for decoding submessages in a callback, use [pb_decode](#pb_decode) and pass it the `SubMessage_fields` descriptor array. 938 939#### pb_decode_varint 940 941Read and decode a [varint](http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints) 942encoded integer. 943 944 bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest); 945 946| | | 947|----------------------|--------------------------------------------------------| 948| stream | Input stream to read from. 1-10 bytes will be read. 949| dest | Storage for the decoded integer. Value is undefined on error. 950| returns | True on success, false if value exceeds uint64_t range or an IO error happens. 951 952#### pb_decode_varint32 953 954Same as `pb_decode_varint`, but limits the value to 32 bits: 955 956 bool pb_decode_varint32(pb_istream_t *stream, uint32_t *dest); 957 958Parameters are the same as `pb_decode_varint`. This function can be used 959for decoding lengths and other commonly occurring elements that you know 960shouldn't be larger than 32 bit. It will return an error if the value 961exceeds the `uint32_t` datatype. 962 963#### pb_decode_svarint 964 965Similar to [pb_decode_varint](#pb_decode_varint), except that it 966performs zigzag-decoding on the value. This corresponds to the Protocol 967Buffers `sint32` and `sint64` datatypes. : 968 969 bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest); 970 971(parameters are the same as [pb_decode_varint](#pb_decode_varint)) 972 973#### pb_decode_fixed32 974 975Decode a `fixed32`, `sfixed32` or `float` value. 976 977 bool pb_decode_fixed32(pb_istream_t *stream, void *dest); 978 979| | | 980|----------------------|--------------------------------------------------------| 981| stream | Input stream to read from. 4 bytes will be read. 982| dest | Pointer to destination `int32_t`, `uint32_t` or `float`. 983| returns | True on success, false on IO errors. 984 985This function reads 4 bytes from the input stream. On big endian 986architectures, it then reverses the order of the bytes. Finally, it 987writes the bytes to `dest`. 988 989#### pb_decode_fixed64 990 991Decode a `fixed64`, `sfixed64` or `double` value. : 992 993 bool pb_decode_fixed64(pb_istream_t *stream, void *dest); 994 995| | | 996|----------------------|--------------------------------------------------------| 997| stream | Input stream to read from. 8 bytes will be read. 998| dest | Pointer to destination `int64_t`, `uint64_t` or `double`. 999| returns | True on success, false on IO errors. 1000 1001Same as [pb_decode_fixed32](#pb_decode_fixed32), except this reads 8 1002bytes. 1003 1004#### pb_decode_double_as_float 1005 1006Decodes a 64-bit `double` value into a 32-bit `float` 1007variable. Counterpart of [pb_encode_float_as_double](#pb_encode_float_as_double). : 1008 1009 bool pb_decode_double_as_float(pb_istream_t *stream, float *dest); 1010 1011| | | 1012|----------------------|--------------------------------------------------------| 1013| stream | Input stream to read from. 8 bytes will be read. 1014| dest | Pointer to destination *float*. 1015| returns | True on success, false on IO errors. 1016 1017#### pb_make_string_substream 1018 1019Decode the length for a field with wire type `PB_WT_STRING` and create 1020a substream for reading the data. 1021 1022 bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream); 1023 1024| | | 1025|----------------------|--------------------------------------------------------| 1026| stream | Original input stream to read the length and data from. 1027| substream | Storage for a new substream that has limited length. Filled in by the function. 1028| returns | True on success, false if reading the length fails. 1029 1030This function uses `pb_decode_varint` to read an integer from the stream. 1031This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the 1032length, and its callback function and state the same as the parent stream. 1033 1034#### pb_close_string_substream 1035 1036Close the substream created with 1037[pb_make_string_substream](#pb_make_string_substream). 1038 1039 void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream); 1040 1041| | | 1042|----------------------|--------------------------------------------------------| 1043| stream | Original input stream to read data from. 1044| substream | Substream to close 1045 1046This function copies back the state from the substream to the parent stream, 1047and throws away any unread data from the substream. 1048It must be called after done with the substream. 1049 1050## pb_common.h 1051 1052### pb_field_iter_begin 1053 1054Begins iterating over the fields in a message type: 1055 1056 bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_msgdesc_t *desc, void *message); 1057 1058| | | 1059|----------------------|--------------------------------------------------------| 1060| iter | Pointer to destination [pb_field_iter_t](#pb_field_iter_t) variable. 1061| desc | Autogenerated message descriptor. 1062| message | Pointer to message structure. 1063| returns | True on success, false if the message type has no fields. 1064 1065### pb_field_iter_next 1066 1067Advance to the next field in the message: 1068 1069 bool pb_field_iter_next(pb_field_iter_t *iter); 1070 1071| | | 1072|----------------------|--------------------------------------------------------| 1073| iter | Pointer to `pb_field_iter_t` previously initialized by [pb_field_iter_begin](#pb_field_iter_begin). 1074| returns | True on success, false after last field in the message. 1075 1076When the last field in the message has been processed, this function 1077will return false and initialize `iter` back to the first field in the 1078message. 1079 1080### pb_field_iter_find 1081 1082Find a field specified by tag number in the message: 1083 1084 bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag); 1085 1086| | | 1087|----------------------|--------------------------------------------------------| 1088| iter | Pointer to `pb_field_iter_t` previously initialized by [pb_field_iter_begin](#pb_field_iter_begin). 1089| tag | Tag number to search for. 1090| returns | True if field was found, false otherwise. 1091 1092This function is functionally identical to calling `pb_field_iter_next()` until `iter.tag` equals the searched value. 1093Internally this function avoids fully processing the descriptor for intermediate fields. 1094 1095### pb_validate_utf8 1096 1097Validates an UTF8 encoded string: 1098 1099 bool pb_validate_utf8(const char *s); 1100 1101| | | 1102|----------------------|--------------------------------------------------------| 1103| s | Pointer to beginning of a string. 1104| returns | True, if string is valid UTF-8, false otherwise. 1105 1106The protobuf standard requires that `string` fields only contain valid 1107UTF-8 encoded text, while `bytes` fields can contain arbitrary data. 1108When the compilation option `PB_VALIDATE_UTF8` is defined, nanopb will 1109automatically validate strings on both encoding and decoding. 1110 1111User code can call this function to validate strings in e.g. custom 1112callbacks. 1113