Bug 994889 - Fix how to get video size from OMXCodec r=cajbir
[gecko.git] / mfbt / RollingMean.h
blob5caee3bc830491aaf1ab5aa1a28ff8cec75a4fa5
1 /* -*- Mode: C++; tab-w idth: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 /* A set abstraction for enumeration values. */
8 #ifndef mozilla_RollingMean_h_
9 #define mozilla_RollingMean_h_
11 #include "mozilla/Assertions.h"
12 #include "mozilla/TypeTraits.h"
13 #include "mozilla/Vector.h"
15 #include <algorithm>
16 #include <stddef.h>
17 #include <stdint.h>
19 namespace mozilla {
21 /**
22 * RollingMean<T> calculates a rolling mean of the values it is given. It
23 * accumulates the total as values are added and removed. The second type
24 * argument S specifies the type of the total. This may need to be a bigger
25 * type in order to maintain that the sum of all values in the average doesn't
26 * exceed the maximum input value.
28 * WARNING: Float types are not supported due to rounding errors.
30 template<typename T, typename S>
31 class RollingMean
33 private:
34 size_t mInsertIndex;
35 size_t mMaxValues;
36 Vector<T> mValues;
37 S mTotal;
39 public:
40 static_assert(!IsFloatingPoint<T>::value,
41 "floating-point types are unsupported due to rounding "
42 "errors");
44 RollingMean(size_t aMaxValues)
45 : mInsertIndex(0),
46 mMaxValues(aMaxValues),
47 mTotal(0)
49 MOZ_ASSERT(aMaxValues > 0);
52 RollingMean& operator=(RollingMean&& aOther) {
53 MOZ_ASSERT(this != &aOther, "self-assignment is forbidden");
54 this->~RollingMean();
55 new(this) RollingMean(aOther.mMaxValues);
56 mInsertIndex = aOther.mInsertIndex;
57 mTotal = aOther.mTotal;
58 mValues.swap(aOther.mValues);
59 return *this;
62 /**
63 * Insert a value into the rolling mean.
65 bool insert(T aValue) {
66 MOZ_ASSERT(mValues.length() <= mMaxValues);
68 if (mValues.length() == mMaxValues) {
69 mTotal = mTotal - mValues[mInsertIndex] + aValue;
70 mValues[mInsertIndex] = aValue;
71 } else {
72 if (!mValues.append(aValue))
73 return false;
74 mTotal = mTotal + aValue;
77 mInsertIndex = (mInsertIndex + 1) % mMaxValues;
78 return true;
81 /**
82 * Calculate the rolling mean.
84 T mean() {
85 MOZ_ASSERT(!empty());
86 return T(mTotal / mValues.length());
89 bool empty() {
90 return mValues.empty();
93 /**
94 * Remove all values from the rolling mean.
96 void clear() {
97 mValues.clear();
98 mInsertIndex = 0;
99 mTotal = T(0);
102 size_t maxValues() {
103 return mMaxValues;
107 } // namespace mozilla
109 #endif // mozilla_RollingMean_h_