5 The things outlined here are common to both the encoder and the decoder part.
14 Nanopb uses streams for accessing the data in encoded format.
15 The stream abstraction is very lightweight, and consists of a structure (*pb_ostream_t* or *pb_istream_t*) which contains a pointer to a callback function.
17 There are a few generic rules for callback functions:
19 #) Return false on IO errors. The encoding or decoding process will abort immediately.
20 #) Use state to store your own data, such as a file descriptor.
21 #) *bytes_written* and *bytes_left* are updated by pb_write and pb_read.
22 #) Your callback may be used with substreams. In this case *bytes_left*, *bytes_written* and *max_size* have smaller values than the original stream. Don't use these values to calculate pointers.
31 bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count);
37 The *callback* for output stream may be NULL, in which case the stream simply counts the number of bytes written. In this case, *max_size* is ignored.
39 Otherwise, if *bytes_written* + bytes_to_be_written is larger than *max_size*, pb_write returns false before doing anything else. If you don't want to limit the size of the stream, pass SIZE_MAX.
43 This is the way to get the size of the message without storing it anywhere::
45 Person myperson = ...;
46 pb_ostream_t sizestream = {0};
47 pb_encode(&sizestream, Person_fields, &myperson);
48 printf("Encoded size is %d\n", sizestream.bytes_written);
54 bool callback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
56 FILE *file = (FILE*) stream->state;
57 return fwrite(buf, 1, count, file) == count;
60 pb_ostream_t stdoutstream = {&callback, stdout, SIZE_MAX, 0};
64 For input streams, there are a few extra rules:
66 #) If buf is NULL, read from stream but don't store the data. This is used to skip unknown input.
67 #) You don't need to know the length of the message in advance. After getting EOF error when reading, set bytes_left to 0 and return false. Pb_decode will detect this and if the EOF was in a proper position, it will return true.
69 Here is the structure::
73 bool (*callback)(pb_istream_t *stream, uint8_t *buf, size_t count);
78 The *callback* must always be a function pointer. *Bytes_left* is an upper limit on the number of bytes that will be read. You can use SIZE_MAX if your callback handles EOF as described above.
82 This function binds an input stream to stdin:
86 bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
88 FILE *file = (FILE*)stream->state;
93 while (count-- && fgetc(file) != EOF);
97 status = (fread(buf, 1, count, file) == count);
100 stream->bytes_left = 0;
105 pb_istream_t stdinstream = {&callback, stdin, SIZE_MAX};
110 Most Protocol Buffers datatypes have directly corresponding C datatypes, such as int32 is int32_t, float is float and bool is bool. However, the variable-length datatypes are more complex:
112 1) Strings, bytes and repeated fields of any type map to callback functions by default.
113 2) If there is a special option *(nanopb).max_size* specified in the .proto file, string maps to null-terminated char array and bytes map to a structure containing a char array and a size field.
114 3) If there is a special option *(nanopb).max_count* specified on a repeated field, it maps to an array of whatever type is being repeated. Another field will be created for the actual number of entries stored.
116 =============================================================================== =======================
117 field in .proto autogenerated in .h
118 =============================================================================== =======================
119 required string name = 1; pb_callback_t name;
120 required string name = 1 [(nanopb).max_size = 40]; char name[40];
121 repeated string name = 1 [(nanopb).max_size = 40]; pb_callback_t name;
122 repeated string name = 1 [(nanopb).max_size = 40, (nanopb).max_count = 5]; | size_t name_count;
124 required bytes data = 1 [(nanopb).max_size = 40]; | typedef struct {
128 | Person_data_t data;
129 =============================================================================== =======================
131 The maximum lengths are checked in runtime. If string/bytes/array exceeds the allocated length, *pb_decode* will return false.
133 For more information about callbacks, see the `Encoding` and `Decoding` sections.
135 Field description array
136 =======================
138 For using the *pb_encode* and *pb_decode* functions, you need an array of pb_field_t constants describing the structure you wish to encode. This description is usually autogenerated from .proto file.
142 message PhoneNumber {
143 required string number = 1 [(nanopb).max_size = 40];
144 optional PhoneType type = 2 [default = HOME];
149 const pb_field_t Person_PhoneNumber_fields[3] = {
150 {1, PB_HTYPE_REQUIRED | PB_LTYPE_STRING,
151 offsetof(Person_PhoneNumber, number), 0,
152 pb_membersize(Person_PhoneNumber, number), 0, 0},
154 {2, PB_HTYPE_OPTIONAL | PB_LTYPE_VARINT,
155 pb_delta(Person_PhoneNumber, type, number),
156 pb_delta(Person_PhoneNumber, has_type, type),
157 pb_membersize(Person_PhoneNumber, type), 0,
158 &Person_PhoneNumber_type_default},
163 For more information about the format, see the `Generated code` section.
166 Return values and error handling
167 ================================
169 Most functions in nanopb return bool: *true* means success, *false* means failure. If this is enough for you, skip this section.
171 For simplicity, nanopb doesn't define it's own error codes. This might be added if there is a compelling need for it. You can however deduce something about the error causes:
173 1) Running out of memory. Because everything is allocated from the stack, nanopb can't detect this itself. Encoding or decoding the same type of a message always takes the same amount of stack space. Therefore, if it works once, it works always.
174 2) Invalid field description. These are usually stored as constants, so if it works under the debugger, it always does.
175 3) IO errors in your own stream callbacks. Because encoding/decoding stops at the first error, you can overwrite the *state* field in the struct and store your own error code there.
176 4) Errors that happen in your callback functions. You can use the state field in the callback structure.
177 5) Exceeding the max_size or bytes_left of a stream.
178 6) Exceeding the max_size of a string or array field
179 7) Invalid protocol buffers binary message. It's not like you could recover from it anyway, so a simple failure should be enough.
181 In my opinion, it is enough that 1. and 2. can be resolved using a debugger.
183 However, you may be interested which of the remaining conditions caused the error. For 3. and 4., you can set and check the state. If you have to detect 5. and 6., you should convert the fields to callback type. Any remaining problem is of type 7.