blob: 198e7b2cf1917c2560373f1c5f5e350c2d818537 [file] [log] [blame]
John Reck2a3d29d2023-08-17 17:45:01 -04001/*
2 * Copyright 2023 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
17#pragma once
18
19#include <stddef.h>
20#include <array>
21
22namespace android::utils {
23
24template <class T, size_t SIZE>
25class RingBuffer {
26 RingBuffer(const RingBuffer&) = delete;
27 void operator=(const RingBuffer&) = delete;
28
29public:
30 RingBuffer() = default;
31 ~RingBuffer() = default;
32
33 constexpr size_t capacity() const { return SIZE; }
34
35 size_t size() const { return mCount; }
36
37 T& next() {
38 mHead = static_cast<size_t>(mHead + 1) % SIZE;
39 if (mCount < SIZE) {
40 mCount++;
41 }
42 return mBuffer[static_cast<size_t>(mHead)];
43 }
44
45 T& front() { return (*this)[0]; }
46
47 T& back() { return (*this)[size() - 1]; }
48
49 T& operator[](size_t index) {
50 return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
51 }
52
53 const T& operator[](size_t index) const {
54 return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
55 }
56
57 void clear() {
58 mCount = 0;
59 mHead = -1;
60 }
61
62private:
63 std::array<T, SIZE> mBuffer;
64 int mHead = -1;
65 size_t mCount = 0;
66};
67
68} // namespace android::utils