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 "webrtc/base/checks.h" |
| 16 |
| 17 namespace webrtc { |
| 18 |
| 19 // A RingBuffer works like a fixed size queue which starts discarding |
| 20 // the oldest elements when it becomes full. |
| 21 template <typename T> |
| 22 class RingBuffer { |
| 23 public: |
| 24 // Creates a RingBuffer with space for |capacity| elements. |
| 25 explicit RingBuffer(size_t capacity) |
| 26 : // We allocate space for one extra sentinel element. |
| 27 data_(new T[capacity + 1]) { |
| 28 RTC_DCHECK(capacity > 0); |
| 29 end_ = data_.get() + (capacity + 1); |
| 30 front_ = data_.get(); |
| 31 back_ = data_.get(); |
| 32 } |
| 33 |
| 34 ~RingBuffer() { |
| 35 // The unique_ptr will free the memory. |
| 36 } |
| 37 |
| 38 // Removes an element from the front of the queue. |
| 39 void pop_front() { |
| 40 RTC_DCHECK(!empty()); |
| 41 ++front_; |
| 42 if (front_ == end_) { |
| 43 front_ = data_.get(); |
| 44 } |
| 45 } |
| 46 |
| 47 // Appends an element to the back of the queue (and removes an |
| 48 // element from the front if there is no space at the back of the queue). |
| 49 void push_back(const T& elem) { |
| 50 *back_ = elem; |
| 51 ++back_; |
| 52 if (back_ == end_) { |
| 53 back_ = data_.get(); |
| 54 } |
| 55 if (back_ == front_) { |
| 56 ++front_; |
| 57 } |
| 58 if (front_ == end_) { |
| 59 front_ = data_.get(); |
| 60 } |
| 61 } |
| 62 |
| 63 T& front() { return *front_; } |
| 64 |
| 65 const T& front() const { return *front_; } |
| 66 |
| 67 bool empty() const { return (front_ == back_); } |
| 68 |
| 69 private: |
| 70 std::unique_ptr<T[]> data_; |
| 71 T* end_; |
| 72 T* front_; |
| 73 T* back_; |
| 74 |
| 75 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RingBuffer); |
| 76 }; |
| 77 |
| 78 } // namespace webrtc |
| 79 |
| 80 #endif // WEBRTC_CALL_RINGBUFFER_H_ |
OLD | NEW |