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 RTC_DCHECK(capacity > 0); |
| 27 data_ = new T[capacity + 1]; |
| 28 end_ = data_ + (capacity + 1); |
| 29 front_ = data_; |
| 30 back_ = data_; |
| 31 } |
| 32 ~RingBuffer() { |
| 33 delete[] data_; |
| 34 } |
| 35 |
| 36 // Removes an element from the front of the queue. |
| 37 void pop_front() { |
| 38 RTC_DCHECK(!empty()); |
| 39 front_++; |
| 40 if (front_ == end_) { |
| 41 front_ = data_; |
| 42 } |
| 43 } |
| 44 |
| 45 // Appends an element to the back of the queue (and removes an |
| 46 // element from the front if there is no space at the back of the queue). |
| 47 void push_back(const T& elem) { |
| 48 *back_ = elem; |
| 49 back_++; |
| 50 if (back_ == end_) { |
| 51 back_ = data_; |
| 52 } |
| 53 if (back_ == front_) { |
| 54 front_++; |
| 55 } |
| 56 if (front_ == end_) { |
| 57 front_ = data_; |
| 58 } |
| 59 } |
| 60 |
| 61 T& front() { |
| 62 return *front_; |
| 63 } |
| 64 |
| 65 const T& front() const { |
| 66 return *front_; |
| 67 } |
| 68 |
| 69 bool empty() const { |
| 70 return (front_ == back_); |
| 71 } |
| 72 |
| 73 private: |
| 74 T* data_; |
| 75 T* end_; |
| 76 T* front_; |
| 77 T* back_; |
| 78 |
| 79 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RingBuffer); |
| 80 }; |
| 81 |
| 82 } // namespace webrtc |
| 83 |
| 84 #endif // WEBRTC_CALL_RINGBUFFER_H_ |
OLD | NEW |