[][src]Crate slyce

Slyce implements a python-like slicer for rust. It selects zero or more elements from an input array and returns these elements, in the order selected, as an output array.

A slice selects array elements between an inclusive start index and an exclusive end index, incrementing by a step value.

Indices, of type Index, can be relative to the start of the array (Head), with Head(0) denoting the first element of a non-empty array, or relative to the end of the array (Tail), with Tail(1) denoting the last element of a non-empty array.

The default value for step is 1. The default values for start and end depend on the sign of step, as follows (where len is the length of the input array):

Condition start end
step >= 0 Head(0) Head(len)
step < 0 Tail(1) Tail(len + 1)
Default array slice start and end values

If start or end is Head(n) for n >= len or Tail(m) for m >= len + 1, then it is replaced by the default value for start or end, respectively.

If step is zero, the resultant array is empty.

If step is non-zero, iteration begins at the array index of start incrementing by step while the array index of end has not been reached, with end itself excluded from the iteration. At each iteration step, if the iteration value is inside the bounds of the array, the corresponding element is selected and if the iteration value is outside the bounds of the array no element is selected.

This crate provides a few implementations of From<T> for Index for common types, so you can pass numbers and options instead of Index (just call .into()). An integer index value is equivalent to specifying a position relative to the start or end of the array, depending on whether the value is non-negative or negative, respectively. For example, 0 is equivalent to Head(0) and -1 is equivalent to Tail(1).

Example

use slyce::{Slice, Index};
let v = vec![10,20,30,40,50];
let render = |s: Slice| format!("{:?}", s.apply(&v).collect::<Vec<_>>());

let start: isize = -3;
let s = slyce::Slice{start: start.into(), end: Index::Default, step: None};
assert_eq!(render(s), "[30, 40, 50]");

let s = slyce::Slice{start: Index::Tail(3), end: Index::Default, step: None};
assert_eq!(render(s), "[30, 40, 50]");

let end: Option<isize> = None;
let s = slyce::Slice{start: Index::Tail(3), end: end.into(), step: None};
assert_eq!(render(s), "[30, 40, 50]");

let s = slyce::Slice{start: Index::Tail(3), end: Index::Default, step: Some(-1)};
assert_eq!(render(s), "[30, 20, 10]");

let s = slyce::Slice{start: Index::Head(4), end: Index::Head(0), step: Some(-1)};
assert_eq!(render(s), "[50, 40, 30, 20]");

let s = slyce::Slice{start: Index::Default, end: Index::Head(0), step: Some(-1)};
assert_eq!(render(s), "[50, 40, 30, 20]");

let s = slyce::Slice{start: Index::Tail(1000), end: 2000.into(), step: None};
assert_eq!(render(s), "[10, 20, 30, 40, 50]");

Structs

Slice

A slice has an optional start, an optional end, and an optional step.

Enums

Index

A position inside an array.