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]; } 46 back()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 clear()57 void clear() { 58 mCount = 0; 59 mHead = -1; 60 } 61 62 private: 63 std::array<T, SIZE> mBuffer; 64 int mHead = -1; 65 size_t mCount = 0; 66 }; 67 68 } // namespace android::utils 69