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"
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
>
40 static_assert(!IsFloatingPoint
<T
>::value
,
41 "floating-point types are unsupported due to rounding "
44 RollingMean(size_t aMaxValues
)
46 mMaxValues(aMaxValues
),
49 MOZ_ASSERT(aMaxValues
> 0);
52 RollingMean
& operator=(RollingMean
&& aOther
) {
53 MOZ_ASSERT(this != &aOther
, "self-assignment is forbidden");
55 new(this) RollingMean(aOther
.mMaxValues
);
56 mInsertIndex
= aOther
.mInsertIndex
;
57 mTotal
= aOther
.mTotal
;
58 mValues
.swap(aOther
.mValues
);
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
;
72 if (!mValues
.append(aValue
))
74 mTotal
= mTotal
+ aValue
;
77 mInsertIndex
= (mInsertIndex
+ 1) % mMaxValues
;
82 * Calculate the rolling mean.
86 return T(mTotal
/ mValues
.length());
90 return mValues
.empty();
94 * Remove all values from the rolling mean.
107 } // namespace mozilla
109 #endif // mozilla_RollingMean_h_