pub fn clamp_index(given_indx: &isize, max_size: &isize) -> RUMResult<usize>
Expand description
Take a requested index and the maximum size of the item container. Check if the index is valid and return an error if it is. The purpose of this function is to enable handling of out of bounds without triggering a panic. Also, add negative indices like Python does when doing a reverse search!
- If the index is 0, return Error
- If the index is below 0, return the max - index iff max - index > 0
- If the index is bigger than the defined max, return Error.
- Otherwise, return the given index.
§Examples
§Min
use ::rumtk_core::core::clamp_index;
use ::rumtk_core::strings::format_compact;
let max: isize = 5;
let i: isize = 1;
let result = clamp_index(&i, &max).unwrap();
assert_eq!(&1, &result, "{}", format_compact!("Expected to receive 0 but got {}", &result))
§Max
use ::rumtk_core::core::clamp_index;
use ::rumtk_core::strings::format_compact;
let max: isize = 5;
let i: isize = 5;
let result = clamp_index(&i, &max).unwrap();
assert_eq!(&5, &result, "{}", format_compact!("Expected to receive 0 but got {}", &result))
§Valid
use ::rumtk_core::core::clamp_index;
use ::rumtk_core::strings::format_compact;
let max: isize = 5;
let i: isize = 5;
let result = clamp_index(&i, &max).unwrap();
assert_eq!(&5, &result, "{}", format_compact!("Expected to receive 0 but got {}", &result))
§Valid Negative Index (reverse lookup)
use ::rumtk_core::core::clamp_index;
use ::rumtk_core::strings::format_compact;
let max: isize = 5;
let i: isize = -1;
let result = clamp_index(&i, &max).unwrap();
assert_eq!(&5, &result, "{}", format_compact!("Expected to receive 0 but got {}", &result))