first commit
[clinton/Smoothieware.git] / src / libs / RingBuffer.h
CommitLineData
4cff3ded
AW
1/*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6
7 With chucks taken from http://en.wikipedia.org/wiki/Circular_buffer, see licence there also
8*/
9
10#ifndef RINGBUFFER_H
11#define RINGBUFFER_H
12
13
14template<class kind, int length> class RingBuffer {
15 public:
16 RingBuffer();
17 int size();
18 int capacity();
19 void push_back(kind object);
20 void pop_front(kind &object);
21 void get( int index, kind &object);
22 kind* get_ref( int index);
23 void delete_first();
24
25 kind buffer[length];
26 int head;
27 int tail;
28};
29
30
31template<class kind, int length> RingBuffer<kind, length>::RingBuffer(){
32 this->head = this->tail = 0;
33}
34
35template<class kind, int length> int RingBuffer<kind, length>::capacity(){
36 return length-1;
37}
38
39template<class kind, int length> int RingBuffer<kind, length>::size(){
40return((this->head>this->tail)?length:0)+this->tail-head;
41}
42
43template<class kind, int length> void RingBuffer<kind, length>::push_back(kind object){
44 this->buffer[this->tail] = object;
45 this->tail = (tail+1)&(length-1);
46}
47
48template<class kind, int length> void RingBuffer<kind, length>::get(int index, kind &object){
49 int j= 0;
50 int k= this->head;
51 while (k != this->tail){
52 if (j == index) break;
53 j++;
54 k= (k + 1) & (length - 1);
55 }
56 if (k == this->tail){
57 //return NULL;
58 }
59 object = this->buffer[k];
60}
61
62
63template<class kind, int length> kind* RingBuffer<kind, length>::get_ref(int index){
64 int j= 0;
65 int k= this->head;
66 while (k != this->tail){
67 if (j == index) break;
68 j++;
69 k= (k + 1) & (length - 1);
70 }
71 if (k == this->tail){
72 return NULL;
73 }
74 return &(this->buffer[k]);
75}
76
77template<class kind, int length> void RingBuffer<kind, length>::pop_front(kind &object){
78 object = this->buffer[this->head];
79 this->head = (this->head+1)&(length-1);
80}
81
82template<class kind, int length> void RingBuffer<kind, length>::delete_first(){
83 kind dummy;
84 this->pop_front(dummy);
85}
86
87
88#endif