Improve the detection of missing required fields.
[apps/agl-service-can-low-level.git] / docs / reference.rst
1 =====================
2 Nanopb: API reference
3 =====================
4
5 .. include :: menu.rst
6
7 .. contents ::
8
9 Compilation options
10 ===================
11 The following options can be specified using -D switch given to the C compiler:
12
13 ============================  ==============================================================================================
14 __BIG_ENDIAN__                 Set this if your platform stores integers and floats in big-endian format.
15                                Mixed-endian systems (different layout for ints and floats) are currently not supported.
16 NANOPB_INTERNALS               Set this to expose the field encoder functions that are hidden since nanopb-0.1.3.
17 PB_MAX_REQUIRED_FIELDS         Maximum number of required fields to check for presence. Default value is 64.
18 ============================  ==============================================================================================
19
20 pb.h
21 ====
22
23 pb_type_t
24 ---------
25 Defines the encoder/decoder behaviour that should be used for a field. ::
26
27     typedef enum { ... } pb_type_t;
28
29 The low-order byte of the enumeration values defines the function that can be used for encoding and decoding the field data:
30
31 ==================== ===== ================================================
32 LTYPE identifier     Value Storage format
33 ==================== ===== ================================================
34 PB_LTYPE_VARINT      0x00  Integer.
35 PB_LTYPE_SVARINT     0x01  Integer, zigzag encoded.
36 PB_LTYPE_FIXED       0x02  Integer or floating point.
37 PB_LTYPE_BYTES       0x03  Structure with *size_t* field and byte array.
38 PB_LTYPE_STRING      0x04  Null-terminated string.
39 PB_LTYPE_SUBMESSAGE  0x05  Submessage structure.
40 ==================== ===== ================================================
41
42 The high-order byte defines whether the field is required, optional, repeated or callback:
43
44 ==================== ===== ================================================
45 HTYPE identifier     Value Field handling
46 ==================== ===== ================================================
47 PB_HTYPE_REQUIRED    0x00  Verify that field exists in decoded message.
48 PB_HTYPE_OPTIONAL    0x10  Use separate *has_<field>* boolean to specify
49                            whether the field is present.
50 PB_HTYPE_ARRAY       0x20  A repeated field with preallocated array.
51                            Separate *<field>_count* for number of items.
52 PB_HTYPE_CALLBACK    0x30  A field with dynamic storage size, data is
53                            actually a pointer to a structure containing a
54                            callback function.
55 ==================== ===== ================================================
56
57 pb_field_t
58 ----------
59 Describes a single structure field with memory position in relation to others. The descriptions are usually autogenerated. ::
60
61     typedef struct _pb_field_t pb_field_t;
62     struct _pb_field_t {
63         uint8_t tag;
64         pb_type_t type;
65         uint8_t data_offset;
66         int8_t size_offset;
67         uint8_t data_size;
68         uint8_t array_size;
69         const void *ptr;
70     } pb_packed;
71
72 :tag:           Tag number of the field or 0 to terminate a list of fields.
73 :type:          LTYPE and HTYPE of the field.
74 :data_offset:   Offset of field data, relative to the end of the previous field.
75 :size_offset:   Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data.
76 :data_size:     Size of a single data entry, in bytes. For PB_LTYPE_BYTES, the size of the byte array inside the containing structure. For PB_HTYPE_CALLBACK, size of the C data type if known.
77 :array_size:    Maximum number of entries in an array, if it is an array type.
78 :ptr:           Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE.
79
80 The *uint8_t* datatypes limit the maximum size of a single item to 255 bytes and arrays to 255 items. Compiler will warn "Initializer too large for type" if the limits are exceeded. The types can be changed to larger ones if necessary.
81
82 pb_bytes_array_t
83 ----------------
84 An byte array with a field for storing the length::
85
86     typedef struct {
87         size_t size;
88         uint8_t bytes[1];
89     } pb_bytes_array_t;
90
91 In an actual array, the length of *bytes* may be different.
92
93 pb_callback_t
94 -------------
95 Part of a message structure, for fields with type PB_HTYPE_CALLBACK::
96
97     typedef struct _pb_callback_t pb_callback_t;
98     struct _pb_callback_t {
99         union {
100             bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);
101             bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);
102         } funcs;
103         
104         void *arg;
105     };
106
107 The *arg* is passed to the callback when calling. It can be used to store any information that the callback might need.
108
109 When calling `pb_encode`_, *funcs.encode* is used, and similarly when calling `pb_decode`_, *funcs.decode* is used. The function pointers are stored in the same memory location but are of incompatible types. You can set the function pointer to NULL to skip the field.
110
111 pb_wire_type_t
112 --------------
113 Protocol Buffers wire types. These are used with `pb_encode_tag`_. ::
114
115     typedef enum {
116         PB_WT_VARINT = 0,
117         PB_WT_64BIT  = 1,
118         PB_WT_STRING = 2,
119         PB_WT_32BIT  = 5
120     } pb_wire_type_t;
121
122 pb_encode.h
123 ===========
124
125 pb_ostream_from_buffer
126 ----------------------
127 Constructs an output stream for writing into a memory buffer. This is just a helper function, it doesn't do anything you couldn't do yourself in a callback function. It uses an internal callback that stores the pointer in stream *state* field. ::
128
129     pb_ostream_t pb_ostream_from_buffer(uint8_t *buf, size_t bufsize);
130
131 :buf:           Memory buffer to write into.
132 :bufsize:       Maximum number of bytes to write.
133 :returns:       An output stream.
134
135 After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer.
136
137 pb_write
138 --------
139 Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. ::
140
141     bool pb_write(pb_ostream_t *stream, const uint8_t *buf, size_t count);
142
143 :stream:        Output stream to write to.
144 :buf:           Pointer to buffer with the data to be written.
145 :count:         Number of bytes to write.
146 :returns:       True on success, false if maximum length is exceeded or an IO error happens.
147
148 If an error happens, *bytes_written* is not incremented. Depending on the callback used, calling pb_write again after it has failed once may be dangerous. Nanopb itself never does this, instead it returns the error to user application. The builtin pb_ostream_from_buffer is safe to call again after failed write.
149
150 pb_encode
151 ---------
152 Encodes the contents of a structure as a protocol buffers message and writes it to output stream. ::
153
154     bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
155
156 :stream:        Output stream to write to.
157 :fields:        A field description array, usually autogenerated.
158 :src_struct:    Pointer to the data that will be serialized.
159 :returns:       True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false.
160
161 Normally pb_encode simply walks through the fields description array and serializes each field in turn. However, submessages must be serialized twice: first to calculate their size and then to actually write them to output. This causes some constraints for callback fields, which must return the same data on every call.
162
163 .. sidebar:: Encoding fields manually
164
165     The functions with names *pb_encode_\** are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_encode`_ will call your callback function, which in turn will call *pb_encode_\** functions repeatedly to write out values.
166
167     The tag of a field must be encoded separately with `pb_encode_tag_for_field`_. After that, you can call exactly one of the content-writing functions to encode the payload of the field. For repeated fields, you can repeat this process multiple times.
168
169     Writing packed arrays is a little bit more involved: you need to use `pb_encode_tag` and specify `PB_WT_STRING` as the wire type. Then you need to know exactly how much data you are going to write, and use `pb_encode_varint`_ to write out the number of bytes before writing the actual data. Substreams can be used to determine the number of bytes beforehand; see `pb_encode_submessage`_ source code for an example.
170
171 pb_encode_tag
172 -------------
173 Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. ::
174
175     bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, int field_number);
176
177 :stream:        Output stream to write to. 1-5 bytes will be written.
178 :wiretype:      PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT
179 :field_number:  Identifier for the field, defined in the .proto file. You can get it from field->tag.
180 :returns:       True on success, false on IO error.
181
182 pb_encode_tag_for_field
183 -----------------------
184 Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. ::
185
186     bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
187
188 :stream:        Output stream to write to. 1-5 bytes will be written.
189 :field:         Field description structure. Usually autogenerated.
190 :returns:       True on success, false on IO error or unknown field type.
191
192 This function only considers the LTYPE of the field. You can use it from your field callbacks, because the source generator writes correct LTYPE also for callback type fields.
193
194 Wire type mapping is as follows:
195
196 ========================= ============
197 LTYPEs                    Wire type
198 ========================= ============
199 VARINT, SVARINT           PB_WT_VARINT
200 FIXED64                   PB_WT_64BIT  
201 STRING, BYTES, SUBMESSAGE PB_WT_STRING 
202 FIXED32                   PB_WT_32BIT
203 ========================= ============
204
205 pb_encode_varint
206 ----------------
207 Encodes a signed or unsigned integer in the varint_ format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`::
208
209     bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
210
211 :stream:        Output stream to write to. 1-10 bytes will be written.
212 :value:         Value to encode. Just cast e.g. int32_t directly to uint64_t.
213 :returns:       True on success, false on IO error.
214
215 .. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
216
217 pb_encode_svarint
218 -----------------
219 Encodes a signed integer in the 'zig-zagged' format. Works for fields of type `sint32` and `sint64`::
220
221     bool pb_encode_svarint(pb_ostream_t *stream, int64_t value);
222
223 (parameters are the same as for `pb_encode_varint`_
224
225 pb_encode_string
226 ----------------
227 Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`::
228
229     bool pb_encode_string(pb_ostream_t *stream, const uint8_t *buffer, size_t size);
230
231 :stream:        Output stream to write to.
232 :buffer:        Pointer to string data.
233 :size:          Number of bytes in the string. Pass `strlen(s)` for strings.
234 :returns:       True on success, false on IO error.
235
236 pb_encode_fixed32
237 -----------------
238 Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`::
239
240     bool pb_encode_fixed32(pb_ostream_t *stream, const void *value);
241
242 :stream:    Output stream to write to.
243 :value:     Pointer to a 4-bytes large C variable, for example `uint32_t foo;`.
244 :returns:   True on success, false on IO error.
245
246 pb_encode_fixed64
247 -----------------
248 Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`::
249
250     bool pb_encode_fixed64(pb_ostream_t *stream, const void *value);
251
252 :stream:    Output stream to write to.
253 :value:     Pointer to a 8-bytes large C variable, for example `uint64_t foo;`.
254 :returns:   True on success, false on IO error.
255
256 pb_encode_submessage
257 --------------------
258 Encodes a submessage field, including the size header for it. Works for fields of any message type::
259
260     bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
261
262 :stream:        Output stream to write to.
263 :fields:        Pointer to the autogenerated field description array for the submessage type, e.g. `MyMessage_fields`.
264 :src:           Pointer to the structure where submessage data is.
265 :returns:       True on success, false on IO errors, pb_encode errors or if submessage size changes between calls.
266
267 In Protocol Buffers format, the submessage size must be written before the submessage contents. Therefore, this function has to encode the submessage twice in order to know the size beforehand.
268
269 If the submessage contains callback fields, the callback function might misbehave and write out a different amount of data on the second call. This situation is recognized and *false* is returned, but garbage will be written to the output before the problem is detected.
270
271 pb_decode.h
272 ===========
273
274 pb_istream_from_buffer
275 ----------------------
276 Helper function for creating an input stream that reads data from a memory buffer. ::
277
278     pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize);
279
280 :buf:           Pointer to byte array to read from.
281 :bufsize:       Size of the byte array.
282 :returns:       An input stream ready to use.
283
284 pb_read
285 -------
286 Read data from input stream. Always use this function, don't try to call the stream callback directly. ::
287
288     bool pb_read(pb_istream_t *stream, uint8_t *buf, size_t count);
289
290 :stream:        Input stream to read from.
291 :buf:           Buffer to store the data to, or NULL to just read data without storing it anywhere.
292 :count:         Number of bytes to read.
293 :returns:       True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs.
294
295 End of file is signalled by *stream->bytes_left* being zero after pb_read returns false.
296
297 pb_decode
298 ---------
299 Read and decode all fields of a structure. Reads until EOF on input stream. ::
300
301     bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
302
303 :stream:        Input stream to read from.
304 :fields:        A field description array. Usually autogenerated.
305 :dest_struct:   Pointer to structure where data will be stored.
306 :returns:       True on success, false on IO error, on detectable errors in field description, if a field encoder returns false or if a required field is missing.
307
308 In Protocol Buffers binary format, EOF is only allowed between fields. If it happens anywhere else, pb_decode will return *false*. If pb_decode returns false, you cannot trust any of the data in the structure.
309
310 In addition to EOF, the pb_decode implementation supports terminating a message with a 0 byte. This is compatible with the official Protocol Buffers because 0 is never a valid field tag.
311
312 For optional fields, this function applies the default value and sets *has_<field>* to false if the field is not present.
313
314 pb_decode_varint
315 ----------------
316 Read and decode a varint_ encoded integer. ::
317
318     bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);
319
320 :stream:        Input stream to read from. 1-10 bytes will be read.
321 :dest:          Storage for the decoded integer. Value is undefined on error.
322 :returns:       True on success, false if value exceeds uint64_t range or an IO error happens.
323
324 pb_skip_varint
325 --------------
326 Skip a varint_ encoded integer without decoding it. ::
327
328     bool pb_skip_varint(pb_istream_t *stream);
329
330 :stream:        Input stream to read from. Will read 1 byte at a time until the MSB is clear.
331 :returns:       True on success, false on IO error.
332
333 pb_skip_string
334 --------------
335 Skip a varint-length-prefixed string. This means skipping a value with wire type PB_WT_STRING. ::
336
337     bool pb_skip_string(pb_istream_t *stream);
338
339 :stream:        Input stream to read from.
340 :returns:       True on success, false on IO error or length exceeding uint32_t.
341
342 pb_decode_tag
343 -------------
344 Decode the tag that comes before field in the protobuf encoding::
345
346     bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, int *tag, bool *eof);
347
348 :stream:        Input stream to read from.
349 :wire_type:     Pointer to variable where to store the wire type of the field.
350 :tag:           Pointer to variable where to store the tag of the field.
351 :eof:           Pointer to variable where to store end-of-file status.
352 :returns:       True on success, false on error or EOF.
353
354 When the message (stream) ends, this function will return false and set *eof* to true. On other
355 errors, *eof* will be set to false.
356
357 pb_skip_field
358 -------------
359 Remove the data for a field from the stream, without actually decoding it::
360
361     bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);
362
363 :stream:        Input stream to read from.
364 :wire_type:     Type of field to skip.
365 :returns:       True on success, false on IO error.
366
367 .. sidebar:: Field decoders
368     
369     The functions with names beginning with *pb_dec_* are called field decoders. Each PB_LTYPE has an own field decoder, which handles translating from Protocol Buffers data to C data.
370
371     Each field decoder reads and decodes a single value. For arrays, the decoder is called repeatedly.
372
373     You can use the decoders from your callbacks. Just be aware that the pb_field_t passed to the callback is not directly compatible 
374     with the *varint* field decoders. Instead, you must create a new pb_field_t structure and set the data_size according to the data type 
375     you pass to *dest*, e.g. *field.data_size = sizeof(int);*. Other fields in the *pb_field_t* don't matter.
376
377     The field decoder interface is a bit messy as a result of the interface required inside the nanopb library.
378     Eventually they may be replaced by separate wrapper functions with a more friendly interface.
379
380 pb_dec_varint
381 -------------
382 Field decoder for PB_LTYPE_VARINT. ::
383
384     bool pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
385
386 :stream:        Input stream to read from. 1-10 bytes will be read.
387 :field:         Field description structure. Only *field->data_size* matters.
388 :dest:          Pointer to destination integer. Must have size of *field->data_size* bytes.
389 :returns:       True on success, false on IO errors or if `pb_decode_varint`_ fails.
390
391 This function first calls `pb_decode_varint`_. It then copies the first bytes of the 64-bit result value to *dest*, or on big endian architectures, the last bytes.
392
393 pb_dec_svarint
394 --------------
395 Field decoder for PB_LTYPE_SVARINT. Similar to `pb_dec_varint`_, except that it performs zigzag-decoding on the value. ::
396
397     bool pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
398
399 (parameters are the same as `pb_dec_varint`_)
400
401 pb_dec_fixed32
402 --------------
403 Field decoder for PB_LTYPE_FIXED32. ::
404
405     bool pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
406
407 :stream:        Input stream to read from. 4 bytes will be read.
408 :field:         Not used.
409 :dest:          Pointer to destination *int32_t*, *uint32_t* or *float*.
410 :returns:       True on success, false on IO errors.
411
412 This function reads 4 bytes from the input stream.
413 On big endian architectures, it then reverses the order of the bytes.
414 Finally, it writes the bytes to *dest*.
415
416 pb_dec_fixed64
417 --------------
418 Field decoder for PB_LTYPE_FIXED64. ::
419
420     bool pb_dec_fixed(pb_istream_t *stream, const pb_field_t *field, void *dest);
421
422 :stream:        Input stream to read from. 8 bytes will be read.
423 :field:         Not used.
424 :dest:          Pointer to destination *int64_t*, *uint64_t* or *double*.
425 :returns:       True on success, false on IO errors.
426
427 Same as `pb_dec_fixed32`_, except this reads 8 bytes.
428
429 pb_dec_bytes
430 ------------
431 Field decoder for PB_LTYPE_BYTES. Reads a length-prefixed block of bytes. ::
432
433     bool pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
434
435 **Note:** This is an internal function that is not useful in decoder callbacks. To read bytes fields in callbacks, use 
436 *stream->bytes_left* and `pb_read`_.
437
438 :stream:        Input stream to read from.
439 :field:         Field description structure. Only *field->data_size* matters.
440 :dest:          Pointer to a structure similar to pb_bytes_array_t.
441 :returns:       True on success, false on IO error or if length exceeds the array size.
442
443 This function expects a pointer to a structure with a *size_t* field at start, and a variable sized byte array after it. It will deduce the maximum size of the array from *field->data_size*.
444
445 pb_dec_string
446 -------------
447 Field decoder for PB_LTYPE_STRING. Reads a length-prefixed string. ::
448
449     bool pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
450
451 **Note:** This is an internal function that is not useful in decoder callbacks. To read string fields in callbacks, use 
452 *stream->bytes_left* and `pb_read`_.
453
454 :stream:        Input stream to read from.
455 :field:         Field description structure. Only *field->data_size* matters.
456 :dest:          Pointer to a character array of size *field->data_size*.
457 :returns:       True on success, false on IO error or if length exceeds the array size.
458
459 This function null-terminates the string when successful. On error, the contents of the destination array is undefined.
460
461 pb_dec_submessage
462 -----------------
463 Field decoder for PB_LTYPE_SUBMESSAGE. Calls `pb_decode`_ to perform the actual decoding. ::
464
465     bool pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
466
467 **Note:** This is an internal function that is not useful in decoder callbacks. To read submessage fields in callbacks, use 
468 `pb_decode`_ directly.
469
470 :stream:        Input stream to read from.
471 :field:         Field description structure. Only *field->ptr* matters.
472 :dest:          Pointer to the destination structure.
473 :returns:       True on success, false on IO error or if `pb_decode`_ fails.
474
475 The *field->ptr* should be a pointer to *pb_field_t* array describing the submessage.
476