Function scolapasta_aref::offset_to_index

source ·
pub fn offset_to_index(index: i64, len: usize) -> Option<usize>
Expand description

Convert a signed aref offset to a usize index into the underlying container.

Negative indexes are interpreted as indexing from the end of the container as long as their magnitude is less than the given length.

Callers must still check whether the returned index is in bounds for the container. The returned index may be out of range since this routine can be used to calculate indexes beyond the length of the container during assignment (for example, Array#[]= may perform length-extension upon an out-of-bounds index).

§Examples

let data = "ABC, 123, XYZ";

let offset = 6;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 6);
assert_eq!(&data[index..], "23, XYZ");

let offset = 55;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 55);

let offset = -5;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 8);
assert_eq!(&data[index..], ", XYZ");

let offset = -44;
let index = scolapasta_aref::offset_to_index(offset, data.len());
assert_eq!(index, None);