Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#ifndef mozilla_layers_RecentEventsBuffer_h
8
#define mozilla_layers_RecentEventsBuffer_h
9
10
#include <deque>
11
12
#include "mozilla/TimeStamp.h"
13
14
namespace mozilla {
15
namespace layers {
16
/**
17
* RecentEventsBuffer: maintains an age constrained buffer of events
18
*
19
* Intended for use with elements of type InputData, but the only requirement
20
* is a member "mTimeStamp" of type TimeStamp
21
*/
22
template <typename Event>
23
class RecentEventsBuffer {
24
public:
25
explicit RecentEventsBuffer(TimeDuration maxAge);
26
27
void push(Event event);
28
void clear();
29
30
typedef typename std::deque<Event>::size_type size_type;
31
size_type size() { return mBuffer.size(); }
32
33
// Delegate to container for iterators
34
typedef typename std::deque<Event>::iterator iterator;
35
typedef typename std::deque<Event>::const_iterator const_iterator;
36
iterator begin() { return mBuffer.begin(); }
37
iterator end() { return mBuffer.end(); }
38
const_iterator cbegin() const { return mBuffer.cbegin(); }
39
const_iterator cend() const { return mBuffer.cend(); }
40
41
// Also delegate for front/back
42
typedef typename std::deque<Event>::reference reference;
43
typedef typename std::deque<Event>::const_reference const_reference;
44
reference front() { return mBuffer.front(); }
45
reference back() { return mBuffer.back(); }
46
const_reference front() const { return mBuffer.front(); }
47
const_reference back() const { return mBuffer.back(); }
48
49
private:
50
TimeDuration mMaxAge;
51
std::deque<Event> mBuffer;
52
};
53
54
template <typename Event>
55
RecentEventsBuffer<Event>::RecentEventsBuffer(TimeDuration maxAge)
56
: mMaxAge(maxAge), mBuffer() {}
57
58
template <typename Event>
59
void RecentEventsBuffer<Event>::push(Event event) {
60
// Events must be pushed in chronological order
61
MOZ_ASSERT(mBuffer.empty() || mBuffer.back().mTimeStamp <= event.mTimeStamp);
62
63
mBuffer.push_back(event);
64
65
// Flush all events older than the given lifetime
66
TimeStamp bound = event.mTimeStamp - mMaxAge;
67
while (!mBuffer.empty()) {
68
if (mBuffer.front().mTimeStamp >= bound) {
69
break;
70
}
71
mBuffer.pop_front();
72
}
73
}
74
75
template <typename Event>
76
void RecentEventsBuffer<Event>::clear() {
77
mBuffer.clear();
78
}
79
80
} // namespace layers
81
} // namespace mozilla
82
83
#endif // mozilla_layers_RecentEventsBuffer_h