Simvik

An opaque FIFO module: fifo.h and fifo.c

Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions. A medium embedded C problem (Buffers and data…

medium · Buffers and data structures · buffers · headers · encapsulation

fifo.h below is the interface of a byte FIFO module that two drivers share, one FIFO each. It declares fifo_t without saying what is inside: the type is opaque, so the rest of the firmware can only hold a fifo_t * and call the functions. Write fifo.c:

  • struct fifo itself: FIFO_CAPACITY bytes, and whatever you need to track them.
  • fifo_create() hands out a FIFO from a pool of FIFO_INSTANCES, defined in fifo.c (there is no heap), and returns NULL once they are all taken.
  • fifo_put adds a byte and returns false if the FIFO is full; fifo_get takes the oldest byte and returns false if it is empty; fifo_count says how many bytes it holds.

The tests include fifo.h only, so they cannot see inside a fifo_t, and neither should anything else.

Starter code

// ===== fifo.h =====
// fifo.h: a byte FIFO whose layout is private to fifo.c.
#ifndef FIFO_H
#define FIFO_H

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#define FIFO_CAPACITY 8u
#define FIFO_INSTANCES 2u

typedef struct fifo fifo_t;   // defined in fifo.c: callers only hold pointers

fifo_t *fifo_create(void);
bool fifo_put(fifo_t *f, uint8_t byte);
bool fifo_get(fifo_t *f, uint8_t *byte);
size_t fifo_count(const fifo_t *f);

#endif

// ===== fifo.c =====
#include "fifo.h"

// struct fifo, the pool of FIFO_INSTANCES and the four functions.

Example tests

First in, first out

fifo_t *f = fifo_create();
fifo_put(f, 1);
fifo_put(f, 2);
fifo_put(f, 3);
uint8_t b;
while (fifo_get(f, &b)) printf("%u ", b);
printf("count %u\n", (unsigned)fifo_count(f));

Expected output:

1 2 3 count 0

Learn it first

More Buffers and data structures problems