[][src]Crate slice_of_array

Extension traits for viewing a slice as a slice of arrays or vice versa.

Provides the following methods on [T]:

  • nest: &[T] -> &[[T; n]]
  • flat: &[[T; n]] -> &[T]
  • as_array: &[T] -> &[T; n] (the reverse is already provided by a coercion)
  • nest_mut, flat_mut, as_mut_array for &mut [_].

Altogether, these let you swap between arbitrary representations of contiguous, T-aligned streams of T data. For instance, to view a [[i32; 6]; 5] as a &[[[i32; 3]; 2]; 5], one could write

x.flat().nest().nest().as_array()

Type inference generally works quite well, and as long as the final shape is unambiguous there is no need to annotate types in the middle of the method chain.

In cases where type inference is unable to determine the target array size, one can use a turbofish: e.g .x.nest::<[_; 3]>().

use ::slice_of_array::prelude::*;

let vec = vec![[2i32, 2, 2], [7, 7, 7], [4, 4, 4], [1, 1, 1]];
assert_eq!(vec.flat(), &[2, 2, 2, 7, 7, 7, 4, 4, 4, 1, 1, 1]);

// note: this requires an annotation only due to polymorphism in PartialEq
let slc = vec.nest::<[_; 2]>();
assert_eq!(slc, &[[[2i32, 2, 2], [7, 7, 7]], [[ 4, 4, 4], [1, 1, 1]]]);

nest and as_array panic on failure rather than returning options. The rationale is that it is believed that these these conversions are seldom needed on arbitrary user data which may be the wrong size; rather, they are most likely used when bridging the gap between APIs that work with flattened slices and APIs that work with slices of arrays.

Zero-cost conversions in owned data (e.g. between Vec<T> and Vec<[T; n]>) are not provided, and are probably impossible in consideration of e.g. custom allocators. If you need to convert between such types, you can use these traits in tandem with <[T]>::to_vec to perform a copy:

let vec = vec![[2i32, 2, 2], [7, 7, 7]];

// copying into a Vec<i32>
let flattened = vec.flat().to_vec();
assert_eq!(flattened, vec![2i32, 2, 2, 7, 7, 7]);

Modules

prelude

Traits

IsSliceomorphic

Marker trait used in bounds of Slice{Flat,Nest,Array}Ext.

SliceArrayExt

Permits viewing a slice as an array.

SliceFlatExt

Permits viewing a slice of arrays as a flat slice.

SliceNestExt

Permits viewing a slice as a slice of arrays.