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