sndlock/fifo.h

31 lines
720 B
C++

#pragma once
#include <optional>
template<typename T, size_t N>
class FIFO {
private:
size_t produce = 0;
size_t consume = 0;
bool empty = true;
T storage[N];
public:
bool push(T x) {
if(produce == consume && !empty)
return false;
storage[produce] = x;
produce = (produce + 1) % N;
empty = false;
return true;
}
std::optional<T> pull() {
if(empty)
return std::nullopt;
T ret = storage[consume];
consume = (consume + 1) % N;
if(produce == consume)
empty = true;
return ret;
}
};