4c8c874e716df83d9395577d07c0e6422a25a148
[apps/agl-service-can-low-level.git] / docs / reference.rst
1 =====================
2 Nanopb: API reference
3 =====================
4
5 .. contents ::
6
7 pb.h
8 ====
9
10 pb_type_t
11 ---------
12 Defines the encoder/decoder behaviour that should be used for a field. ::
13
14     typedef enum { ... } pb_type_t;
15
16 The low-order byte of the enumeration values defines the function that can be used for encoding and decoding the field data:
17
18 ==================== ===== ================================================
19 LTYPE identifier     Value Storage format
20 ==================== ===== ================================================
21 PB_LTYPE_VARINT      0x00  Integer.
22 PB_LTYPE_SVARINT     0x01  Integer, zigzag encoded.
23 PB_LTYPE_FIXED       0x02  Integer or floating point.
24 PB_LTYPE_BYTES       0x03  Structure with *size_t* field and byte array.
25 PB_LTYPE_STRING      0x04  Null-terminated string.
26 PB_LTYPE_SUBMESSAGE  0x05  Submessage structure.
27 ==================== ===== ================================================
28
29 The high-order byte defines whether the field is required, optional, repeated or callback:
30
31 ==================== ===== ================================================
32 HTYPE identifier     Value Field handling
33 ==================== ===== ================================================
34 PB_HTYPE_REQUIRED    0x00  Verify that field exists in decoded message.
35 PB_HTYPE_OPTIONAL    0x10  Use separate *has_<field>* boolean to specify
36                            whether the field is present.
37 PB_HTYPE_ARRAY       0x20  A repeated field with preallocated array.
38 PB_HTYPE_CALLBACK    0x30  A field with dynamic storage size, data is
39                            actually a pointer to a structure containing a
40                            callback function.
41 ==================== ===== ================================================
42
43 pb_field_t
44 ----------
45 Describes a single structure field with memory position in relation to others. ::
46
47     typedef struct _pb_field_t pb_field_t;
48     struct _pb_field_t {
49         uint8_t tag;
50         pb_type_t type;
51         uint8_t data_offset;
52         int8_t size_offset;
53         uint8_t data_size;
54         uint8_t array_size;
55         const void *ptr;
56     } pb_packed;
57
58 :tag:           Tag number of the field or 0 to terminate a list of fields.
59 :type:          LTYPE and HTYPE of the field.
60 :data_offset:   Offset of field data, relative to the end of the previous field.
61 :size_offset:   Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data.
62 :data_size:     Size of a single data entry, in bytes.
63 :array_size:    Maximum number of entries in an array, if it is an array type.
64 :ptr:           Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE.
65
66 pb_encode.h
67 ===========
68
69 pb_ostream_from_buffer
70 ----------------------
71 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. ::
72
73     pb_ostream_t pb_ostream_from_buffer(uint8_t *buf, size_t bufsize);
74
75 :buf:           Memory buffer to write into.
76 :bufsize:       Maximum number of bytes to write.
77 :returns:       An output stream.
78
79 After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer.
80
81 pb_write
82 --------
83 Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. ::
84
85     bool pb_write(pb_ostream_t *stream, const uint8_t *buf, size_t count);
86
87 :stream:        Output stream to write to.
88 :buf:           Pointer to buffer with the data to be written.
89 :count:         Number of bytes to write.
90 :returns:       True on success, false if maximum length is exceeded or an IO error happens.
91
92 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.
93
94 pb_encode
95 ---------
96 Encodes the contents of a structure as a protocol buffers message and writes it to output stream. ::
97
98     bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
99
100 :stream:        Output stream to write to.
101 :fields:        A field description array, usually autogenerated.
102 :src_struct:    Pointer to the data that will be serialized.
103 :returns:       True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false.
104
105 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.
106
107 pb_encode_varint
108 ----------------
109 Encodes an unsigned integer in the varint_ format. ::
110
111     bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
112
113 :stream:        Output stream to write to. 1-10 bytes will be written.
114 :value:         Value to encode.
115 :returns:       True on success, false on IO error.
116
117 .. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
118
119 pb_encode_tag
120 -------------
121 Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. ::
122
123     bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, int field_number);
124
125 :stream:        Output stream to write to. 1-5 bytes will be written.
126 :wiretype:      PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT
127 :field_number:  Identifier for the field, defined in the .proto file.
128 :returns:       True on success, false on IO error.
129
130 pb_encode_tag_for_field
131 -----------------------
132 Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. ::
133
134     bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
135
136 :stream:        Output stream to write to. 1-5 bytes will be written.
137 :field:         Field description structure. Usually autogenerated.
138 :returns:       True on success, false on IO error or unknown field type.
139
140 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.
141
142 pb_encode_string
143 ----------------
144 Writes the length of a string as varint and then contents of the string. Used for writing fields with wire type PB_WT_STRING. ::
145
146     bool pb_encode_string(pb_ostream_t *stream, const uint8_t *buffer, size_t size);
147
148 :stream:        Output stream to write to.
149 :buffer:        Pointer to string data.
150 :size:          Number of bytes in the string.
151 :returns:       True on success, false on IO error.
152
153 .. sidebar:: Field encoders
154
155     The functions with names beginning with *pb_enc_* are called field encoders. Each PB_LTYPE has an own field encoder, which handles translating from C data into Protocol Buffers data.
156
157     By using the *data_size* in the field description and by taking advantage of C casting rules, it has been possible to combine many data types to a single LTYPE. For example, *int32*, *uint32*, *int64*, *uint64*, *bool* and *enum* are all handled by *pb_enc_varint*.
158
159     Each field encoder only encodes the contents of the field. The tag must be encoded separately with `pb_encode_tag_for_field`_.
160
161     You can use the field encoders from your callbacks.
162
163 pb_enc_varint
164 -------------
165 Field encoder for PB_LTYPE_VARINT. Takes the first *field->data_size* bytes from src, casts them as *uint64_t* and calls `pb_encode_varint`_. ::
166
167     bool pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
168
169 :stream:        Output stream to write to.
170 :field:         Field description structure. Only *data_size* matters.
171 :src:           Pointer to start of the field data.
172 :returns:       True on success, false on IO error.
173
174 pb_enc_svarint
175 --------------
176 Field encoder for PB_LTYPE_SVARINT. Similar to `pb_enc_varint`_, except first zig-zag encodes the value for more efficient negative number encoding. ::
177
178     bool pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
179
180 (parameters are the same as for `pb_enc_varint`_)
181
182 The number is considered negative if the high-order bit of the value is set. On big endian computers, it is the highest bit of *\*src*. On little endian computers, it is the highest bit of *\*(src + field->data_size - 1)*.
183
184 pb_enc_fixed
185 ------------
186 Field encoder for PB_LTYPE_FIXED. Writes the data in little endian order. On big endian computers, reverses the order of bytes. ::
187
188     bool pb_enc_fixed(pb_ostream_t *stream, const pb_field_t *field, const void *src);
189
190 (parameters are the same as for `pb_enc_varint`_)
191
192 The same function is used for both integers, floats and doubles. This break encoding of double values on architectures where they are mixed endian (primarily some arm processors with hardware FPU).
193
194 pb_enc_bytes
195 ------------
196 Field encoder for PB_LTYPE_BYTES. Just calls `pb_encode_string`_. ::
197
198     bool pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src);
199
200 :stream:        Output stream to write to.
201 :field:         Not used.
202 :src:           Pointer to a structure similar to pb_bytes_array_t.
203 :returns:       True on success, false on IO error.
204
205 This function expects a pointer to a structure with a *size_t* field at start, and a variable sized byte array after it. The platform-specific field offset is inferred from *pb_bytes_array_t*, which has a byte array of size 1.
206
207 pb_enc_string
208 -------------
209 Field encoder for PB_LTYPE_STRING. Determines size of string with strlen() and then calls `pb_encode_string`_. ::
210
211     bool pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src);
212
213 :stream:        Output stream to write to.
214 :field:         Not used.
215 :src:           Pointer to a null-terminated string.
216 :returns:       True on success, false on IO error.
217
218 pb_enc_submessage
219 -----------------
220 Field encoder for PB_LTYPE_SUBMESSAGE. Calls `pb_encode`_ to perform the actual encoding. ::
221
222     bool pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src);
223
224 :stream:        Output stream to write to.
225 :field:         Field description structure. The *ptr* field must be a pointer to a field description array for the submessage.
226 :src:           Pointer to the structure where submessage data is.
227 :returns:       True on success, false on IO errors, pb_encode errors or if submessage size changes between calls.
228
229 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.
230
231 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 it is up to the caller to ensure that the receiver of the message does not interpret it as valid data.
232
233 pb_decode.h
234 ===========
235
236 pb_istream_from_buffer
237 ----------------------
238 Helper function for creating an input stream that reads data from a memory buffer. ::
239
240     pb_istream_t pb_istream_from_buffer(uint8_t *buf, size_t bufsize);
241
242 :buf:           Pointer to byte array to read from.
243 :bufsize:       Size of the byte array.
244 :returns:       An input stream ready to use.
245
246 pb_read
247 -------
248 Read data from input stream. Always use this function, don't try to call the stream callback directly. ::
249
250     bool pb_read(pb_istream_t *stream, uint8_t *buf, size_t count);
251
252 :stream:        Input stream to read from.
253 :buf:           Buffer to store the data to, or NULL to just read data without storing it anywhere.
254 :count:         Number of bytes to read.
255 :returns:       True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs.
256
257 End of file is signalled by *stream->bytes_left* being zero after pb_read returns false.
258
259 pb_decode_varint
260 ----------------
261 Read and decode a varint_ encoded integer. ::
262
263     bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);
264
265 :stream:        Input stream to read from. 1-10 bytes will be read.
266 :dest:          Storage for the decoded integer. Value is undefined on error.
267 :returns:       True on success, false if value exceeds uint64_t range or an IO error happens.
268
269 pb_skip_varint
270 --------------
271 Skip a varint_ encoded integer without decoding it. ::
272
273     bool pb_skip_varint(pb_istream_t *stream);
274
275 :stream:        Input stream to read from. Will read 1 byte at a time until the MSB is clear.
276 :returns:       True on success, false on IO error.
277
278 pb_skip_string
279 --------------
280 Skip a varint-length-prefixed string. This means skipping a value with wire type PB_WT_STRING. ::
281
282     bool pb_skip_string(pb_istream_t *stream);
283
284 :stream:        Input stream to read from.
285 :returns:       True on success, false on IO error or length exceeding uint32_t.
286
287 pb_decode
288 ---------
289 Read and decode all fields of a structure. Reads until EOF on input stream. ::
290
291     bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);
292
293 :stream:        Input stream to read from.
294 :fields:        A field description array. Usually autogenerated.
295 :dest_struct:   Pointer to structure where data will be stored.
296 :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.
297
298 In Protocol Buffers binary format, EOF is only allowed between fields. If it happens anywhere else, pb_decode will return *false*.
299
300 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.
301
302 For optional fields, this function applies the default value and sets *has_<field>* to false if the field is not present.
303
304 Because of memory concerns, the detection of missing required fields is not perfect if the structure contains more than 32 fields.
305
306 .. sidebar:: Field decoders
307     
308     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.
309
310     Each field decoder reads and decodes a single value. For arrays, the decoder is called repeatedly.
311
312     You can use the decoders from your callbacks.
313
314 pb_dec_varint
315 -------------
316 Field decoder for PB_LTYPE_VARINT. ::
317
318     bool pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
319
320 :stream:        Input stream to read from. 1-10 bytes will be read.
321 :field:         Field description structure. Only *field->data_size* matters.
322 :dest:          Pointer to destination integer. Must have size of *field->data_size* bytes.
323 :returns:       True on success, false on IO errors or if `pb_decode_varint`_ fails.
324
325 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.
326
327 pb_dec_svarint
328 --------------
329 Field decoder for PB_LTYPE_SVARINT. Similar to `pb_dec_varint`_, except that it performs zigzag-decoding on the value. ::
330
331     bool pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
332
333 (parameters are the same as `pb_dec_varint`_)
334
335 pb_dec_fixed
336 ------------
337 Field decoder for PB_LTYPE_FIXED. ::
338
339     bool pb_dec_fixed(pb_istream_t *stream, const pb_field_t *field, void *dest);
340
341 (parameters are the same as `pb_dec_varint`_)
342
343 This function reads *field->data_size* bytes from the input stream.
344 On big endian architectures, it then reverses the order of the bytes.
345 Finally, it writes the bytes to *dest*.
346
347 pb_dec_bytes
348 ------------
349 Field decoder for PB_LTYPE_BYTES. Reads a length-prefixed block of bytes. ::
350
351     bool pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
352
353 :stream:        Input stream to read from.
354 :field:         Field description structure. Only *field->data_size* matters.
355 :dest:          Pointer to a structure similar to pb_bytes_array_t.
356 :returns:       True on success, false on IO error or if length exceeds the array size.
357
358 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*.
359
360 pb_dec_string
361 -------------
362 Field decoder for PB_LTYPE_STRING. Reads a length-prefixed string. ::
363
364     bool pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
365
366 :stream:        Input stream to read from.
367 :field:         Field description structure. Only *field->data_size* matters.
368 :dest:          Pointer to a character array of size *field->data_size*.
369 :returns:       True on success, false on IO error or if length exceeds the array size.
370
371 This function null-terminates the string when successful. On error, the contents of the destination array is undefined.
372
373 pb_dec_submessage
374 -----------------
375 Field decoder for PB_LTYPE_SUBMESSAGE. Calls `pb_decode`_ to perform the actual decoding. ::
376
377     bool pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
378
379 :stream:        Input stream to read from.
380 :field:         Field description structure. Only *field->ptr* matters.
381 :dest:          Pointer to the destination structure.
382 :returns:       True on success, false on IO error or if `pb_decode`_ fails.
383
384 The *field->ptr* should be a pointer to *pb_field_t* array describing the submessage.
385