Simvik

Fill level from two indices

Compute how many items a FIFO holds from its head and tail. An easy embedded C problem (Buffers and data structures), run and graded in the browser.

easy · Buffers and data structures · fifo · modular-arithmetic

A lock-free FIFO stores no count. Its fill level is derived from the write index head and the read index tail, both in the range 0 to size - 1.

Return the number of items stored. head == tail means empty. size is not necessarily a power of two.

Starter code

size_t fifo_used(size_t head, size_t tail, size_t size) {
  // Items stored between tail (read position) and head (write position).
  return head - tail;
}

Example tests

Head ahead of tail

printf("%u\n", (unsigned)fifo_used(5, 2, 8));

Expected output:

3

Head has wrapped

printf("%u\n", (unsigned)fifo_used(1, 6, 8));

Expected output:

3

Learn it first

More Buffers and data structures problems