FDD-book/examples/part-01/ch04-a-first-look-at-the-c-programming-language/final-practice/lab5-circular-buffer/cbuf.c
Edson Brandi 6e6dac94fe Add book companion files under examples/
Organize companion code and materials by book part:

  part-01/      Foundations
  part-02/      Kernel & driver fundamentals
  part-03/      Character & block devices
  part-04/      Networking & storage
  part-05/      Buses & advanced topics
  part-06/      Debugging & performance
  part-07/      Real-world drivers
  appendices/   Supplementary material
  README.md     Overview and build instructions
2026-04-25 16:51:00 +00:00

49 lines
959 B
C

#include "cbuf.h"
/* Prepare a buffer wrapper around caller-provided storage. */
int
cb_init(cbuf_t *cb, int *storage, size_t n)
{
if (!cb || !storage || n == 0)
return (22); /* EINVAL */
cb->cap = n;
cb->head = cb->tail = 0;
cb->data = storage;
return (CB_OK);
}
/* Empty when indices match. */
int
cb_is_empty(const cbuf_t *cb)
{
return (cb->head == cb->tail);
}
/* Full when advancing head would collide with tail. */
int
cb_is_full(const cbuf_t *cb)
{
return (((cb->head + 1) % cb->cap) == cb->tail);
}
/* Write the value, then advance head with wrap-around. */
int
cb_push(cbuf_t *cb, int v)
{
if (cb_is_full(cb))
return (CB_EFULL);
cb->data[cb->head] = v;
cb->head = (cb->head + 1) % cb->cap;
return (CB_OK);
}
/* Read the value, then advance tail with wrap-around. */
int
cb_pop(cbuf_t *cb, int *out)
{
if (cb_is_empty(cb))
return (CB_EEMPTY);
*out = cb->data[cb->tail];
cb->tail = (cb->tail + 1) % cb->cap;
return (CB_OK);
}