The library provides an implementation of a ring buffer. It allows for thread-safe operation on the data in the buffer. The library enables copying data in and out, and some more optimal direct operations of portions of the ring buffer to avoid memory copying.
Initialization
The NRF_RINGBUF_DEF macro creates an instance of the ring buffer. The size of the ring buffer must be a power of 2. It must be first initialized before it can be used.
Access through copying
Data can be copied into the ring buffer using nrf_ringbuf_cpy_put . If another 'put' operation on the instance was interrupted, the attempt returns NRF_ERROR_BUSY . The nrf_ringbuf_cpy_put function returns the amount of data written to the buffer. It can be smaller than requested if there is no space available to copy all data.
Data can be copied out from the ring buffer using nrf_ringbuf_cpy_get . If another 'get' operation on the instance was interrupted, the attempt returns NRF_ERROR_BUSY . The nrf_ringbuf_cpy_get function returns the amount of data read from the buffer. It can be smaller than requested if there is less data available to copy.
Direct access to the memory
The ring buffer library allows for working directly on the memory within the buffer. A portion of the buffer can be allocated for use. Once used, it can be put back (the put amount can be smaller than the allocated one). A similar approach can be used for getting data from the buffer. You can get it and then free it. The amount of freed data can be smaller than the one that was got.
Putting data to the ring buffer consists of the following steps.
- Request allocation of N bytes ( nrf_ringbuf_alloc ) - get M (where M <= N) bytes and the pointer to the buffer. M is smaller or equal to N.
- Write P bytes to the buffer where P is smaller or equal to M.
- Indicate to the ring buffer that P bytes are valid ( nrf_ringbuf_put ).
Getting data from the ring buffer consists of the following steps:
- Attempt to get N bytes of data from the ring buffer ( nrf_ringbuf_get ) - get M (where M <= N) bytes and the pointer to the buffer.
- Process P bytes of data where P is smaller or equal to M.
- Indicate to the ring buffer that P bytes can be freed ( nrf_ringbuf_free ).
Access to the ring buffer can be exclusive. It means that an attempt to allocate another buffer between nrf_ringbuf_alloc and nrf_ringbuf_put or an attempt to get data from the ring buffer between nrf_ringbuf_get and nrf_ringbuf_free can be detected. However, it is also possible to allocate or get more data with disabled exclusion check.