Skip to content

Commit

Permalink
Add constructor and test in limit.
Browse files Browse the repository at this point in the history
  • Loading branch information
pierre-rouanet committed Aug 22, 2023
1 parent fcbdc05 commit d476e13
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions src/limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,52 @@ use serde::{Deserialize, Serialize};
/// Limit wrapper
pub struct Limit {
/// lower limit
pub min: f64,
min: f64,
/// upper limit
pub max: f64,
max: f64,
}

impl Limit {
/// Create new limit
pub fn new(min: f64, max: f64) -> Self {
if min > max {
panic!("min must be less than max");
}
Self { min, max }
}

/// lower limit
pub fn min(&self) -> f64 {
self.min
}

/// upper limit
pub fn max(&self) -> f64 {
self.max
}

/// Clamp value to limits
pub fn clamp(&self, value: f64) -> f64 {
value.clamp(self.min, self.max)
}
}

#[cfg(test)]
mod tests {
use crate::Limit;

#[test]
#[should_panic]
fn bad_limit() {
Limit::new(1.0, -1.0);
}

#[test]
fn check_limit() {
let limit = Limit::new(-1.0, 1.0);

assert_eq!(limit.clamp(-2.0), -1.0);
assert_eq!(limit.clamp(0.0), 0.0);
assert_eq!(limit.clamp(2.0), 1.0);
}
}

0 comments on commit d476e13

Please sign in to comment.