OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. |
| 3 * |
| 4 * Use of this source code is governed by a BSD-style license |
| 5 * that can be found in the LICENSE file in the root of the source |
| 6 * tree. An additional intellectual property rights grant can be found |
| 7 * in the file PATENTS. All contributing project authors may |
| 8 * be found in the AUTHORS file in the root of the source tree. |
| 9 * |
| 10 */ |
| 11 |
| 12 #ifndef WEBRTC_CALL_RINGBUFFER_H_ |
| 13 #define WEBRTC_CALL_RINGBUFFER_H_ |
| 14 |
| 15 #include <memory> |
| 16 |
| 17 #include "webrtc/base/checks.h" |
| 18 |
| 19 namespace webrtc { |
| 20 |
| 21 // A RingBuffer works like a fixed size queue which starts discarding |
| 22 // the oldest elements when it becomes full. |
| 23 template <typename T> |
| 24 class RingBuffer { |
| 25 public: |
| 26 // Creates a RingBuffer with space for |capacity| elements. |
| 27 explicit RingBuffer(size_t capacity) |
| 28 : // We allocate space for one extra sentinel element. |
| 29 data_(new T[capacity + 1]) { |
| 30 RTC_DCHECK(capacity > 0); |
| 31 end_ = data_.get() + (capacity + 1); |
| 32 front_ = data_.get(); |
| 33 back_ = data_.get(); |
| 34 } |
| 35 |
| 36 ~RingBuffer() { |
| 37 // The unique_ptr will free the memory. |
| 38 } |
| 39 |
| 40 // Removes an element from the front of the queue. |
| 41 void pop_front() { |
| 42 RTC_DCHECK(!empty()); |
| 43 ++front_; |
| 44 if (front_ == end_) { |
| 45 front_ = data_.get(); |
| 46 } |
| 47 } |
| 48 |
| 49 // Appends an element to the back of the queue (and removes an |
| 50 // element from the front if there is no space at the back of the queue). |
| 51 void push_back(const T& elem) { |
| 52 *back_ = elem; |
| 53 ++back_; |
| 54 if (back_ == end_) { |
| 55 back_ = data_.get(); |
| 56 } |
| 57 if (back_ == front_) { |
| 58 ++front_; |
| 59 } |
| 60 if (front_ == end_) { |
| 61 front_ = data_.get(); |
| 62 } |
| 63 } |
| 64 |
| 65 T& front() { return *front_; } |
| 66 |
| 67 const T& front() const { return *front_; } |
| 68 |
| 69 bool empty() const { return (front_ == back_); } |
| 70 |
| 71 private: |
| 72 std::unique_ptr<T[]> data_; |
| 73 T* end_; |
| 74 T* front_; |
| 75 T* back_; |
| 76 |
| 77 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RingBuffer); |
| 78 }; |
| 79 |
| 80 } // namespace webrtc |
| 81 |
| 82 #endif // WEBRTC_CALL_RINGBUFFER_H_ |
OLD | NEW |