blob: 06bcdcd7d84b4a0aa5382a1d680aa35c138a98a4 [file] [log] [blame]
John Reckba6adf62015-02-19 14:36:50 -08001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef RINGBUFFER_H_
17#define RINGBUFFER_H_
18
19#include "utils/Macros.h"
20
21#include <stddef.h>
22
23namespace android {
24namespace uirenderer {
25
26template<class T, size_t SIZE>
27class RingBuffer {
28 PREVENT_COPY_AND_ASSIGN(RingBuffer);
29
30public:
31 RingBuffer() {}
32 ~RingBuffer() {}
33
Chih-Hung Hsieh2f1e21d2015-05-19 10:44:53 -070034 constexpr size_t capacity() const { return SIZE; }
Andres Moralesa21c1da2015-12-09 14:40:33 -080035 size_t size() const { return mCount; }
John Reckba6adf62015-02-19 14:36:50 -080036
37 T& next() {
38 mHead = (mHead + 1) % SIZE;
39 if (mCount < SIZE) {
40 mCount++;
41 }
42 return mBuffer[mHead];
43 }
44
45 T& front() {
John Reck41300272015-06-03 14:42:34 -070046 return (*this)[0];
John Reckba6adf62015-02-19 14:36:50 -080047 }
48
49 T& back() {
John Reck41300272015-06-03 14:42:34 -070050 return (*this)[size() - 1];
John Reckba6adf62015-02-19 14:36:50 -080051 }
52
53 T& operator[](size_t index) {
54 return mBuffer[(mHead + index + 1) % mCount];
55 }
56
Andres Moralesa21c1da2015-12-09 14:40:33 -080057 const T& operator[](size_t index) const {
58 return mBuffer[(mHead + index + 1) % mCount];
59 }
60
John Reckba6adf62015-02-19 14:36:50 -080061 void clear() {
62 mCount = 0;
63 mHead = -1;
64 }
65
66private:
67 T mBuffer[SIZE];
68 int mHead = -1;
69 size_t mCount = 0;
70};
71
72}; // namespace uirenderer
73}; // namespace android
74
75#endif /* RINGBUFFER_H_ */