From 747933f99d5fcadbb16a1bb6d6a8ec9c11a4a4aa Mon Sep 17 00:00:00 2001 From: asquared31415 <34665709+asquared31415@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:57:19 +0000 Subject: [PATCH] add example for misaligned elements in subslice_range --- library/core/src/slice/mod.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 0677bb8f5871a..7caf8a8046dfd 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -5327,6 +5327,32 @@ impl [T] { /// assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); /// assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); /// ``` + /// Returning `None` with a slice not aligned to the elements of the base array: + /// ``` + /// use core::range::Range; + /// use core::slice::from_ref; + /// + /// let arr: &[[u8; 4]] = &[[0, 1, 2, 3], [4, 5, 6, 7]]; + /// let flattened: &[u8] = arr.as_flattened(); + /// + /// // This sub-slice is aligned with the first element of `arr`: + /// // &[[0, 1, 2, 3], [4, 5, 6, 7]] + /// // &[[0, 1, 2, 3]] + /// let aligned_elem: &[u8; 4] = flattened[0..4].try_into().unwrap(); + /// let aligned_slice: &[[u8; 4]] = from_ref(aligned_elem); + /// + /// // `aligned_slice` is `&arr[0..1]` + /// assert_eq!(arr.subslice_range(aligned_slice), Some(Range { start: 0, end: 1 })); + /// + /// // This sub-slice is **not** aligned to the elements of `arr`, despite pointing inside it: + /// // &[[0, 1, 2, 3], [4, 5, 6, 7]] + /// // &[[1, 2, 3, 4]] + /// let misaligned_elem: &[u8; 4] = flattened[1..5].try_into().unwrap(); + /// let misaligned_slice: &[[u8; 4]] = from_ref(misaligned_elem); + /// + /// // `misaligned_slice` has no corresponding slice of `arr` + /// assert_eq!(arr.subslice_range(misaligned_slice), None); + /// ``` #[must_use] #[stable(feature = "substr_range", since = "1.98.0")] pub fn subslice_range(&self, subslice: &[T]) -> Option> {