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