Skip to main content

ps_util/
subarray.rs

1use crate::subarray_checked;
2
3/// Get a subarray of length `S` at `index`.
4///
5/// # Examples
6///
7/// ```
8/// use ps_util::subarray;
9/// let data = [1, 2, 3, 4, 5];
10/// let chunk: &[i32; 2] = subarray::<2, i32>(&data, 1);
11/// assert_eq!(chunk, &[2, 3]);
12/// ```
13///
14/// Works with vectors:
15///
16/// ```
17/// use ps_util::subarray;
18/// let vec = vec!["a", "b", "c", "d"];
19/// let chunk: &[&str; 3] = subarray::<3, &str>(&vec, 0);
20/// assert_eq!(chunk, &["a", "b", "c"]);
21/// ```
22///
23/// # Panics
24///
25/// Panics if `index + S` exceeds the slice length:
26///
27/// ```should_panic
28/// use ps_util::subarray;
29/// let data = [1, 2, 3];
30/// let _chunk: &[i32; 3] = subarray::<3, i32>(&data, 1);
31/// ```
32#[allow(clippy::expect_used)]
33pub fn subarray<const S: usize, T>(slice: &[T], index: usize) -> &[T; S] {
34    subarray_checked(slice, index).expect("range end index out of range for subarray")
35}