Crate static_slicing

Source
Expand description

Provides utilities for emulating statically-checked array slicing and indexing.

The StaticRangeIndex type can be used as an index into fixed-size arrays to get or set a fixed-size slice. Likewise, the StaticIndex type can be used to get or set the element at a given index.

The static index types can be used to index other collections, such as slices and Vecs, but only when they are wrapped in a SliceWrapper. Due to Rust’s orphan rule and lack of specialization support, this seems to be the best we can do - it’s apparently impossible to implement Index for both [T; N] and [T].

§Examples

This example demonstrates how to obtain an 8-element slice of an array, starting from index 4.

use static_slicing::StaticRangeIndex;
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let sub_arr = arr[StaticRangeIndex::<4, 8>];
assert_eq!(sub_arr, arr[4..12]);

This example demonstrates how to obtain a mutable 3-element slice of an array, starting from index 2.

use static_slicing::StaticRangeIndex;
let mut arr = [3, 5, 7, 9, 11];
let sub_arr = &mut arr[StaticRangeIndex::<2, 3>];
sub_arr[1] = 13;
assert_eq!(arr[3], 13);

This example demonstrates how to obtain the item at index 2 of a 4-element array.

use static_slicing::StaticIndex;
let arr = [3, 5, 7, 9];
let value = arr[StaticIndex::<2>];
assert_eq!(value, 7);

This example demonstrates how to obtain a 2-element slice of a 4-element Vec starting from index 0.

use static_slicing::{SliceWrapper, StaticRangeIndex};
let x = vec![1, 2, 3];
let x = SliceWrapper::new(x);
assert_eq!(x[StaticRangeIndex::<0, 2>], [1, 2]);

The following examples demonstrate the compile-time safety guarantees of the static slicing framework.

use static_slicing::StaticRangeIndex;
let arr = [1, 2, 3, 4, 5];
// error! we can't get 5 elements starting from index 1
let sub_arr = arr[StaticRangeIndex::<1, 5>];
use static_slicing::StaticIndex;
let arr = [1, 2, 3, 4, 5];
// error! we can't get the item at index 5, because there are only 5 items
let value = arr[StaticIndex::<5>];

The following examples demonstrate the runtime safety guarantees of the static slicing framework. Note that when fixed-size arrays are used, there is zero cost at runtime, since all checks are done at compile time.

use static_slicing::{SliceWrapper, StaticIndex};
let x = SliceWrapper::new(vec![1, 2, 3]);
let _ = x[StaticIndex::<3>];
use static_slicing::{SliceWrapper, StaticIndex};
let mut x = SliceWrapper::new(vec![1, 2, 3]);
x[StaticIndex::<3>] = 5;

Structs§

SliceWrapper
Wrapper around slice references to add support for the static index types.
StaticIndex
A single-element index that exists entirely at compile time.
StaticRangeIndex
A range index that exists entirely at compile time. Range indexes can be used to obtain fixed-size slices. For any pair of (START, LENGTH), the range covered is [START, START+LENGTH).