rago | ff0a51f | 2018-03-22 09:55:50 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 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 | #ifndef SHCIRCULARBUFFER_H |
| 18 | #define SHCIRCULARBUFFER_H |
| 19 | |
| 20 | #include <log/log.h> |
| 21 | #include <vector> |
| 22 | |
| 23 | template <class T> |
| 24 | class SHCircularBuffer { |
| 25 | |
| 26 | public: |
| 27 | SHCircularBuffer() : mReadIndex(0), mWriteIndex(0), mReadAvailable(0) { |
| 28 | } |
| 29 | |
| 30 | explicit SHCircularBuffer(size_t maxSize) { |
| 31 | resize(maxSize); |
| 32 | } |
| 33 | void resize(size_t maxSize) { |
| 34 | mBuffer.resize(maxSize); |
| 35 | mReadIndex = 0; |
| 36 | mWriteIndex = 0; |
| 37 | mReadAvailable = 0; |
| 38 | } |
| 39 | inline void write(T value) { |
| 40 | if (availableToWrite()) { |
| 41 | mBuffer[mWriteIndex++] = value; |
| 42 | if (mWriteIndex >= getSize()) { |
| 43 | mWriteIndex = 0; |
| 44 | } |
| 45 | mReadAvailable++; |
| 46 | } else { |
| 47 | ALOGE("Error: SHCircularBuffer no space to write. allocated size %zu ", getSize()); |
| 48 | } |
| 49 | } |
| 50 | inline T read() { |
| 51 | T value = T(); |
| 52 | if (availableToRead()) { |
| 53 | value = mBuffer[mReadIndex++]; |
| 54 | if (mReadIndex >= getSize()) { |
| 55 | mReadIndex = 0; |
| 56 | } |
| 57 | mReadAvailable--; |
| 58 | } else { |
| 59 | ALOGW("Warning: SHCircularBuffer no data available to read. Default value returned"); |
| 60 | } |
| 61 | return value; |
| 62 | } |
| 63 | inline size_t availableToRead() const { |
| 64 | return mReadAvailable; |
| 65 | } |
| 66 | inline size_t availableToWrite() const { |
| 67 | return getSize() - mReadAvailable; |
| 68 | } |
| 69 | inline size_t getSize() const { |
| 70 | return mBuffer.size(); |
| 71 | } |
| 72 | |
| 73 | private: |
| 74 | std::vector<T> mBuffer; |
| 75 | size_t mReadIndex; |
| 76 | size_t mWriteIndex; |
| 77 | size_t mReadAvailable; |
| 78 | }; |
| 79 | |
| 80 | |
| 81 | #endif //SHCIRCULARBUFFER_H |