lilzz
lilzz

Reputation: 5413

How do you declare a circular buffer?

/**
 * ring_buffer_set - update the ring buffer with the given value
 * @lq_recv: pointer to the ring buffer
 * @lq_index: index to store the value at
 * @value: value to store in the ring buffer
 */
static void ring_buffer_set(uint8_t lq_recv[], uint8_t *lq_index,
                   uint8_t value)
{
    lq_recv[*lq_index] = value;
    *lq_index = (*lq_index + 1) % 64;
}

/**
 * ring_buffer_set - compute the average of all non-zero values stored
 * in the given ring buffer
 * @lq_recv: pointer to the ring buffer
 *
 * Returns computed average value.
 */
static uint8_t ring_buffer_avg(const uint8_t lq_recv[])
{
    const uint8_t *ptr;
    uint16_t count = 0, i = 0, sum = 0;

    ptr = lq_recv;

    while (i < 64) {
        if (*ptr != 0) {
            count++;
            sum += *ptr;
        }

        i++;
        ptr++;
    }

    if (count == 0)
        return 0;

    return (uint8_t)(sum / count);
}

1) lq_recv[] is circular buffer but it looks like a plain array?

2) What's the purpose of *lq_index = (*lq_index + 1) % 64?

Upvotes: 0

Views: 370

Answers (2)

sampathsris
sampathsris

Reputation: 22270

  1. Circular buffer is of course a plain array, but you reset the array indexers once it comes to the last element.
  2. Use of modulus operator (%) ensures that array index is reset to 0 once it comes to the last element.

Upvotes: 4

user149341
user149341

Reputation:

  1. A "circular buffer" is an array that's used in a particular way. It's not declared any differently from any other array.

  2. It's updating the index of the array that's read from and keeping it within the bounds of the array.

Upvotes: 5

Related Questions