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/. */
7 /* A set abstraction for enumeration values. */
9 #ifndef mozilla_RollingMean_h_
10 #define mozilla_RollingMean_h_
12 #include "mozilla/Assertions.h"
13 #include "mozilla/TypeTraits.h"
14 #include "mozilla/Vector.h"
21 * RollingMean<T> calculates a rolling mean of the values it is given. It
22 * accumulates the total as values are added and removed. The second type
23 * argument S specifies the type of the total. This may need to be a bigger
24 * type in order to maintain that the sum of all values in the average doesn't
25 * exceed the maximum input value.
27 * WARNING: Float types are not supported due to rounding errors.
29 template<typename T
, typename S
>
39 static_assert(!IsFloatingPoint
<T
>::value
,
40 "floating-point types are unsupported due to rounding "
43 explicit RollingMean(size_t aMaxValues
)
45 mMaxValues(aMaxValues
),
48 MOZ_ASSERT(aMaxValues
> 0);
51 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.
67 MOZ_ASSERT(mValues
.length() <= mMaxValues
);
69 if (mValues
.length() == mMaxValues
) {
70 mTotal
= mTotal
- mValues
[mInsertIndex
] + aValue
;
71 mValues
[mInsertIndex
] = aValue
;
73 if (!mValues
.append(aValue
)) {
76 mTotal
= mTotal
+ aValue
;
79 mInsertIndex
= (mInsertIndex
+ 1) % mMaxValues
;
84 * Calculate the rolling mean.
89 return T(mTotal
/ mValues
.length());
94 return mValues
.empty();
98 * Remove all values from the rolling mean.
113 } // namespace mozilla
115 #endif // mozilla_RollingMean_h_