Skip to content

Commit

Permalink
implement integer ranges
Browse files Browse the repository at this point in the history
  • Loading branch information
micahrj committed Jan 20, 2024
1 parent 9bcc00c commit b1bfeee
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/params/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32> {
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<u32> {
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);

0 comments on commit b1bfeee

Please sign in to comment.