Skip to content

Instantly share code, notes, and snippets.

@martin31821
Created September 11, 2016 20:06
Show Gist options
  • Save martin31821/abba8763d03e70c0e4b8b770368fd379 to your computer and use it in GitHub Desktop.
Save martin31821/abba8763d03e70c0e4b8b770368fd379 to your computer and use it in GitHub Desktop.
C++ templated FiFo
#pragma once
#include <stdint.h>
/**
* Simple templated c++ FIFO implementation.
*
* Inspired by: https://www.mikrocontroller.net/articles/FIFO#FIFO_mit_C-Pr.C3.A4prozessor
*
* @typeparam TData The data type of the fifo.
* @typeparam len The length of the fifo.
*/
template<typename TData, uint16_t len>
class Fifo
{
private:
/**
* The buffer, allocated in the object.
*/
TData _buffer[len];
/**
* The read pointer.
*/
uint16_t _read;
/**
* The write pointer.
*/
uint16_t _write;
public:
/**
* Creates a new instance of the fifo. It is empty.
*/
Fifo () : _read(0), _write(0)
{};
/**
* Gets a value indicating whether an item is inside the fifo.
* @returns true if item inside the fifo, false otherwise.
*/
bool Available () const
{
return _read != _write;
};
/**
* Reads an item from the fifo.
* @returns Item or default value of TData if no item is available
*/
TData read ()
{
if (!Available ())
{
return TData ();
}
return _buffer[_read = (_read + 1) % len];
};
/**
* Writes an item into the fifo.
* @param data The data to write into the fifo.
*/
void write (const TData& data)
{
uint16_t tmphead = (_write + 1) % len;
if (tmphead != _read)
{
_buffer[tmphead] = data;
_write = tmphead;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment