Previous - Up - Next

14.2   Usage

This section gives an overview of the most common operations in the dbuffer API.

To create a new dbuffer, call the new_dbuffer function. This will return a pointer to a dbuffer_t that is used in later API calls to manipulate the dbuffer.

To add data to the buffer, the most commonly used function is dbuffer_append. It will extend the size of the dbuffer by the given amount of bytes and return a pointer to the newly added bytes. This pointer can be used to move data into the buffer by using it as the destination address of memcpy call, or any other suitable way. The pointer returned by dbuffer_append, or the similar functions dbuffer_prepend and dbuffer_insert can only be used to write data to the newly added part of the dbuffer, since the memory allocated for the dbuffer may not be contiguous.

There are two ways to read data from the dbuffer, and to write data to it. The first is the simple way of using dbuffer_read, dbuffer_update and dbuffer_replace which will return a pointer to a memory block that contains the data that is to be read from or written to. However, sometimes the data in the dbuffer needs to be reshuffled or copied to produce a contiguous block of memory. To minimize the overhead, it is better to use the dbuffer_read_some, dbuffer_update_some and dbuffer_replace_some functions instead.

Another important aspect of the dbuffer API is that it is cheap to make a copy of a dbuffer. The dbuffer_clone function will return a new dbuffer that contains the same data as a given dbuffer, but the two dbuffers are completely independent, so any changes you make to one copy will not affect the other. The cloning is done using a copy-on-write mechanism internally, which means that it doesn't need to copy any data from the original dbuffer, but if one of the dbuffers is updated in a way that would affect the data in the other, a copy of at least parts of the data will be done behind the scenes. Some updates, such as appending to the dbuffer, is still without overhead.

Finally, when the dbuffer is no longer needed, the dbuffer_free function should be called.

See the API section for the full documentation of the dbuffer API.

Previous - Up - Next