Circular Buffer: add flush routine to empty buffer
[clinton/Smoothieware.git] / src / libs / USBDevice / USBSerial / CircBuffer.h
1 /* Copyright (c) 2010-2011 mbed.org, MIT License
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
4 * and associated documentation files (the "Software"), to deal in the Software without
5 * restriction, including without limitation the rights to use, copy, modify, merge, publish,
6 * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
7 * Software is furnished to do so, subject to the following conditions:
8 *
9 * The above copyright notice and this permission notice shall be included in all copies or
10 * substantial portions of the Software.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
13 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 */
18
19 #ifndef CIRCBUFFER_H
20 #define CIRCBUFFER_H
21
22 #include <stdlib.h>
23
24 template <class T>
25 class CircBuffer {
26 public:
27 CircBuffer(int length) {
28 write = 0;
29 read = 0;
30 size = length + 1;
31 buf = (T *)malloc(size * sizeof(T));
32 };
33
34 bool isFull() {
35 return ((write + 1) % size == read);
36 };
37
38 bool isEmpty() {
39 return (read == write);
40 };
41
42 void queue(T k) {
43 if (isFull()) {
44 read++;
45 read %= size;
46 }
47 buf[write++] = k;
48 write %= size;
49 }
50
51 uint16_t available() {
52 return (write >= read) ? write - read : (size - read) + write;
53 };
54 uint16_t free() {
55 return size - available();
56 };
57
58 void dump() {
59 iprintf("[RingBuffer Sz:%2d Rd:%2d Wr:%2d Av:%2d Fr:%2d]\n", size, read, write, available(), free());
60 }
61
62 bool dequeue(T * c) {
63 bool empty = isEmpty();
64 if (!empty) {
65 *c = buf[read++];
66 read %= size;
67 }
68 return(!empty);
69 };
70
71 void flush() {
72 read = write;
73 }
74
75 private:
76 volatile uint16_t write;
77 volatile uint16_t read;
78 uint16_t size;
79 T * buf;
80 };
81
82 #endif