ps_util/subarray_unchecked.rs
1/// Get a subarray of length `S` at `index` without bounds checking.
2///
3/// This is the unchecked variant of [`crate::subarray`]. See that function for a safe alternative.
4///
5/// # Safety
6///
7/// The caller must ensure that `index + S <= slice.len()`. Violating this is undefined behavior.
8///
9/// # Examples
10///
11/// ```
12/// use ps_util::subarray_unchecked;
13/// let data = [1, 2, 3, 4, 5];
14/// // SAFETY: index=1, S=2, slice.len()=5, so 1+2 <= 5
15/// let chunk: &[i32; 2] = unsafe { subarray_unchecked::<2, i32>(&data, 1) };
16/// assert_eq!(chunk, &[2, 3]);
17/// ```
18///
19/// Works with vectors:
20///
21/// ```
22/// use ps_util::subarray_unchecked;
23/// let vec = vec!["a", "b", "c", "d"];
24/// // SAFETY: index=0, S=3, vec.len()=4, so 0+3 <= 4
25/// let chunk: &[&str; 3] = unsafe { subarray_unchecked::<3, &str>(&vec, 0) };
26/// assert_eq!(chunk, &["a", "b", "c"]);
27/// ```
28pub const unsafe fn subarray_unchecked<const S: usize, T>(slice: &[T], index: usize) -> &[T; S] {
29 &*slice.as_ptr().add(index).cast::<[T; S]>()
30}