From 00fd59405a77332c67942b65d113c6c8a3d3e3df Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Mon, 2 Feb 2026 22:22:15 -0700 Subject: [PATCH] Add `SliceExt` Adds an extension trait for `[T]` which adds a set of parallel `as_hybrid_*` methods for the core `as_*_array`. These are wrappers for `Array::slice_as*` but avoid notating `Array` --- src/traits.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/traits.rs b/src/traits.rs index d22a30e..7c9f183 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -145,3 +145,55 @@ where self.into() } } + +/// Extension trait for `[T]` providing methods for working with [`Array`]. +pub trait SliceExt: sealed::Sealed { + /// Get a reference to an array from a slice, if the slice is exactly the size of the array. + /// + /// Returns `None` if the slice's length is not exactly equal to the array size. + fn as_hybrid_array(&self) -> Option<&Array>; + + /// Get a mutable reference to an array from a slice, if the slice is exactly the size of the + /// array. + /// + /// Returns `None` if the slice's length is not exactly equal to the array size. + fn as_mut_hybrid_array(&mut self) -> Option<&mut Array>; + + /// Splits the shared slice into a slice of `U`-element arrays, starting at the beginning + /// of the slice, and a remainder slice with length strictly less than `U`. + /// + /// # Panics + /// If `U` is 0. + fn as_hybrid_chunks(&self) -> (&[Array], &[T]); + + /// Splits the exclusive slice into a slice of `U`-element arrays, starting at the beginning + /// of the slice, and a remainder slice with length strictly less than `U`. + /// + /// # Panics + /// If `U` is 0. + fn as_hybrid_chunks_mut(&mut self) -> (&mut [Array], &mut [T]); +} + +impl SliceExt for [T] { + fn as_hybrid_array(&self) -> Option<&Array> { + Array::slice_as_array(self) + } + + fn as_mut_hybrid_array(&mut self) -> Option<&mut Array> { + Array::slice_as_mut_array(self) + } + + fn as_hybrid_chunks(&self) -> (&[Array], &[T]) { + Array::slice_as_chunks(self) + } + + fn as_hybrid_chunks_mut(&mut self) -> (&mut [Array], &mut [T]) { + Array::slice_as_chunks_mut(self) + } +} + +impl sealed::Sealed for [T] {} + +mod sealed { + pub trait Sealed {} +}