Documenting and improving stream behaviour
authorPetteri Aimonen <jpa@npb.mail.kapsi.fi>
Thu, 11 Aug 2011 19:22:36 +0000 (19:22 +0000)
committerPetteri Aimonen <jpa@npb.mail.kapsi.fi>
Thu, 11 Aug 2011 19:22:36 +0000 (19:22 +0000)
git-svn-id: https://svn.kapsi.fi/jpa/nanopb@954 e3a754e5-d11d-0410-8d38-ebb782a927b9

docs/Makefile
docs/concepts.rst [new file with mode: 0644]
docs/encoding.rst [new file with mode: 0644]
docs/index.rst
docs/lsr.css
pb_decode.c
pb_encode.c
pb_encode.h
tests/test_decode1.c
tests/test_encode1.c

index e4cac27..80b61b6 100644 (file)
@@ -1,4 +1,4 @@
-all: index.html
+all: index.html encoding.html
 
 %.html: %.rst
        rst2html --stylesheet=lsr.css --link-stylesheet $< $@
\ No newline at end of file
diff --git a/docs/concepts.rst b/docs/concepts.rst
new file mode 100644 (file)
index 0000000..30daed0
--- /dev/null
@@ -0,0 +1,98 @@
+======================
+Nanopb: Basic concepts
+======================
+
+The things outlined here are common to both the encoder and the decoder part.
+
+Return values and error handling
+================================
+
+Most functions in nanopb return *bool*. *True* means success, *false* means failure.
+
+Because code size is of the essence, nanopb doesn't give any information about the cause of the error. However, there are few possible sources of errors:
+
+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.
+2) Invalid field description. These are usually stored as constants, so if it works under the debugger, it always does.
+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.
+4) Errors in your callback functions. You can use the state field in the callback structure.
+5) Exceeding the max_size or bytes_left of a stream.
+6) Exceeding the max_size of a string or array field
+7) Invalid protocol buffers binary message. It's not like you could recover from it anyway, so a simple failure should be enough.
+
+In my opinion, it is enough that 1) and 2) can be resolved using a debugger.
+
+However, you may be interested which of the remaining conditions caused the error. For 3) and 4), you can 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).
+
+Streams
+=======
+
+Nanopb uses streams for accessing the data in encoded format.
+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.
+
+There are a few generic rules for callback functions:
+
+#) Return false on IO errors. The encoding or decoding process will abort immediately.
+#) Use state to store your own data, such as a file descriptor.
+#) *bytes_written* and *bytes_left* are updated by *pb_write* and *pb_read*. Don't touch them.
+#) 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.
+
+Output streams
+--------------
+
+::
+
+ struct _pb_ostream_t
+ {
+    bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count);
+    void *state;
+    size_t max_size;
+    size_t bytes_written;
+ };
+
+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.
+
+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.
+
+Most commonly you want to initialize *bytes_written* to 0. It doesn't matter to the library, though.
+**Example 1:**
+
+This is the way to get the size of the message without storing it anywhere::
+
+ Person myperson = ...;
+ pb_ostream_t sizestream = {0};
+ pb_encode(&sizestream, Person_fields, &myperson);
+ printf("Encoded size is %d\n", sizestream.bytes_written);
+
+**Example 2:**
+
+Writing to stdout::
+
+ bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
+ {
+    FILE *file = (FILE*) stream->state;
+    return fwrite(buf, 1, count, file) == count;
+ }
+ pb_ostream_t stdoutstream = {&streamcallback, stdout, SIZE_MAX, 0};
+
+Input streams
+-------------
+For input streams, there are a few extra rules:
+#) If buf is NULL, read from stream but don't store the data. This is used to skip unknown input.
+#) 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.
+
+::
+
+ struct _pb_istream_t
+ {
+    bool (*callback)(pb_istream_t *stream, uint8_t *buf, size_t count);
+    void *state;
+    size_t bytes_left;
+ };
+
+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.
+
+**Example**
\ No newline at end of file
diff --git a/docs/encoding.rst b/docs/encoding.rst
new file mode 100644 (file)
index 0000000..e4e0cd7
--- /dev/null
@@ -0,0 +1,39 @@
+=========================
+Nanopb: Encoding messages
+=========================
+
+The basic way to encode messages is to:
+
+1) Write a callback function for whatever stream you want to write the message to.
+2) Fill a structure with your data.
+3) Call pb_encode with the stream, a pointer to *const pb_field_t* array and a pointer to your structure.
+
+A few extra steps are necessary if you need to know the size of the message beforehand, or if you have dynamically sized fields.
+
+Output streams
+==============
+
+This is the contents of *pb_ostream_t* structure::
+
+ typedef struct _pb_ostream_t pb_ostream_t;
+ struct _pb_ostream_t
+ {
+    bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count);
+    void *state;
+    size_t max_size;
+    size_t bytes_written;
+ };
+
+This, combined with the pb_write function, provides a light-weight abstraction
+for whatever destination you want to write data to.
+
+*callback* should be a pointer to your callback function. These are the rules for it:
+
+1) Return false on IO errors. This will cause encoding to abort.
+ * 
+ * 2) You can use state to store your own data (e.g. buffer pointer).
+ * 
+ * 3) pb_write will update bytes_written after your callback runs.
+ * 
+ * 4) Substreams will modify max_size and bytes_written. Don't use them to
+ * calculate any pointers.
\ No newline at end of file
index 93b06e8..5a5cc82 100644 (file)
@@ -89,4 +89,4 @@ Wishlist
 ========
 #) A specialized encoder for encoding to a memory buffer. Should serialize in reverse order to avoid having to determine submessage size beforehand.
 #) A cleaner rewrite of the source generator.
-#) Better performance for 16- and 8-bit platforms.
+#) Better performance for 16- and 8-bit platforms: use smaller datatypes where possible.
index 758b231..081bf06 100644 (file)
@@ -88,7 +88,7 @@ pre {
 
 h1.title {
   color: #003a6b;
-  font-size: 250%;
+  font-size: 180%;
   margin-bottom: 0em;
 }
 
@@ -105,19 +105,19 @@ h1, h2, h3, h4, h5, h6 {
 }
 
 h1 {
-  font-size: 160%;
+  font-size: 150%;
   margin-bottom: 0.5em;
   border-bottom: 2px solid #aaa;
 }
 
 h2 {
-  font-size: 140%;
+  font-size: 130%;
   margin-bottom: 0.5em;
   border-bottom: 1px solid #aaa;
 }
 
 h3 {
-  font-size: 130%;
+  font-size: 120%;
   margin-bottom: 0.5em;
 }
 
index df05331..e2888f2 100644 (file)
@@ -349,7 +349,7 @@ bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struc
         uint32_t temp;
         int tag, wire_type;
         if (!pb_decode_varint32(stream, &temp))
-            return false;
+            return stream->bytes_left == 0; /* Was it EOF? */
         
         tag = temp >> 3;
         wire_type = temp & 7;
index 63ca288..19a531c 100644 (file)
@@ -309,16 +309,17 @@ bool pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *sr
 
 bool pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src)
 {
-    pb_ostream_t sizestream = {0};
+    pb_ostream_t substream = {0};
     size_t size;
+    bool status;
     
     if (field->ptr == NULL)
         return false;
     
-    if (!pb_encode(&sizestream, (pb_field_t*)field->ptr, src))
+    if (!pb_encode(&substream, (pb_field_t*)field->ptr, src))
         return false;
     
-    size = sizestream.bytes_written;
+    size = substream.bytes_written;
     
     if (!pb_encode_varint(stream, size))
         return false;
@@ -326,6 +327,23 @@ bool pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void
     if (stream->callback == NULL)
         return pb_write(stream, NULL, size); /* Just sizing */
     
-    return pb_encode(stream, (pb_field_t*)field->ptr, src);
+    if (stream->bytes_written + size > stream->max_size)
+        return false;
+        
+    /* Use a substream to verify that a callback doesn't write more than
+     * what it did the first time. */
+    substream.callback = stream->callback;
+    substream.state = stream->state;
+    substream.max_size = size;
+    substream.bytes_written = 0;
+    
+    status = pb_encode(stream, (pb_field_t*)field->ptr, src);
+    
+    stream->bytes_written += substream.bytes_written;
+    
+    if (substream.bytes_written != size)
+        return false;
+    
+    return status;
 }
 
index 17ba5b9..b341602 100644 (file)
  * max_size is not checked.
  *
  * Rules for callback:
- * 1) Return false on IO errors. This will cause decoding to abort.
+ * 1) Return false on IO errors. This will cause encoding to abort.
  * 
  * 2) You can use state to store your own data (e.g. buffer pointer).
  * 
  * 3) pb_write will update bytes_written after your callback runs.
  * 
- * 4) Your callback will be always used with the same pb_ostream_t.
- * There are no substreams when encoding.
+ * 4) Substreams will modify max_size and bytes_written. Don't use them to
+ * calculate any pointers.
  */
 struct _pb_ostream_t
 {
index cc4688d..a2c7f42 100644 (file)
@@ -24,12 +24,28 @@ bool print_person(pb_istream_t *stream)
     return true;
 }
 
-int main()
+bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
 {
-    uint8_t buffer[512];
-    size_t size = fread(buffer, 1, 512, stdin);
+    FILE *file = (FILE*)stream->state;
+    bool status;
+    
+    if (buf == NULL)
+    {
+        while (count-- && fgetc(file) != EOF);
+        return count == 0;
+    }
+    
+    status = (fread(buf, 1, count, file) == count);
     
-    pb_istream_t stream = pb_istream_from_buffer(buffer, size);
+    if (feof(file))
+        stream->bytes_left = 0;
+    
+    return status;
+}
+
+int main()
+{
+    pb_istream_t stream = {&callback, stdin, SIZE_MAX};
     if (!print_person(&stream))
         printf("Parsing failed.\n");
     
index b4998f4..99be7cb 100644 (file)
@@ -5,9 +5,10 @@
 /* This test has only one source file anyway.. */
 #include "person.c"
 
-bool callback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
+bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
 {
-    return fwrite(buf, 1, count, stdout) == count;
+    FILE *file = (FILE*) stream->state;
+    return fwrite(buf, 1, count, file) == count;
 }
 
 int main()
@@ -15,7 +16,7 @@ int main()
     Person person = {"Test Person 99", 99, true, "test@person.com",
         1, {{"555-12345678", true, Person_PhoneType_MOBILE}}};
     
-    pb_ostream_t stream = {&callback, 0, SIZE_MAX, 0};
+    pb_ostream_t stream = {&streamcallback, stdout, SIZE_MAX, 0};
     
     pb_encode(&stream, Person_fields, &person);