xref: /aosp_15_r20/frameworks/native/services/surfaceflinger/Utils/RingBuffer.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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::utils {
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 
front()45     T& front() { return (*this)[0]; }
front()46     const T& front() const { return (*this)[0]; }
47 
back()48     T& back() { return (*this)[size() - 1]; }
back()49     const T& back() const { return (*this)[size() - 1]; }
50 
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 
clear()59     void clear() {
60         mCount = 0;
61         mHead = -1;
62     }
63 
64 private:
65     std::array<T, SIZE> mBuffer;
66     int mHead = -1;
67     size_t mCount = 0;
68 };
69 
70 } // namespace android::utils
71