Crate scolapasta_aref

Source
Expand description

Functions for working with Ruby containers that respond to #[] or “aref”.

§Examples

Index into arrays:

let data = [1, 2, 3, 4, 5];

// Positive offset
let offset = 2;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 2);
assert_eq!(data[index], 3);

// Negative offset
let offset = -3;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 2);
assert_eq!(data[index], 3);

// Out-of-bounds offset
let offset = 10;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 10);

// Out-of-bounds negative offset
let offset = -10;
let index = scolapasta_aref::offset_to_index(offset, data.len());
assert_eq!(index, None);

Index into strings:

let data = "Hello, World!";

// Positive offset
let offset = 7;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 7);
assert_eq!(&data[index..], "World!");

// Negative offset
let offset = -6;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 7);
assert_eq!(&data[index..], "World!");

// Out-of-bounds offset
let offset = 20;
let index = scolapasta_aref::offset_to_index(offset, data.len())?;
assert_eq!(index, 20);

// Out-of-bounds negative offset
let offset = -20;
let index = scolapasta_aref::offset_to_index(offset, data.len());
assert_eq!(index, None);

Functions§

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