p kj
/
LPC824-BlynkWeatherstation
Microduino
Fork of Io_moon by
Diff: Blynk_v0_3_7/Blynk/utility/BlynkFifo.h
- Revision:
- 0:740c1eb2df13
diff -r 000000000000 -r 740c1eb2df13 Blynk_v0_3_7/Blynk/utility/BlynkFifo.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Blynk_v0_3_7/Blynk/utility/BlynkFifo.h Thu Jun 23 11:16:14 2016 +0000 @@ -0,0 +1,106 @@ +/** + * @file BlynkFifo.h + * @author Volodymyr Shymanskyy + * @license This project is released under the MIT License (MIT) + * @copyright Copyright (c) 2015 Volodymyr Shymanskyy + * @date Feb 2015 + * @brief FIFO implementation + * + */ + +#ifndef BlynkFifo_h +#define BlynkFifo_h + +#include <utility/BlynkUtility.h> + +template<typename T, unsigned SIZE> +class BlynkFifo { + + BlynkFifo(const BlynkFifo<T, SIZE> & rb); + +public: + + BlynkFifo() : fst(0), lst(0), flag(0) {} + ~BlynkFifo() {} + + void clear() { + fst = 0; + lst = 0; + flag = 0; + } + + size_t write(const T* data, size_t n) + { + if ((n = BlynkMin(n, getFree()))) { + const size_t ch1 = BlynkMin(n, SIZE - lst); + memcpy(buffer + lst, data, ch1 * sizeof(T)); + lst = (lst + ch1) % SIZE; + + if (ch1 < n) { + const size_t ch2 = n - ch1; + memcpy(buffer + lst, data + ch1, ch2 * sizeof(T)); + lst = (lst + ch2) % SIZE; + } + + if (fst == lst) { + flag = 1; + } + } + return n; + } + + size_t read(T* dest, size_t n) + { + if ((n = BlynkMin(n, getOccupied()))) { + flag = 0; + + const size_t ch1 = BlynkMin(n, SIZE - fst); + memcpy(dest, buffer + fst, ch1 * sizeof(T)); + fst = (fst + ch1) % SIZE; + + if (ch1 < n) { + const size_t ch2 = n - ch1; + memcpy(dest + ch1, buffer + fst, ch2 * sizeof(T)); + fst = (fst + ch2) % SIZE; + } + } + return n; + } + + void dump(void) + { + for (int i = fst; i < lst; i++) { + pc.printf("0x%02X ", buffer[i]); + if (i % 16 == 0) { + pc.printf("\r\n"); + } + } + } + + bool push(const T& data) { + return write(&data, 1) == 1; + } + + size_t getOccupied() const { + if (lst == fst) { + return flag ? SIZE : 0; + } else if (lst > fst) { + return lst - fst; + } else { + return SIZE + lst - fst; + } + } + + size_t getFree() const { + return SIZE - getOccupied(); + } + +private: + T buffer[SIZE]; + size_t fst; + size_t lst; + uint8_t flag; +}; + +#endif +