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

357 Views Asked by At

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));
2

There are 2 best solutions below

0
On BEST ANSWER

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

1
On

You can use min() and max().

  let input: i64 = 8456;
  let saturated: i64 = input.max(7).min(4000);
  assert!((7..=4000).contains(saturated));