From 08d6d7c262612371248658560eb72b32429bb610 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 18 Mar 2020 23:07:23 +0100 Subject: [PATCH] library: core: color: add clamp method --- src/core/color.rs | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/src/core/color.rs b/src/core/color.rs index 2810c17..b1e9475 100644 --- a/src/core/color.rs +++ b/src/core/color.rs @@ -36,6 +36,20 @@ impl LinearColor { pub fn new(r: f32, g: f32, b: f32) -> Self { LinearColor { r, g, b } } + + #[must_use] + pub fn clamp(self) -> Self { + fn clamp(v: f32) -> f32 { + if v > 1. { + 1. + } else if v < 0. { + 0. + } else { + v + } + }; + LinearColor::new(clamp(self.r), clamp(self.g), clamp(self.b)) + } } impl Default for LinearColor { @@ -81,21 +95,12 @@ impl DivAssign for LinearColor { } impl From for image::Rgb { - fn from(color: LinearColor) -> Self { - fn clamp(v: f32) -> f32 { - // FIXME: use clamp from nightly - if v > 1. { - 1. - } else if v < 0. { - 0. - } else { - v - } - }; + fn from(mut color: LinearColor) -> Self { + color = color.clamp(); image::Rgb([ - (clamp(color.r) * 255.) as u8, - (clamp(color.g) * 255.) as u8, - (clamp(color.b) * 255.) as u8, + (color.r * 255.) as u8, + (color.g * 255.) as u8, + (color.b * 255.) as u8, ]) } } @@ -299,6 +304,12 @@ mod test { ); } + #[test] + fn clamp_works() { + let color = LinearColor::new(1.5, -1., 0.5); + assert_eq!(color.clamp(), LinearColor::new(1., 0., 0.5)) + } + #[test] fn deserialization_works() { let yaml = "{r: 1.0, g: 0.5, b: 0.2}";