From 5ee3677fb77165ec1d9ea849bc3535d164fd7177 Mon Sep 17 00:00:00 2001 From: MathisWellmann Date: Tue, 9 Jun 2026 00:27:23 +0200 Subject: [PATCH] add `First` --- Cargo.lock | 2 +- Cargo.toml | 2 +- img/trend_flex.png | Bin 94131 -> 94131 bytes src/rolling/first.rs | 47 +++++++++++++++++++++++++++++++++++++++++++ src/rolling/mod.rs | 2 ++ 5 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/rolling/first.rs 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 e950d8d6e9d793e2840b154deb1d467202185f85..b02620d5dd3348b2a7eb8d061989b8e875eb5541 100644 GIT binary patch delta 34 scmV+-0Nwwy-vzVZ1%R{xe_RmjuHyxwa@7O9*o*P_$McxCk6ZyH6FtZg@c;k- delta 34 ocmdmdpLO$n)`l&N^)UkTA|xL$0D-5gpUXO@gr@ENF^nq00P8jk3IG5A 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;