From b1bfeee17cd38b135bfcb1455e325ce6a3b51175 Mon Sep 17 00:00:00 2001 From: Micah Johnston Date: Sat, 20 Jan 2024 01:15:01 -0600 Subject: [PATCH] implement integer ranges --- src/params/range.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/params/range.rs b/src/params/range.rs index c1a2e1f..d5c73a3 100644 --- a/src/params/range.rs +++ b/src/params/range.rs @@ -61,3 +61,64 @@ macro_rules! float_range { float_range!(f32); float_range!(f64); + +macro_rules! int_range { + ($int:ty) => { + impl Range<$int> for std::ops::Range<$int> { + #[inline] + fn steps(&self) -> Option { + Some(self.end.abs_diff(self.start) as u32) + } + + #[inline] + fn encode(&self, value: $int) -> ParamValue { + let steps_recip = 1.0 / (self.end as f64 - self.start as f64); + (value as f64 - self.start as f64 + 0.5) * steps_recip + } + + #[inline] + fn decode(&self, value: ParamValue) -> $int { + let steps = self.end as f64 - self.start as f64; + (self.start as f64 + value * steps) as $int + } + } + + impl Range<$int> for std::ops::RangeInclusive<$int> { + #[inline] + fn steps(&self) -> Option { + Some(self.end().abs_diff(*self.start()).saturating_add(1) as u32) + } + + #[inline] + fn encode(&self, value: $int) -> ParamValue { + let steps_recip = 1.0 / (*self.end() as f64 + 1.0 - *self.start() as f64); + (value as f64 - *self.start() as f64 + 0.5) * steps_recip + } + + #[inline] + fn decode(&self, value: ParamValue) -> $int { + let steps = *self.end() as f64 + 1.0 - *self.start() as f64; + (*self.start() as f64 + value * steps) as $int + } + } + + impl DefaultRange for $int { + type Range = std::ops::Range<$int>; + + #[inline] + fn default_range() -> Self::Range { + 0..1 + } + } + }; +} + +int_range!(u8); +int_range!(u16); +int_range!(u32); +int_range!(u64); + +int_range!(i8); +int_range!(i16); +int_range!(i32); +int_range!(i64);