Tips & tricks

Application buffer size

Buffer size shall always be 1 byte bigger than anticipated data size.

When application uses buffer for some data block N times, it is advised to set buffer size to 1 byte more than N * block_size is. This is due to R and W pointers alignment.

Note

For more information, check How it works.

Application buffer size assignment
 1#include "lwrb/lwrb.h"
 2
 3/* Number of data blocks to write */
 4#define N          3
 5
 6/* Create custom data structure */
 7/* Data is array of 2 32-bit words, 8-bytes */
 8uint32_t d[2];
 9
10/* Create buffer structures */
11lwrb_t buff_1;
12lwrb_t buff_2;
13
14/* Create data for buffers. Use sizeof structure,
15   multiplied by N (for N instances) */
16/* Buffer with + 1 bytes bigger memory */
17uint8_t buff_data_1[sizeof(d) * N + 1];
18/* Buffer without + 1 at the end */
19uint8_t buff_data_2[sizeof(d) * N];
20
21/* Write result values */
22size_t len_1;
23size_t len_2;
24
25/* Initialize buffers */
26lwrb_init(&buff_1, buff_data_1, sizeof(buff_data_1));
27lwrb_init(&buff_2, buff_data_2, sizeof(buff_data_2));
28
29/* Write data to buffer */
30for (size_t i = 0; i < N; ++i) {
31    /* Prepare data */
32    d.a = i;
33    d.b = i * 2;
34
35    /* Write data to both buffers, memory copy from d to buffer */
36    len_1 = lwrb_write(&buff_1, d, sizeof(d));
37    len_2 = lwrb_write(&buff_2, d, sizeof(d));
38
39    /* Print results */
40    printf("Write buffer 1: %d/%d bytes; buffer 2: %d/%d\r\n",
41        (int)len_1, (int)sizeof(d),
42        (int)len_2, (int)sizeof(d));
43}

When the code is executed, it produces following output:

Application buffer size assignment output
Write: buffer 1: 8/8; buffer 2: 8/8
Write: buffer 1: 8/8; buffer 2: 8/8
Write: buffer 1: 8/8; buffer 2: 7/8 <-- See here -->