Circular DMA Buffer Index

Hard C Data Flow Asked at STMicroelectronics
Solve this problem

A peripheral DMA writes continuously into a circular buffer and only exposes its current write index. Compute how many new bytes are available since the last read, handling wrap correctly.

Constraints

  • Buffer length is a compile-time constant, not necessarily a power of two.
  • `size_t bytes_available(size_t write_index, size_t read_index)`.
  • Must handle write_index < read_index (wrapped case).
  • Must return 0 when the indices are equal.
  • No modulo operator in the hot path.
  • No 64-bit math.
Starter codeC
1#include <stddef.h>2 3#define DMA_BUF_LEN 3004 5size_t bytes_available(size_t write_index, size_t read_index) {6    // TODO7    return 0;8}