diff --git a/Cargo.lock b/Cargo.lock index 4bff427..5430dc1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1237,7 +1237,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "sliding_features" -version = "9.1.0" +version = "9.2.0" dependencies = [ "ballpark", "criterion", diff --git a/Cargo.toml b/Cargo.toml index 475b5e1..ec0456f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ cargo-features = ["edition2024"] [package] name = "sliding_features" -version = "9.1.0" +version = "9.2.0" authors = ["MathisWellmann "] edition = "2024" license-file = "LICENSE" diff --git a/img/trend_flex.png b/img/trend_flex.png index e950d8d..b02620d 100644 Binary files a/img/trend_flex.png and b/img/trend_flex.png differ diff --git a/src/rolling/first.rs b/src/rolling/first.rs new file mode 100644 index 0000000..3a07679 --- /dev/null +++ b/src/rolling/first.rs @@ -0,0 +1,47 @@ +//! Retains the first value it sees and never updates again. + +use crate::View; + +/// Retains the first value it ever sees and never updates it again. +#[derive(Default, Clone, Debug)] +pub struct First { + out: Option, +} + +impl First { + /// Create a new First View + #[inline(always)] + pub fn new() -> First { + First { out: None } + } +} + +impl View for First { + fn update(&mut self, val: T) { + debug_assert!(val.is_finite(), "value must be finite"); + if self.out.is_none() { + self.out = Some(val); + } + } + + fn last(&self) -> Option { + self.out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first() { + let mut f = First::new(); + assert_eq!(f.last(), None); + f.update(42.0); + assert_eq!(f.last(), Some(42.0)); + f.update(7.0); + assert_eq!(f.last(), Some(42.0)); + f.update(99.0); + assert_eq!(f.last(), Some(42.0)); + } +} diff --git a/src/rolling/mod.rs b/src/rolling/mod.rs index 022d5aa..caab30d 100644 --- a/src/rolling/mod.rs +++ b/src/rolling/mod.rs @@ -1,9 +1,11 @@ //! This module contains `View` implementations that are updated on a rolling basis, but don't maintain a sliding window with history. mod drawdown; +mod first; mod ln_return; mod welford_rolling; pub use drawdown::Drawdown; +pub use first::First; pub use ln_return::LnReturn; pub use welford_rolling::WelfordRolling;