74e2ced37446861e0907b67c532a53c71e4a7acd
[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 #include "sLPC17xx.h"
24 #include "platform_memory.h"
25
26 template <class T>
27 class CircBuffer {
28 public:
29 CircBuffer(int length) {
30 write = 0;
31 read = 0;
32 size = length;
33 buf = (uint8_t*) AHB0.alloc(size * sizeof(T));
34 };
35
36 bool isFull() {
37 return ((write + 1) % size == read);
38 };
39
40 bool isEmpty() {
41 return (read == write);
42 };
43
44 void queue(T k) {
45 __disable_irq();
46 if (isFull()) {
47 read++;
48 read %= size;
49 }
50 buf[write++] = k;
51 write %= size;
52 __enable_irq();
53 }
54
55 uint16_t available() {
56 __disable_irq();
57 uint16_t i= (write >= read) ? write - read : (size - read) + write;
58 __enable_irq();
59 return i;
60 };
61 uint16_t free() {
62 return size - available() - 1;
63 };
64
65 void dump() {
66 iprintf("[RingBuffer Sz:%2d Rd:%2d Wr:%2d Av:%2d Fr:%2d]\n", size, read, write, available(), free());
67 }
68
69 bool dequeue(T * c) {
70 bool empty = isEmpty();
71 if (!empty) {
72 *c = buf[read++];
73 read %= size;
74 }
75 return(!empty);
76 };
77
78 void peek(T * c, int offset) {
79 int h = (read + offset) % size;
80 *c = buf[h];
81 };
82
83 void flush() {
84 read = write;
85 }
86
87 private:
88 volatile uint16_t write;
89 volatile uint16_t read;
90 uint16_t size;
91 T * buf;
92 };
93
94 #endif