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