From 7bc59f6df8106ed23aada1737ab6ba8261bcb6ca Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Tue, 12 Nov 2024 19:33:54 +0100 Subject: [PATCH] add BrightnessGrid::saturating_load --- crates/servicepoint/src/brightness.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/servicepoint/src/brightness.rs b/crates/servicepoint/src/brightness.rs index e5a82b3..009b8fe 100644 --- a/crates/servicepoint/src/brightness.rs +++ b/crates/servicepoint/src/brightness.rs @@ -37,6 +37,13 @@ pub struct Brightness(u8); /// ``` pub type BrightnessGrid = PrimitiveGrid; +impl BrightnessGrid { + /// Like [Self::load], but ignoring any out-of-range brightness values + pub fn saturating_load(width: usize, height: usize, data: &[u8]) -> Self { + PrimitiveGrid::load(width, height, data).map(Brightness::saturating_from) + } +} + impl From for u8 { fn from(brightness: Brightness) -> Self { brightness.0 @@ -105,7 +112,7 @@ impl TryFrom> for BrightnessGrid { let brightnesses = value .iter() .map(|b| Brightness::try_from(*b)) - .collect::, _>>()?; + .collect::, _>>()?; Ok(BrightnessGrid::load( value.width(), value.height(), @@ -155,4 +162,10 @@ mod tests { assert_eq!(Brightness::MAX, Brightness::saturating_from(100)); assert_eq!(Brightness(5), Brightness::saturating_from(5)); } + + #[test] + fn saturating_load() { + assert_eq!(BrightnessGrid::load(2,2, &[Brightness::MAX, Brightness::MAX, Brightness::MIN, Brightness::MAX]), + BrightnessGrid::saturating_load(2,2, &[255u8, 23, 0, 42])); + } }