SHCircularBuffer.h 2.2 KB

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