1use 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}