Skip to main content

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/// In debug builds, this precondition is checked with a `debug_assert!`.
10///
11/// # Examples
12///
13/// ```
14/// use ps_util::subarray_unchecked;
15/// let data = [1, 2, 3, 4, 5];
16/// // SAFETY: index=1, S=2, slice.len()=5, so 1+2 <= 5
17/// let chunk: &[i32; 2] = unsafe { subarray_unchecked::<2, i32>(&data, 1) };
18/// assert_eq!(chunk, &[2, 3]);
19/// ```
20///
21/// Works with vectors:
22///
23/// ```
24/// use ps_util::subarray_unchecked;
25/// let vec = vec!["a", "b", "c", "d"];
26/// // SAFETY: index=0, S=3, vec.len()=4, so 0+3 <= 4
27/// let chunk: &[&str; 3] = unsafe { subarray_unchecked::<3, &str>(&vec, 0) };
28/// assert_eq!(chunk, &["a", "b", "c"]);
29/// ```
30pub const unsafe fn subarray_unchecked<const S: usize, T>(slice: &[T], index: usize) -> &[T; S] {
31    debug_assert!(S <= slice.len() && index <= slice.len() - S);
32
33    &*slice.as_ptr().add(index).cast::<[T; S]>()
34}