UsefulOutBuf is a structure and functions (an object) that are good for serializing data into a buffer such as is often done with network protocols or data written to files. More...
#include <UsefulBuf.h>
UsefulOutBuf is a structure and functions (an object) that are good for serializing data into a buffer such as is often done with network protocols or data written to files.
The main idea is that all the pointer manipulation for adding data is done by UsefulOutBuf functions so the caller doesn't have to do any. All the pointer manipulation is centralized here. This code will have been reviewed and written carefully so it spares the caller of much of this work and results in much safer code with much less work.
The functions to add data to the output buffer always check the length and will never write off the end of the output buffer. If an attempt to add data that will not fit is made, an internal error flag will be set and further attempts to add data will not do anything.
Basically, if you initialized with the correct buffer, there is no way to ever write off the end of that buffer when calling the Add and Insert functions here.
The functions to add data do not return an error. The working model is that the caller just makes all the calls to add data without any error checking on each one. The error is instead checked after all the data is added when the result is to be used. This makes the caller's code cleaner.
There is a utility function to get the error status anytime along the way if the caller wants. There are functions to see how much room is left and see if some data will fit too, but their use is generally not necessary.
The general call flow is like this:
UsefulOutBuf can be initialized with just a buffer length by passing NULL as the pointer to the output buffer. This is useful if you want to go through the whole serialization process to either see if it will fit into a given buffer or compute the size of the buffer needed. Pass a very large buffer size when calling Init, if you want just to compute the size.
Some inexpensive simple sanity checks are performed before every data addition to guard against use of an uninitialized or corrupted UsefulOutBuf.
This has been used to create a CBOR encoder. The CBOR encoder has almost no pointer manipulation in it, is much easier to read, and easier to review.
A UsefulOutBuf is 27 bytes or 15 bytes on 64- or 32-bit machines so it can go on the stack or be a C99 function parameter.
Definition at line 642 of file UsefulBuf.h.