| 1 | #ifndef __MDFN_SIMPLEFIFO_H |
| 2 | #define __MDFN_SIMPLEFIFO_H |
| 3 | |
| 4 | #include <vector> |
| 5 | #include <assert.h> |
| 6 | |
| 7 | #include "../math_ops.h" |
| 8 | |
| 9 | template<typename T> |
| 10 | class SimpleFIFO |
| 11 | { |
| 12 | public: |
| 13 | |
| 14 | // Constructor |
| 15 | SimpleFIFO(uint32 the_size) // Size should be a power of 2! |
| 16 | { |
| 17 | data.resize(round_up_pow2(the_size)); |
| 18 | size = the_size; |
| 19 | read_pos = 0; |
| 20 | write_pos = 0; |
| 21 | in_count = 0; |
| 22 | } |
| 23 | |
| 24 | // Destructor |
| 25 | INLINE ~SimpleFIFO() |
| 26 | { |
| 27 | |
| 28 | } |
| 29 | |
| 30 | INLINE uint32 CanRead(void) |
| 31 | { |
| 32 | return(in_count); |
| 33 | } |
| 34 | |
| 35 | INLINE uint32 CanWrite(void) |
| 36 | { |
| 37 | return(size - in_count); |
| 38 | } |
| 39 | |
| 40 | INLINE T ReadUnit(bool peek = false) |
| 41 | { |
| 42 | T ret; |
| 43 | |
| 44 | assert(in_count > 0); |
| 45 | |
| 46 | ret = data[read_pos]; |
| 47 | |
| 48 | if(!peek) |
| 49 | { |
| 50 | read_pos = (read_pos + 1) & (data.size() - 1); |
| 51 | in_count--; |
| 52 | } |
| 53 | |
| 54 | return(ret); |
| 55 | } |
| 56 | |
| 57 | INLINE uint8 ReadByte(bool peek = false) |
| 58 | { |
| 59 | assert(sizeof(T) == 1); |
| 60 | |
| 61 | return(ReadUnit(peek)); |
| 62 | } |
| 63 | |
| 64 | INLINE void Write(const T *happy_data, uint32 happy_count) |
| 65 | { |
| 66 | assert(CanWrite() >= happy_count); |
| 67 | |
| 68 | while(happy_count) |
| 69 | { |
| 70 | data[write_pos] = *happy_data; |
| 71 | |
| 72 | write_pos = (write_pos + 1) & (data.size() - 1); |
| 73 | in_count++; |
| 74 | happy_data++; |
| 75 | happy_count--; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | INLINE void WriteUnit(const T& wr_data) |
| 80 | { |
| 81 | Write(&wr_data, 1); |
| 82 | } |
| 83 | |
| 84 | INLINE void WriteByte(const T& wr_data) |
| 85 | { |
| 86 | assert(sizeof(T) == 1); |
| 87 | Write(&wr_data, 1); |
| 88 | } |
| 89 | |
| 90 | |
| 91 | INLINE void Flush(void) |
| 92 | { |
| 93 | read_pos = 0; |
| 94 | write_pos = 0; |
| 95 | in_count = 0; |
| 96 | } |
| 97 | |
| 98 | //private: |
| 99 | std::vector<T> data; |
| 100 | uint32 size; |
| 101 | uint32 read_pos; // Read position |
| 102 | uint32 write_pos; // Write position |
| 103 | uint32 in_count; // Number of units in the FIFO |
| 104 | }; |
| 105 | |
| 106 | |
| 107 | #endif |