Do you know any saturation function? To make number fit to given range?

Issue

Looking for a saturating function in Rust.
Here I called it fit_to_range(range).

  let input:i64= something;
  let saturated:64= input.fit_to_range(7..=4000);
  assert!((7..=4000).contains(saturated));

Solution

What you’re looking for is the clamp function defined in the Ord trait, which is implemented by i64.
For example:

let input: i64 = 5000;
let saturated = input.clamp(7, 4000);
assert!((7..=4000).contains(&saturated));

Documentation of the clamp function

Answered By – kotatsuyaki

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.