Get index contained in range (if out of bounds, return the bound it is out of)

I am trying to simplify the following code and thought Rust ranges could be useful:

				let first = FIRST_INDEX as isize;
				let last = self.last_index() as isize;
				let new_index = if index < first {
					first
				} else if index > last {
					last
				} else {
					index
				} as usize;
				Some(new_index)

As you can see, new_index will be guaranteed to be in the range of first and last (can also be last, so index is in first..=last). Is there a way to do this with ranges somehow, or another way to do this more concisely with less code? If rust ranges don't provide this functionality, does anyone know of a rust crate that could do this? What I have now seems overly verbose.
Looking forward to reading your suggestions! Thanks for your help!

There's Ord::clamp:

let new_index = index.clamp(first, last);
1 Like

Thank you very much, this is exactly what I was looking for!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.