ps_util/subarray_checked.rs
1/// Returns a reference to a contiguous subarray of length `S` starting at `index`.
2///
3/// Returns `None` if the requested range exceeds the slice bounds.
4/// Returns `None` if `index + S` overflows.
5///
6/// This is the bounds-checked variant. For an unchecked version, see `subarray_unchecked`.
7///
8/// # Examples
9///
10/// ```
11/// use ps_util::subarray_checked;
12/// let data = [1, 2, 3, 4, 5];
13/// let chunk: Option<&[i32; 2]> = subarray_checked::<2, i32>(&data, 1);
14/// assert_eq!(chunk, Some(&[2, 3]));
15///
16/// // Out of bounds returns None
17/// assert_eq!(subarray_checked::<2, i32>(&data, 4), None);
18/// ```
19///
20/// Works with vectors:
21///
22/// ```
23/// use ps_util::subarray_checked;
24/// let vec = vec!["a", "b", "c", "d"];
25/// let chunk: Option<&[&str; 3]> = subarray_checked::<3, &str>(&vec, 0);
26/// assert_eq!(chunk, Some(&["a", "b", "c"]));
27///
28/// // Out of bounds returns None
29/// assert_eq!(subarray_checked::<3, &str>(&vec, 2), None);
30/// ```
31pub fn subarray_checked<const S: usize, T>(slice: &[T], index: usize) -> Option<&[T; S]> {
32 let end = index.checked_add(S)?;
33 slice.get(index..end)?.as_array()
34}