blob: 215472b388b9af29b3c730b747ae5ec5378300ac [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]; }
Ady Abrahamed1283a2024-07-24 15:49:16 -070046 const T& front() const { return (*this)[0]; }
John Reck2a3d29d2023-08-17 17:45:01 -040047
48 T& back() { return (*this)[size() - 1]; }
Ady Abrahamed1283a2024-07-24 15:49:16 -070049 const T& back() const { return (*this)[size() - 1]; }
John Reck2a3d29d2023-08-17 17:45:01 -040050
51 T& operator[](size_t index) {
52 return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
53 }
54
55 const T& operator[](size_t index) const {
56 return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
57 }
58
59 void clear() {
60 mCount = 0;
61 mHead = -1;
62 }
63
64private:
65 std::array<T, SIZE> mBuffer;
66 int mHead = -1;
67 size_t mCount = 0;
68};
69
70} // namespace android::utils