mbed-drivers
CircularBuffer.h
1 /*
2  * Copyright (c) 2015-2016, ARM Limited, All Rights Reserved
3  * SPDX-License-Identifier: Apache-2.0
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may
6  * not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #ifndef MBED_CIRCULARBUFFER_H
18 #define MBED_CIRCULARBUFFER_H
19 
20 namespace mbed {
21 
24 template<typename T, uint32_t BufferSize, typename CounterType = uint32_t>
26 public:
27  CircularBuffer() : _head(0), _tail(0), _full(false) {
28  }
29 
30  ~CircularBuffer() {
31  }
32 
38  void push(const T& data) {
39  if (full()) {
40  _tail++;
41  _tail %= BufferSize;
42  }
43  _pool[_head++] = data;
44  _head %= BufferSize;
45  if (_head == _tail) {
46  _full = true;
47  }
48  }
49 
55  bool pop(T& data) {
56  if (!empty()) {
57  data = _pool[_tail++];
58  _tail %= BufferSize;
59  _full = false;
60  return true;
61  }
62  return false;
63  }
64 
69  bool empty() {
70  return (_head == _tail) && !_full;
71  }
72 
77  bool full() {
78  return _full;
79  }
80 
84  void reset() {
85  _head = 0;
86  _tail = 0;
87  _full = false;
88  }
89 
90 private:
91  T _pool[BufferSize];
92  CounterType _head;
93  CounterType _tail;
94  bool _full;
95 };
96 
97 }
98 
99 #endif
void push(const T &data)
Definition: CircularBuffer.h:38
Definition: CircularBuffer.h:25
bool empty()
Definition: CircularBuffer.h:69
bool full()
Definition: CircularBuffer.h:77
bool pop(T &data)
Definition: CircularBuffer.h:55
Definition: BusIn.cpp:19
void reset()
Definition: CircularBuffer.h:84