Add compile-time option PB_BUFFER_ONLY.
[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. Increases stack
18                                usage 1 byte per every 8 fields. Compiler warning will tell if you need this.
19 PB_FIELD_16BIT                 Add support for tag numbers > 255 and fields larger than 255 bytes or 255 array entries.
20                                Increases code size 3 bytes per each field. Compiler error will tell if you need this.
21 PB_FIELD_32BIT                 Add support for tag numbers > 65535 and fields larger than 65535 bytes or 65535 array entries.
22                                Increases code size 9 bytes per each field. Compiler error will tell if you need this.
23 PB_NO_ERRMSG                   Disables the support for error messages; only error information is the true/false return value.
24                                Decreases the code size by a few hundred bytes.
25 PB_BUFFER_ONLY                 Disables the support for custom streams. Only supports encoding to memory buffers.
26                                Speeds up execution and decreases code size slightly.
27 ============================  ================================================================================================
28
29 The PB_MAX_REQUIRED_FIELDS, PB_FIELD_16BIT and PB_FIELD_32BIT settings allow raising some datatype limits to suit larger messages.
30 Their need is recognized automatically by C-preprocessor #if-directives in the generated .pb.h files. The default setting is to use
31 the smallest datatypes (least resources used).
32
33 pb.h
34 ====
35
36 pb_type_t
37 ---------
38 Defines the encoder/decoder behaviour that should be used for a field. ::
39
40     typedef enum { ... } pb_type_t;
41
42 The low-order byte of the enumeration values defines the function that can be used for encoding and decoding the field data:
43
44 ==================== ===== ================================================
45 LTYPE identifier     Value Storage format
46 ==================== ===== ================================================
47 PB_LTYPE_VARINT      0x00  Integer.
48 PB_LTYPE_SVARINT     0x01  Integer, zigzag encoded.
49 PB_LTYPE_FIXED       0x02  Integer or floating point.
50 PB_LTYPE_BYTES       0x03  Structure with *size_t* field and byte array.
51 PB_LTYPE_STRING      0x04  Null-terminated string.
52 PB_LTYPE_SUBMESSAGE  0x05  Submessage structure.
53 ==================== ===== ================================================
54
55 The high-order byte defines whether the field is required, optional, repeated or callback:
56
57 ==================== ===== ================================================
58 HTYPE identifier     Value Field handling
59 ==================== ===== ================================================
60 PB_HTYPE_REQUIRED    0x00  Verify that field exists in decoded message.
61 PB_HTYPE_OPTIONAL    0x10  Use separate *has_<field>* boolean to specify
62                            whether the field is present.
63 PB_HTYPE_ARRAY       0x20  A repeated field with preallocated array.
64                            Separate *<field>_count* for number of items.
65 PB_HTYPE_CALLBACK    0x30  A field with dynamic storage size, data is
66                            actually a pointer to a structure containing a
67                            callback function.
68 ==================== ===== ================================================
69
70 pb_field_t
71 ----------
72 Describes a single structure field with memory position in relation to others. The descriptions are usually autogenerated. ::
73
74     typedef struct _pb_field_t pb_field_t;
75     struct _pb_field_t {
76         uint8_t tag;
77         pb_type_t type;
78         uint8_t data_offset;
79         int8_t size_offset;
80         uint8_t data_size;
81         uint8_t array_size;
82         const void *ptr;
83     } pb_packed;
84
85 :tag:           Tag number of the field or 0 to terminate a list of fields.
86 :type:          LTYPE and HTYPE of the field.
87 :data_offset:   Offset of field data, relative to the end of the previous field.
88 :size_offset:   Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data.
89 :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.
90 :array_size:    Maximum number of entries in an array, if it is an array type.
91 :ptr:           Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE.
92
93 The *uint8_t* datatypes limit the maximum size of a single item to 255 bytes and arrays to 255 items. Compiler will give error if the values are too large. The types can be changed to larger ones by defining *PB_FIELD_16BIT*.
94
95 pb_bytes_array_t
96 ----------------
97 An byte array with a field for storing the length::
98
99     typedef struct {
100         size_t size;
101         uint8_t bytes[1];
102     } pb_bytes_array_t;
103
104 In an actual array, the length of *bytes* may be different.
105
106 pb_callback_t
107 -------------
108 Part of a message structure, for fields with type PB_HTYPE_CALLBACK::
109
110     typedef struct _pb_callback_t pb_callback_t;
111     struct _pb_callback_t {
112         union {
113             bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);
114             bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);
115         } funcs;
116         
117         void *arg;
118     };
119
120 The *arg* is passed to the callback when calling. It can be used to store any information that the callback might need.
121
122 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.
123
124 pb_wire_type_t
125 --------------
126 Protocol Buffers wire types. These are used with `pb_encode_tag`_. ::
127
128     typedef enum {
129         PB_WT_VARINT = 0,
130         PB_WT_64BIT  = 1,
131         PB_WT_STRING = 2,
132         PB_WT_32BIT  = 5
133     } pb_wire_type_t;
134
135 pb_encode.h
136 ===========
137
138 pb_ostream_from_buffer
139 ----------------------
140 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. ::
141
142     pb_ostream_t pb_ostream_from_buffer(uint8_t *buf, size_t bufsize);
143
144 :buf:           Memory buffer to write into.
145 :bufsize:       Maximum number of bytes to write.
146 :returns:       An output stream.
147
148 After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer.
149
150 pb_write
151 --------
152 Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. ::
153
154     bool pb_write(pb_ostream_t *stream, const uint8_t *buf, size_t count);
155
156 :stream:        Output stream to write to.
157 :buf:           Pointer to buffer with the data to be written.
158 :count:         Number of bytes to write.
159 :returns:       True on success, false if maximum length is exceeded or an IO error happens.
160
161 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.
162
163 pb_encode
164 ---------
165 Encodes the contents of a structure as a protocol buffers message and writes it to output stream. ::
166
167     bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
168
169 :stream:        Output stream to write to.
170 :fields:        A field description array, usually autogenerated.
171 :src_struct:    Pointer to the data that will be serialized.
172 :returns:       True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false.
173
174 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.
175
176 .. sidebar:: Encoding fields manually
177
178     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.
179
180     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.
181
182     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.
183
184 pb_encode_tag
185 -------------
186 Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. ::
187
188     bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, int field_number);
189
190 :stream:        Output stream to write to. 1-5 bytes will be written.
191 :wiretype:      PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT
192 :field_number:  Identifier for the field, defined in the .proto file. You can get it from field->tag.
193 :returns:       True on success, false on IO error.
194
195 pb_encode_tag_for_field
196 -----------------------
197 Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. ::
198
199     bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
200
201 :stream:        Output stream to write to. 1-5 bytes will be written.
202 :field:         Field description structure. Usually autogenerated.
203 :returns:       True on success, false on IO error or unknown field type.
204
205 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.
206
207 Wire type mapping is as follows:
208
209 ========================= ============
210 LTYPEs                    Wire type
211 ========================= ============
212 VARINT, SVARINT           PB_WT_VARINT
213 FIXED64                   PB_WT_64BIT  
214 STRING, BYTES, SUBMESSAGE PB_WT_STRING 
215 FIXED32                   PB_WT_32BIT
216 ========================= ============
217
218 pb_encode_varint
219 ----------------
220 Encodes a signed or unsigned integer in the varint_ format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`::
221
222     bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
223
224 :stream:        Output stream to write to. 1-10 bytes will be written.
225 :value:         Value to encode. Just cast e.g. int32_t directly to uint64_t.
226 :returns:       True on success, false on IO error.
227
228 .. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
229
230 pb_encode_svarint
231 -----------------
232 Encodes a signed integer in the 'zig-zagged' format. Works for fields of type `sint32` and `sint64`::
233
234     bool pb_encode_svarint(pb_ostream_t *stream, int64_t value);
235
236 (parameters are the same as for `pb_encode_varint`_
237
238 pb_encode_string
239 ----------------
240 Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`::
241
242     bool pb_encode_string(pb_ostream_t *stream, const uint8_t *buffer, size_t size);
243
244 :stream:        Output stream to write to.
245 :buffer:        Pointer to string data.
246 :size:          Number of bytes in the string. Pass `strlen(s)` for strings.
247 :returns:       True on success, false on IO error.
248
249 pb_encode_fixed32
250 -----------------
251 Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`::
252
253     bool pb_encode_fixed32(pb_ostream_t *stream, const void *value);
254
255 :stream:    Output stream to write to.
256 :value:     Pointer to a 4-bytes large C variable, for example `uint32_t foo;`.
257 :returns:   True on success, false on IO error.
258
259 pb_encode_fixed64
260 -----------------
261 Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`::
262
263     bool pb_encode_fixed64(pb_ostream_t *stream, const void *value);
264
265 :stream:    Output stream to write to.
266 :value:     Pointer to a 8-bytes large C variable, for example `uint64_t foo;`.
267 :returns:   True on success, false on IO error.
268
269 pb_encode_submessage
270 --------------------
271 Encodes a submessage field, including the size header for it. Works for fields of any message type::
272
273     bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
274
275 :stream:        Output stream to write to.
276 :fields:        Pointer to the autogenerated field description array for the submessage type, e.g. `MyMessage_fields`.
277 :src:           Pointer to the structure where submessage data is.
278 :returns:       True on success, false on IO errors, pb_encode errors or if submessage size changes between calls.
279
280 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.
281
282 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.
283
284 pb_decode.h
285 ===========
286
287 pb_istream_from_buffer
288 ----------------------
289 Helper function for creating an input stream that reads data from a memory buffer. ::
290
291     pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize);
292
293 :buf:           Pointer to byte array to read from.
294 :bufsize:       Size of the byte array.
295 :returns:       An input stream ready to use.
296
297 pb_read
298 -------
299 Read data from input stream. Always use this function, don't try to call the stream callback directly. ::
300
301     bool pb_read(pb_istream_t *stream, uint8_t *buf, size_t count);
302
303 :stream:        Input stream to read from.
304 :buf:           Buffer to store the data to, or NULL to just read data without storing it anywhere.
305 :count:         Number of bytes to read.
306 :returns:       True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs.
307
308 End of file is signalled by *stream->bytes_left* being zero after pb_read returns false.
309
310 pb_decode
311 ---------
312 Read and decode all fields of a structure. Reads until EOF on input stream. ::
313
314     bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
315
316 :stream:        Input stream to read from.
317 :fields:        A field description array. Usually autogenerated.
318 :dest_struct:   Pointer to structure where data will be stored.
319 :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.
320
321 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.
322
323 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.
324
325 For optional fields, this function applies the default value and sets *has_<field>* to false if the field is not present.
326
327 pb_decode_noinit
328 ----------------
329 Same as `pb_decode`_, except does not apply the default values to fields. ::
330
331     bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
332
333 (parameters are the same as for `pb_decode`_.)
334
335 The destination structure should be filled with zeros before calling this function. Doing a *memset* manually can be slightly faster than using `pb_decode`_ if you don't need any default values.
336
337 pb_skip_varint
338 --------------
339 Skip a varint_ encoded integer without decoding it. ::
340
341     bool pb_skip_varint(pb_istream_t *stream);
342
343 :stream:        Input stream to read from. Will read 1 byte at a time until the MSB is clear.
344 :returns:       True on success, false on IO error.
345
346 pb_skip_string
347 --------------
348 Skip a varint-length-prefixed string. This means skipping a value with wire type PB_WT_STRING. ::
349
350     bool pb_skip_string(pb_istream_t *stream);
351
352 :stream:        Input stream to read from.
353 :returns:       True on success, false on IO error or length exceeding uint32_t.
354
355 pb_decode_tag
356 -------------
357 Decode the tag that comes before field in the protobuf encoding::
358
359     bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, int *tag, bool *eof);
360
361 :stream:        Input stream to read from.
362 :wire_type:     Pointer to variable where to store the wire type of the field.
363 :tag:           Pointer to variable where to store the tag of the field.
364 :eof:           Pointer to variable where to store end-of-file status.
365 :returns:       True on success, false on error or EOF.
366
367 When the message (stream) ends, this function will return false and set *eof* to true. On other
368 errors, *eof* will be set to false.
369
370 pb_skip_field
371 -------------
372 Remove the data for a field from the stream, without actually decoding it::
373
374     bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);
375
376 :stream:        Input stream to read from.
377 :wire_type:     Type of field to skip.
378 :returns:       True on success, false on IO error.
379
380 .. sidebar:: Decoding fields manually
381     
382     The functions with names beginning with *pb_decode_* are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_decode`_ will call your callback function repeatedly, which can then store the values into e.g. filesystem in the order received in.
383
384     For decoding numeric (including enumerated and boolean) values, use `pb_decode_varint`_, `pb_decode_svarint`_, `pb_decode_fixed32`_ and `pb_decode_fixed64`_. They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage.
385
386     For decoding strings and bytes fields, the length has already been decoded. You can therefore check the total length in *stream->bytes_left* and read the data using `pb_read`_.
387
388     Finally, for decoding submessages in a callback, simply use `pb_decode`_ and pass it the *SubMessage_fields* descriptor array.
389
390 pb_decode_varint
391 ----------------
392 Read and decode a varint_ encoded integer. ::
393
394     bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);
395
396 :stream:        Input stream to read from. 1-10 bytes will be read.
397 :dest:          Storage for the decoded integer. Value is undefined on error.
398 :returns:       True on success, false if value exceeds uint64_t range or an IO error happens.
399
400 pb_decode_svarint
401 -----------------
402 Similar to `pb_decode_varint`_, except that it performs zigzag-decoding on the value. This corresponds to the Protocol Buffers *sint32* and *sint64* datatypes. ::
403
404     bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest);
405
406 (parameters are the same as `pb_decode_varint`_)
407
408 pb_decode_fixed32
409 -----------------
410 Decode a *fixed32*, *sfixed32* or *float* value. ::
411
412     bool pb_decode_fixed32(pb_istream_t *stream, void *dest);
413
414 :stream:        Input stream to read from. 4 bytes will be read.
415 :dest:          Pointer to destination *int32_t*, *uint32_t* or *float*.
416 :returns:       True on success, false on IO errors.
417
418 This function reads 4 bytes from the input stream.
419 On big endian architectures, it then reverses the order of the bytes.
420 Finally, it writes the bytes to *dest*.
421
422 pb_decode_fixed64
423 -----------------
424 Decode a *fixed64*, *sfixed64* or *double* value. ::
425
426     bool pb_dec_fixed(pb_istream_t *stream, const pb_field_t *field, void *dest);
427
428 :stream:        Input stream to read from. 8 bytes will be read.
429 :field:         Not used.
430 :dest:          Pointer to destination *int64_t*, *uint64_t* or *double*.
431 :returns:       True on success, false on IO errors.
432
433 Same as `pb_decode_fixed32`_, except this reads 8 bytes.
434
435 pb_make_string_substream
436 ------------------------
437 Decode the length for a field with wire type *PB_WT_STRING* and create a substream for reading the data. ::
438
439     bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream);
440
441 :stream:        Original input stream to read the length and data from.
442 :substream:     New substream that has limited length. Filled in by the function.
443 :returns:       True on success, false if reading the length fails.
444
445 This function uses `pb_decode_varint`_ to read an integer from the stream. This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the length, and its callback function and state the same as the parent stream.
446
447 pb_close_string_substream
448 -------------------------
449 Close the substream created with `pb_make_string_substream`_. ::
450
451     void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream);
452
453 :stream:        Original input stream to read the length and data from.
454 :substream:     Substream to close
455
456 This function copies back the state from the substream to the parent stream.
457 It must be called after done with the substream.