1 /*
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 
22 namespace android::hardware::graphics::composer {
23 
24 template <class T, size_t SIZE>
25 class RingBuffer {
26     // RingBuffer(const RingBuffer&) = delete;
27     // void operator=(const RingBuffer&) = delete;
28 
29 public:
30     RingBuffer() = default;
31     ~RingBuffer() = default;
32 
capacity()33     constexpr size_t capacity() const { return SIZE; }
34 
size()35     size_t size() const { return mCount; }
36 
next()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& operator[](size_t index) {
46         return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
47     }
48 
49     const T& operator[](size_t index) const {
50         return mBuffer[(static_cast<size_t>(mHead + 1) + index) % mCount];
51     }
52 
clear()53     void clear() {
54         mCount = 0;
55         mHead = -1;
56     }
57 
58 private:
59     std::array<T, SIZE> mBuffer;
60     int mHead = -1;
61     size_t mCount = 0;
62 };
63 
64 } // namespace android::hardware::graphics::composer
65