blob: b3e893139cf898c7f1f73fc82d1cbec2120f9c9c [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
John Reck1bcacfd2017-11-03 10:12:19 -070026template <class T, size_t SIZE>
John Reckba6adf62015-02-19 14:36:50 -080027class 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
John Reck1bcacfd2017-11-03 10:12:19 -070045 T& front() { return (*this)[0]; }
John Reckba6adf62015-02-19 14:36:50 -080046
John Reck1bcacfd2017-11-03 10:12:19 -070047 T& back() { return (*this)[size() - 1]; }
John Reckba6adf62015-02-19 14:36:50 -080048
John Reck1bcacfd2017-11-03 10:12:19 -070049 T& operator[](size_t index) { return mBuffer[(mHead + index + 1) % mCount]; }
John Reckba6adf62015-02-19 14:36:50 -080050
John Reck1bcacfd2017-11-03 10:12:19 -070051 const T& operator[](size_t index) const { return mBuffer[(mHead + index + 1) % mCount]; }
Andres Moralesa21c1da2015-12-09 14:40:33 -080052
John Reckba6adf62015-02-19 14:36:50 -080053 void clear() {
54 mCount = 0;
55 mHead = -1;
56 }
57
58private:
59 T mBuffer[SIZE];
60 int mHead = -1;
61 size_t mCount = 0;
62};
63
John Reck1bcacfd2017-11-03 10:12:19 -070064}; // namespace uirenderer
65}; // namespace android
John Reckba6adf62015-02-19 14:36:50 -080066
67#endif /* RINGBUFFER_H_ */