XBee API mode library
Diff: RingBuffer.h
- Revision:
- 8:776b8dc51932
- Child:
- 9:850306f22153
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/RingBuffer.h Tue Jan 29 13:46:41 2013 +0000 @@ -0,0 +1,51 @@ +#ifndef RING_BUFFER_H +#define RING_BUFFER_H + +#include <stdio.h> +template <typename T, size_t SIZE> +class RingBuffer +{ +public: + RingBuffer() : head(0), tail(0) { + } + + int writable() { + return head < tail ? tail - head - 1 : tail - head + (sizeof(buf) / sizeof(T)) - 1; + } + + int readable() { + return tail <= head ? head - tail : head - tail + (sizeof(buf) / sizeof(T)) - 1; + } + + T putc(T c) { + if (!writable()) + return (T) -1; + + buf[head] = c; + head = (head + 1) % (sizeof(buf) / sizeof(T)); + + return c; + } + + int getc() { + if (readable()) { + T c = buf[tail]; + tail = (tail + 1) % (sizeof(buf) / sizeof(T)); + return c; + } + return -1; + } + + T operator=(T c) { + return putc(c); + } + + operator int() { + return (int) getc(); + } + + int head, tail; + T buf[SIZE]; +}; + +#endif \ No newline at end of file