1/*
2 * Copyright (C) 2015 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#ifndef RINGBUFFER_H_
17#define RINGBUFFER_H_
18
19#include "utils/Macros.h"
20
21#include <stddef.h>
22
23namespace android {
24namespace uirenderer {
25
26template<class T, size_t SIZE>
27class RingBuffer {
28    PREVENT_COPY_AND_ASSIGN(RingBuffer);
29
30public:
31    RingBuffer() {}
32    ~RingBuffer() {}
33
34    constexpr size_t capacity() const { return SIZE; }
35    size_t size() const { return mCount; }
36
37    T& next() {
38        mHead = (mHead + 1) % SIZE;
39        if (mCount < SIZE) {
40            mCount++;
41        }
42        return mBuffer[mHead];
43    }
44
45    T& front() {
46        return (*this)[0];
47    }
48
49    T& back() {
50        return (*this)[size() - 1];
51    }
52
53    T& operator[](size_t index) {
54        return mBuffer[(mHead + index + 1) % mCount];
55    }
56
57    const T& operator[](size_t index) const {
58        return mBuffer[(mHead + index + 1) % mCount];
59    }
60
61    void clear() {
62        mCount = 0;
63        mHead = -1;
64    }
65
66private:
67    T mBuffer[SIZE];
68    int mHead = -1;
69    size_t mCount = 0;
70};
71
72}; // namespace uirenderer
73}; // namespace android
74
75#endif /* RINGBUFFER_H_ */
76