rs_blocks/
ema.rs

1// Copyright ⓒ 2019-2021 Lewis Belcher
2// Licensed under the MIT license (see LICENSE or <http://opensource.org/licenses/MIT>).
3// All files in the project carrying such notice may not be copied, modified, or
4// distributed except according to those terms
5
6use std::ops;
7
8pub struct Ema<T> {
9	current: Option<T>,
10	alpha: T,
11}
12
13impl<T> Ema<T>
14where
15	T: From<u8> + Copy + ops::Mul<Output = T> + ops::Add<Output = T> + ops::Sub<Output = T>,
16{
17	pub fn new(alpha: T) -> Ema<T> {
18		Ema {
19			current: None,
20			alpha,
21		}
22	}
23
24	pub fn push(&mut self, new: T) -> T {
25		if let Some(mut current) = self.current {
26			current = self.alpha * current + (T::from(1) - self.alpha) * new;
27			self.current = Some(current);
28			current
29		} else {
30			self.current = Some(new);
31			new
32		}
33	}
34
35	pub fn reset(&mut self) {
36		self.current = None;
37	}
38}