non_empty_slice/
slice.rs

1//! Non-empty [`[T]`](prim@slice).
2
3use core::{
4    array::TryFromSliceError,
5    mem::MaybeUninit,
6    ops::{Deref, DerefMut, Index, IndexMut, Range},
7    ptr,
8    slice::{Iter, IterMut, SliceIndex},
9};
10
11use non_empty_iter::{IntoNonEmptyIterator, NonEmptyAdapter};
12use non_zero_size::Size;
13use thiserror::Error;
14
15use crate::iter::{
16    ChunkBy, ChunkByMut, Chunks, ChunksExact, ChunksExactMut, ChunksMut, NonEmptyIter,
17    NonEmptyIterMut, RChunks, RChunksExact, RChunksExactMut, RChunksMut, Windows,
18};
19
20/// The error message used when the slice is empty.
21pub const EMPTY_SLICE: &str = "the slice is empty";
22
23/// Represents errors returned when received slices are empty.
24#[derive(Debug, Error)]
25#[error("{EMPTY_SLICE}")]
26#[cfg_attr(
27    feature = "diagnostics",
28    derive(miette::Diagnostic),
29    diagnostic(code(non_empty_slice::slice), help("make sure the slice is non-empty"))
30)]
31pub struct EmptySlice;
32
33/// Represents non-empty bytes, [`NonEmptySlice<u8>`].
34pub type NonEmptyBytes = NonEmptySlice<u8>;
35
36/// Represents non-empty slices.
37#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
38#[repr(transparent)]
39pub struct NonEmptySlice<T> {
40    inner: [T],
41}
42
43/// Represents non-empty slices of possibly uninitialized values, [`NonEmptySlice<MaybeUninit<T>>`].
44pub type NonEmptyMaybeUninitSlice<T> = NonEmptySlice<MaybeUninit<T>>;
45
46#[cfg(any(feature = "std", feature = "alloc"))]
47mod owned {
48    use crate::vec::NonEmptyVec;
49
50    #[cfg(all(not(feature = "std"), feature = "alloc"))]
51    use alloc::borrow::ToOwned;
52
53    use super::NonEmptySlice;
54
55    impl<T: Clone> ToOwned for NonEmptySlice<T> {
56        type Owned = NonEmptyVec<T>;
57
58        fn to_owned(&self) -> Self::Owned {
59            Self::Owned::from_non_empty_slice(self)
60        }
61    }
62}
63
64impl<'a, T> TryFrom<&'a [T]> for &'a NonEmptySlice<T> {
65    type Error = EmptySlice;
66
67    fn try_from(slice: &'a [T]) -> Result<Self, Self::Error> {
68        NonEmptySlice::try_from_slice(slice)
69    }
70}
71
72impl<'a, T> TryFrom<&'a mut [T]> for &'a mut NonEmptySlice<T> {
73    type Error = EmptySlice;
74
75    fn try_from(slice: &'a mut [T]) -> Result<Self, Self::Error> {
76        NonEmptySlice::try_from_mut_slice(slice)
77    }
78}
79
80impl<'a, T> From<&'a NonEmptySlice<T>> for &'a [T] {
81    fn from(slice: &'a NonEmptySlice<T>) -> Self {
82        slice.as_slice()
83    }
84}
85
86impl<'a, T> From<&'a mut NonEmptySlice<T>> for &'a mut [T] {
87    fn from(slice: &'a mut NonEmptySlice<T>) -> Self {
88        slice.as_mut_slice()
89    }
90}
91
92impl<T> AsRef<Self> for NonEmptySlice<T> {
93    fn as_ref(&self) -> &Self {
94        self
95    }
96}
97
98impl<T> AsRef<[T]> for NonEmptySlice<T> {
99    fn as_ref(&self) -> &[T] {
100        self.as_slice()
101    }
102}
103
104impl<T> AsMut<Self> for NonEmptySlice<T> {
105    fn as_mut(&mut self) -> &mut Self {
106        self
107    }
108}
109
110impl<T> AsMut<[T]> for NonEmptySlice<T> {
111    fn as_mut(&mut self) -> &mut [T] {
112        self.as_mut_slice()
113    }
114}
115
116impl<T> Deref for NonEmptySlice<T> {
117    type Target = [T];
118
119    fn deref(&self) -> &Self::Target {
120        self.as_slice()
121    }
122}
123
124impl<T> DerefMut for NonEmptySlice<T> {
125    fn deref_mut(&mut self) -> &mut Self::Target {
126        self.as_mut_slice()
127    }
128}
129
130impl<T, I: SliceIndex<[T]>> Index<I> for NonEmptySlice<T> {
131    type Output = I::Output;
132
133    fn index(&self, index: I) -> &Self::Output {
134        self.as_slice().index(index)
135    }
136}
137
138impl<T, I: SliceIndex<[T]>> IndexMut<I> for NonEmptySlice<T> {
139    fn index_mut(&mut self, index: I) -> &mut Self::Output {
140        self.as_mut_slice().index_mut(index)
141    }
142}
143
144impl<'a, T, const N: usize> TryFrom<&'a NonEmptySlice<T>> for &'a [T; N] {
145    type Error = TryFromSliceError;
146
147    fn try_from(non_empty: &'a NonEmptySlice<T>) -> Result<Self, Self::Error> {
148        non_empty.as_slice().try_into()
149    }
150}
151
152impl<'a, T, const N: usize> TryFrom<&'a mut NonEmptySlice<T>> for &'a mut [T; N] {
153    type Error = TryFromSliceError;
154
155    fn try_from(non_empty: &'a mut NonEmptySlice<T>) -> Result<Self, Self::Error> {
156        non_empty.as_mut_slice().try_into()
157    }
158}
159
160impl<T> NonEmptySlice<T> {
161    /// Constructs [`Self`] from anything that can be converted to slice, provided it is non-empty.
162    ///
163    /// Prefer [`try_from_slice`] if only [`[T]`](prim@slice) is used,
164    /// as this allows for `const` evaluation.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`EmptySlice`] if the slice is empty.
169    ///
170    /// [`try_from_slice`]: Self::try_from_slice
171    pub fn try_new<S: AsRef<[T]> + ?Sized>(slice: &S) -> Result<&Self, EmptySlice> {
172        Self::try_from_slice(slice.as_ref())
173    }
174
175    /// Constructs [`Self`] from anything that can be mutably converted to slice,
176    /// provided it is non-empty.
177    ///
178    /// Prefer [`try_from_mut_slice`] if only [`[T]`](prim@slice) is used,
179    /// as this allows for `const` evaluation.
180    ///
181    /// # Errors
182    ///
183    /// Returns [`EmptySlice`] if the slice is empty.
184    ///
185    /// [`try_from_mut_slice`]: Self::try_from_mut_slice
186    pub fn try_new_mut<S: AsMut<[T]> + ?Sized>(slice: &mut S) -> Result<&mut Self, EmptySlice> {
187        Self::try_from_mut_slice(slice.as_mut())
188    }
189
190    /// Similar to [`try_new`], but the error is discarded.
191    ///
192    /// Prefer [`from_slice`] if only [`[T]`](prim@slice) is used,
193    /// as it allows for `const` evaluation.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use non_empty_slice::NonEmptySlice;
199    ///
200    /// let array = [1, 2, 3];
201    ///
202    /// let non_empty = NonEmptySlice::new(&array).unwrap();
203    ///
204    /// // `NonEmptySlice<T>` is `AsRef<[T]>`, so it can also be used here!
205    /// let from_non_empty = NonEmptySlice::new(non_empty).unwrap();
206    /// ```
207    ///
208    /// [`try_new`]: Self::try_new
209    /// [`from_slice`]: Self::from_slice
210    pub fn new<S: AsRef<[T]> + ?Sized>(slice: &S) -> Option<&Self> {
211        Self::from_slice(slice.as_ref())
212    }
213
214    /// Similar to [`try_new_mut`], but the error is discarded.
215    ///
216    /// Prefer [`from_mut_slice`] if only [`[T]`](prim@slice) is used,
217    /// as it allows for `const` evaluation.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use non_empty_slice::NonEmptySlice;
223    ///
224    /// let mut array = [1, 2, 3];
225    ///
226    /// let non_empty = NonEmptySlice::new_mut(&mut array).unwrap();
227    ///
228    /// // `Slice<T>` is `AsMut<[T]>`, so it can also be used here!
229    /// let from_non_empty = NonEmptySlice::new_mut(non_empty).unwrap();
230    /// ```
231    ///
232    /// [`try_new_mut`]: Self::try_new_mut
233    /// [`from_mut_slice`]: Self::from_mut_slice
234    pub fn new_mut<S: AsMut<[T]> + ?Sized>(slice: &mut S) -> Option<&mut Self> {
235        Self::from_mut_slice(slice.as_mut())
236    }
237
238    /// Constructs [`Self`] from anything that can be converted to slice, without doing any checks.
239    ///
240    /// Prefer [`from_slice_unchecked`] if only [`[T]`](prim@slice) is used,
241    /// as this allows for `const` evaluation.
242    ///
243    /// # Safety
244    ///
245    /// The caller must ensure that the slice is non-empty.
246    ///
247    /// [`from_slice_unchecked`]: Self::from_slice_unchecked
248    #[must_use]
249    pub unsafe fn new_unchecked<S: AsRef<[T]> + ?Sized>(slice: &S) -> &Self {
250        // SAFETY: the caller must ensure that the slice is non-empty
251        unsafe { Self::from_slice_unchecked(slice.as_ref()) }
252    }
253
254    /// Constructs [`Self`] from anything that can be mutably converted to slice,
255    /// without doing any checks.
256    ///
257    /// Prefer [`from_mut_slice_unchecked`] if only [`[T]`](prim@slice) is used,
258    /// as this allows for `const` evaluation.
259    ///
260    /// # Safety
261    ///
262    /// The caller must ensure that the slice is non-empty.
263    ///
264    /// [`from_mut_slice_unchecked`]: Self::from_mut_slice_unchecked
265    #[must_use]
266    pub unsafe fn new_unchecked_mut<S: AsMut<[T]> + ?Sized>(slice: &mut S) -> &mut Self {
267        // SAFETY: the caller must ensure that the slice is non-empty
268        unsafe { Self::from_mut_slice_unchecked(slice.as_mut()) }
269    }
270
271    /// Constructs [`Self`] from [`[T]`](prim@slice), provided the slice is non-empty.
272    ///
273    /// # Errors
274    ///
275    /// Returns [`EmptySlice`] if the slice is empty.
276    pub const fn try_from_slice(slice: &[T]) -> Result<&Self, EmptySlice> {
277        if slice.is_empty() {
278            return Err(EmptySlice);
279        }
280
281        // SAFETY: the slice is non-empty at this point
282        Ok(unsafe { Self::from_slice_unchecked(slice) })
283    }
284
285    /// Constructs [`Self`] from mutable [`[T]`](prim@slice), provided the slice is non-empty.
286    ///
287    /// # Errors
288    ///
289    /// Returns [`EmptySlice`] if the slice is empty.
290    pub const fn try_from_mut_slice(slice: &mut [T]) -> Result<&mut Self, EmptySlice> {
291        if slice.is_empty() {
292            return Err(EmptySlice);
293        }
294
295        // SAFETY: the slice is non-empty at this point
296        Ok(unsafe { Self::from_mut_slice_unchecked(slice) })
297    }
298
299    /// Similar to [`try_from_slice`], but the error is discarded.
300    ///
301    /// # Examples
302    ///
303    /// Basic snippet:
304    ///
305    /// ```
306    /// use non_empty_slice::NonEmptySlice;
307    ///
308    /// let array = [1, 2, 3];
309    ///
310    /// let non_empty = NonEmptySlice::from_slice(&array).unwrap();
311    /// ```
312    ///
313    /// [`None`] is returned if the slice is empty, therefore the following snippet panics:
314    ///
315    /// ```should_panic
316    /// use non_empty_slice::NonEmptyBytes;
317    ///
318    /// let empty = [];
319    ///
320    /// let never = NonEmptyBytes::from_slice(&empty).unwrap();
321    /// ```
322    ///
323    /// [`try_from_slice`]: Self::try_from_slice
324    pub const fn from_slice(slice: &[T]) -> Option<&Self> {
325        if slice.is_empty() {
326            return None;
327        }
328
329        // SAFETY: the slice is non-empty at this point
330        Some(unsafe { Self::from_slice_unchecked(slice) })
331    }
332
333    /// Similar to [`try_from_mut_slice`], but the error is discarded.
334    ///
335    /// # Examples
336    ///
337    /// Basic snippet:
338    ///
339    /// ```
340    /// use non_empty_slice::NonEmptySlice;
341    ///
342    /// let mut array = [1, 2, 3];
343    ///
344    /// let non_empty = NonEmptySlice::from_mut_slice(&mut array).unwrap();
345    /// ```
346    ///
347    /// [`None`] is returned if the slice is empty, therefore the following snippet panics:
348    ///
349    /// ```should_panic
350    /// use non_empty_slice::NonEmptyBytes;
351    ///
352    /// let mut empty = [];
353    ///
354    /// let never = NonEmptyBytes::from_mut_slice(&mut empty).unwrap();
355    /// ```
356    ///
357    /// [`try_from_mut_slice`]: Self::try_from_mut_slice
358    pub const fn from_mut_slice(slice: &mut [T]) -> Option<&mut Self> {
359        if slice.is_empty() {
360            return None;
361        }
362
363        // SAFETY: the slice is non-empty at this point
364        Some(unsafe { Self::from_mut_slice_unchecked(slice) })
365    }
366
367    /// Constructs [`Self`] from immutable [`[T]`](prim@slice),
368    /// without checking if the slice is empty.
369    ///
370    /// # Safety
371    ///
372    /// The caller must ensure that the slice is non-empty.
373    #[must_use]
374    pub const unsafe fn from_slice_unchecked(slice: &[T]) -> &Self {
375        debug_assert!(!slice.is_empty());
376
377        // SAFETY: the caller must ensure that the slice is non-empty
378        // `Slice` is `repr(transparent)`, so it is safe to transmute
379        unsafe { &*(ptr::from_ref(slice) as *const Self) }
380    }
381
382    /// Constructs [`Self`] from mutable [`[T]`](prim@slice),
383    /// without checking if the slice is empty.
384    ///
385    /// # Safety
386    ///
387    /// The caller must ensure that the slice is non-empty.
388    #[must_use]
389    pub const unsafe fn from_mut_slice_unchecked(slice: &mut [T]) -> &mut Self {
390        debug_assert!(!slice.is_empty());
391
392        // SAFETY: the caller must ensure that the slice is non-empty
393        // `Slice` is `repr(transparent)`, so it is safe to transmute
394        unsafe { &mut *(ptr::from_mut(slice) as *mut Self) }
395    }
396
397    #[cfg(feature = "unsafe-assert")]
398    const fn assert_non_empty(&self) {
399        use core::hint::assert_unchecked;
400
401        // SAFETY: the slice is non-empty by construction
402        unsafe {
403            assert_unchecked(!self.inner.is_empty());
404        }
405    }
406
407    /// Returns the contained slice.
408    ///
409    /// # Examples
410    ///
411    /// ```
412    /// use non_empty_slice::NonEmptyBytes;
413    ///
414    /// let nekit = b"nekit";
415    ///
416    /// let non_empty = NonEmptyBytes::from_slice(nekit).unwrap();
417    ///
418    /// assert_eq!(non_empty.as_slice(), nekit);
419    /// ```
420    #[must_use]
421    pub const fn as_slice(&self) -> &[T] {
422        #[cfg(feature = "unsafe-assert")]
423        self.assert_non_empty();
424
425        &self.inner
426    }
427
428    /// Returns the contained mutable slice.
429    #[must_use]
430    pub const fn as_mut_slice(&mut self) -> &mut [T] {
431        #[cfg(feature = "unsafe-assert")]
432        self.assert_non_empty();
433
434        &mut self.inner
435    }
436
437    /// Checks if the slice is empty. Always returns [`false`].
438    ///
439    /// This method is marked as deprecated since the slice is never empty.
440    #[deprecated = "this slice is never empty"]
441    pub const fn is_empty(&self) -> bool {
442        false
443    }
444
445    /// Returns the length of the slice as [`Size`].
446    pub const fn len(&self) -> Size {
447        let len = self.as_slice().len();
448
449        // SAFETY: the slice is non-empty by construction,
450        // therefore its length is guaranteed to be non-zero
451        unsafe { Size::new_unchecked(len) }
452    }
453
454    /// Returns regular by-reference iterator over the slice.
455    pub fn iter(&self) -> Iter<'_, T> {
456        self.as_slice().iter()
457    }
458
459    /// Returns regular by-mutable-reference iterator over the mutable slice.
460    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
461        self.as_mut_slice().iter_mut()
462    }
463
464    /// Returns non-empty by-reference iterator over the slice.
465    pub fn non_empty_iter(&self) -> NonEmptyIter<'_, T> {
466        // SAFETY: the slice is non-empty by construction, so is the underlying iterator
467        unsafe { NonEmptyAdapter::new(self.iter()) }
468    }
469
470    /// Returns non-empty by-mutable-reference iterator over the mutable slice.
471    pub fn non_empty_iter_mut(&mut self) -> NonEmptyIterMut<'_, T> {
472        // SAFETY: the slice is non-empty by construction, so is the underlying iterator
473        unsafe { NonEmptyAdapter::new(self.iter_mut()) }
474    }
475
476    /// Returns the first item of the slice.
477    ///
478    /// Since the slice is guaranteed to be non-empty, this method always returns some value.
479    pub const fn first(&self) -> &T {
480        let option = self.as_slice().first();
481
482        // SAFETY: the slice is non-empty by construction, so there is always some first value
483        unsafe { option.unwrap_unchecked() }
484    }
485
486    /// Returns the first mutable item of the mutable slice.
487    ///
488    /// Since the slice is guaranteed to be non-empty, this method always returns some value.
489    pub const fn first_mut(&mut self) -> &mut T {
490        let option = self.as_mut_slice().first_mut();
491
492        // SAFETY: the slice is non-empty by construction, so there is always some first value
493        unsafe { option.unwrap_unchecked() }
494    }
495
496    /// Returns the last item of the slice.
497    ///
498    /// Since the slice is guaranteed to be non-empty, this method always returns some value.
499    pub const fn last(&self) -> &T {
500        let option = self.as_slice().last();
501
502        // SAFETY: the slice is non-empty by construction, so there is always some last value
503        unsafe { option.unwrap_unchecked() }
504    }
505
506    /// Returns the last mutable item of the mutable slice.
507    ///
508    /// Since the slice is guaranteed to be non-empty, this method always returns some value.
509    pub const fn last_mut(&mut self) -> &mut T {
510        let option = self.as_mut_slice().last_mut();
511
512        // SAFETY: the slice is non-empty by construction, so there is always some last value
513        unsafe { option.unwrap_unchecked() }
514    }
515
516    /// Returns the first and all the rest of the items in the slice.
517    pub const fn split_first(&self) -> (&T, &[T]) {
518        let option = self.as_slice().split_first();
519
520        // SAFETY: the slice is non-empty by construction, so there is always some first value
521        unsafe { option.unwrap_unchecked() }
522    }
523
524    /// Returns the first mutable item and all the rest of the items in the mutable slice.
525    pub const fn split_first_mut(&mut self) -> (&mut T, &mut [T]) {
526        let option = self.as_mut_slice().split_first_mut();
527
528        // SAFETY: the slice is non-empty by construction, so there is always some first value
529        unsafe { option.unwrap_unchecked() }
530    }
531
532    /// Returns the last and all the rest of the items in the slice.
533    pub const fn split_last(&self) -> (&T, &[T]) {
534        let option = self.as_slice().split_last();
535
536        // SAFETY: the slice is non-empty by construction, so there is always some last value
537        unsafe { option.unwrap_unchecked() }
538    }
539
540    /// Returns the last mutable item and all the rest of the items in the mutable slice.
541    pub const fn split_last_mut(&mut self) -> (&mut T, &mut [T]) {
542        let option = self.as_mut_slice().split_last_mut();
543
544        // SAFETY: the slice is non-empty by construction, so there is always some last value
545        unsafe { option.unwrap_unchecked() }
546    }
547
548    /// Returns the first `N` items of the slice as [`[T; N]`](prim@array).
549    ///
550    /// If there are less than `N` items, [`None`] is returned.
551    pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]> {
552        self.as_slice().first_chunk()
553    }
554
555    /// Returns the first mutable `N` items of the mutable slice as [`[T; N]`](prim@array).
556    ///
557    /// If there are less than `N` items, [`None`] is returned.
558    pub const fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
559        self.as_mut_slice().first_chunk_mut()
560    }
561
562    /// Returns the first `N` items of the slice as [`[T; N]`](prim@array)
563    /// and all the rest of the items.
564    ///
565    /// If there are less than `N` items, [`None`] is returned.
566    pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])> {
567        self.as_slice().split_first_chunk()
568    }
569
570    /// Returns the first mutable `N` items of the mutable slice as [`[T; N]`](prim@array)
571    /// and all the rest of the items.
572    ///
573    /// If there are less than `N` items, [`None`] is returned.
574    pub const fn split_first_chunk_mut<const N: usize>(
575        &mut self,
576    ) -> Option<(&mut [T; N], &mut [T])> {
577        self.as_mut_slice().split_first_chunk_mut()
578    }
579
580    /// Returns the last `N` items of the slice as [`[T; N]`](prim@array).
581    ///
582    /// If there are less than `N` items, [`None`] is returned.
583    pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]> {
584        self.as_slice().last_chunk()
585    }
586
587    /// Returns the last mutable `N` items of the mutable slice as [`[T; N]`](prim@array).
588    ///
589    /// If there are less than `N` items, [`None`] is returned.
590    pub const fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]> {
591        self.as_mut_slice().last_chunk_mut()
592    }
593
594    /// Returns the last `N` items of the slice as [`[T; N]`](prim@array)
595    /// and all the rest of the items.
596    ///
597    /// If there are less than `N` items, [`None`] is returned.
598    pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])> {
599        self.as_slice().split_last_chunk()
600    }
601
602    /// Returns the last mutable `N` items of the mutable slice as [`[T; N]`](prim@array)
603    /// and all the rest of the items.
604    ///
605    /// If there are less than `N` items, [`None`] is returned.
606    pub const fn split_last_chunk_mut<const N: usize>(
607        &mut self,
608    ) -> Option<(&mut [T], &mut [T; N])> {
609        self.as_mut_slice().split_last_chunk_mut()
610    }
611
612    /// Returns the raw pointer to the slice.
613    pub const fn as_ptr(&self) -> *const T {
614        self.as_slice().as_ptr()
615    }
616
617    /// Returns the raw mutable pointer to the mutable slice.
618    pub const fn as_mut_ptr(&mut self) -> *mut T {
619        self.as_mut_slice().as_mut_ptr()
620    }
621
622    /// Returns the two raw pointers spanning the slice.
623    ///
624    /// The end pointer is one element past the end of the slice.
625    pub const fn as_ptr_range(&self) -> Range<*const T> {
626        self.as_slice().as_ptr_range()
627    }
628
629    /// Returns the two raw mutable pointers spanning the mutable slice.
630    ///
631    /// The end pointer is one element past the end of the slice.
632    pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
633        self.as_mut_slice().as_mut_ptr_range()
634    }
635
636    /// Reinterprets the slice as [`[T; N]`](prim@array).
637    ///
638    /// If the length is not equal to `N`, [`None`] is returned.
639    pub const fn as_array<const N: usize>(&self) -> Option<&[T; N]> {
640        if self.len().get() == N {
641            let ptr = self.as_ptr().cast();
642
643            // SAFETY: length is equal to `N`, so we can reinterpret this
644            let this = unsafe { &*ptr };
645
646            Some(this)
647        } else {
648            None
649        }
650    }
651
652    /// Reinterprets the mutable slice as [`[T; N]`](prim@array).
653    ///
654    /// If the length is not equal to `N`, [`None`] is returned.
655    pub const fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]> {
656        if self.len().get() == N {
657            let ptr = self.as_mut_ptr().cast();
658
659            // SAFETY: length is equal to `N`, so we can reinterpret this
660            let this = unsafe { &mut *ptr };
661
662            Some(this)
663        } else {
664            None
665        }
666    }
667
668    /// Swaps two items in the slice.
669    ///
670    /// # Panics
671    ///
672    /// Panics if `first` or `other` are out of bounds.
673    pub const fn swap(&mut self, first: usize, other: usize) {
674        self.as_mut_slice().swap(first, other);
675    }
676
677    /// Reverses the slice in place.
678    pub const fn reverse(&mut self) {
679        self.as_mut_slice().reverse();
680    }
681
682    /// Returns non-empty iterator over the slice in (non-overlapping) non-empty chunks
683    /// of given [`Size`], starting at the beginning of the slice.
684    pub const fn chunks(&self, size: Size) -> Chunks<'_, T> {
685        Chunks::new(self, size)
686    }
687
688    /// Returns non-empty iterator over the slice in (non-overlapping) non-empty mutable chunks
689    /// of given [`Size`], starting at the beginning of the slice.
690    pub const fn chunks_mut(&mut self, size: Size) -> ChunksMut<'_, T> {
691        ChunksMut::new(self, size)
692    }
693
694    /// Returns non-empty iterator over the slice in (non-overlapping) non-empty chunks
695    /// of given [`Size`], starting at the end of the slice.
696    pub const fn rchunks(&self, size: Size) -> RChunks<'_, T> {
697        RChunks::new(self, size)
698    }
699
700    /// Returns non-empty iterator over the slice in (non-overlapping) non-empty mutable chunks
701    /// of given [`Size`], starting at the end of the slice.
702    pub const fn rchunks_mut(&mut self, size: Size) -> RChunksMut<'_, T> {
703        RChunksMut::new(self, size)
704    }
705
706    /// Returns non-empty iterator over the slice in (non-overlapping) chunks
707    /// of given [`Size`], starting at the beginning of the slice.
708    ///
709    /// When the length of the slice is not divisible by the chunk size,
710    /// the last chunk will be omitted.
711    pub const fn chunks_exact(&self, size: Size) -> ChunksExact<'_, T> {
712        ChunksExact::new(self, size)
713    }
714
715    /// Returns non-empty iterator over the slice in (non-overlapping) mutable chunks
716    /// of given [`Size`], starting at the beginning of the slice.
717    ///
718    /// When the length of the slice is not divisible by the chunk size,
719    /// the last chunk will be omitted.
720    pub const fn chunks_exact_mut(&mut self, size: Size) -> ChunksExactMut<'_, T> {
721        ChunksExactMut::new(self, size)
722    }
723
724    /// Returns non-empty iterator over the slice in (non-overlapping) chunks
725    /// of given [`Size`], starting at the end of the slice.
726    ///
727    /// When the length of the slice is not divisible by the chunk size,
728    /// the last chunk will be omitted.
729    pub const fn rchunks_exact(&self, size: Size) -> RChunksExact<'_, T> {
730        RChunksExact::new(self, size)
731    }
732
733    /// Returns non-empty iterator over the slice in (non-overlapping) mutable chunks
734    /// of given [`Size`], starting at the end of the slice.
735    ///
736    /// When the length of the slice is not divisible by the chunk size,
737    /// the last chunk will be omitted.
738    pub const fn rchunks_exact_mut(&mut self, size: Size) -> RChunksExactMut<'_, T> {
739        RChunksExactMut::new(self, size)
740    }
741
742    /// Returns non-empty iterator over the slice in (overlapping) windows of given [`Size`].
743    pub const fn windows(&self, size: Size) -> Windows<'_, T> {
744        Windows::new(self, size)
745    }
746
747    /// Returns non-empty iterator over the slice in (non-overlapping) chunks,
748    /// separated by the given predicate.
749    pub const fn chunk_by<P: FnMut(&T, &T) -> bool>(&self, predicate: P) -> ChunkBy<'_, T, P> {
750        ChunkBy::new(self, predicate)
751    }
752
753    /// Returns non-empty iterator over the slice in (non-overlapping) mutable chunks,
754    /// separated by the given predicate.
755    pub const fn chunk_by_mut<P: FnMut(&T, &T) -> bool>(
756        &mut self,
757        predicate: P,
758    ) -> ChunkByMut<'_, T, P> {
759        ChunkByMut::new(self, predicate)
760    }
761
762    /// Splits the slice into chunks of `N` items, starting at the beginning of the slice,
763    /// returning the remainder as another slice.
764    ///
765    /// # Panics
766    ///
767    /// Panics if `N` is zero.
768    pub const fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T]) {
769        self.as_slice().as_chunks()
770    }
771
772    /// Splits the slice into mutable chunks of `N` items, starting at the beginning of the slice,
773    /// returning the remainder as another mutable slice.
774    ///
775    /// # Panics
776    ///
777    /// Panics if `N` is zero.
778    pub const fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T]) {
779        self.as_mut_slice().as_chunks_mut()
780    }
781
782    /// Splits the slice into chunks of `N` items, assuming there is no remainder.
783    ///
784    /// # Safety
785    ///
786    /// The caller must ensure that the length of the slice is divisible by `N` (and `N != 0`).
787    pub const unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]] {
788        // SAFETY: the caller must ensure that the length of the slice is divisible by `N`
789        // and that `N` is non-zero
790        unsafe { self.as_slice().as_chunks_unchecked() }
791    }
792
793    /// Splits the slice into mutable chunks of `N` items, assuming there is no remainder.
794    ///
795    /// # Safety
796    ///
797    /// The caller must ensure that the length of the slice is divisible by `N`.
798    pub const unsafe fn as_chunks_unchecked_mut<const N: usize>(&mut self) -> &mut [[T; N]] {
799        // SAFETY: the caller must ensure that the length of the slice is divisible by `N`
800        // and that `N` is non-zero
801        unsafe { self.as_mut_slice().as_chunks_unchecked_mut() }
802    }
803
804    /// Splits the slice into chunks of `N` items, starting at the end of the slice,
805    /// returning the remainder as another slice.
806    ///
807    /// # Panics
808    ///
809    /// Panics if `N` is zero.
810    pub const fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]]) {
811        self.as_slice().as_rchunks()
812    }
813
814    /// Splits the mutable slice into mutable chunks of `N` items, starting at the end of the slice,
815    /// returning the remainder as another mutable slice.
816    ///
817    /// # Panics
818    ///
819    /// Panics if `N` is zero.
820    pub const fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]]) {
821        self.as_mut_slice().as_rchunks_mut()
822    }
823
824    /// Splits the slice into two at the given non-zero index.
825    ///
826    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
827    ///
828    /// # Panics
829    ///
830    /// Panics if the index is out of bounds.
831    pub const fn split_at(&self, index: Size) -> (&Self, &[T]) {
832        let (left, right) = self.as_slice().split_at(index.get());
833
834        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
835        let left_non_empty = unsafe { Self::from_slice_unchecked(left) };
836
837        (left_non_empty, right)
838    }
839
840    /// Splits the mutable slice into two at the given non-zero index.
841    ///
842    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
843    ///
844    /// # Panics
845    ///
846    /// Panics if the index is out of bounds.
847    pub const fn split_at_mut(&mut self, index: Size) -> (&mut Self, &mut [T]) {
848        let (left, right) = self.as_mut_slice().split_at_mut(index.get());
849
850        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
851        let left_non_empty = unsafe { Self::from_mut_slice_unchecked(left) };
852
853        (left_non_empty, right)
854    }
855
856    /// Splits the slice into two at the given non-zero index, without doing any bounds checks.
857    ///
858    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
859    ///
860    /// # Safety
861    ///
862    /// The caller must ensure that the index is in bounds.
863    pub const unsafe fn split_at_unchecked(&self, index: Size) -> (&Self, &[T]) {
864        // SAFETY: the caller must ensure the index is in bounds
865        let (left, right) = unsafe { self.as_slice().split_at_unchecked(index.get()) };
866
867        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
868        let left_non_empty = unsafe { Self::from_slice_unchecked(left) };
869
870        (left_non_empty, right)
871    }
872
873    /// Splits the mutable slice into two at the given non-zero index,
874    /// without doing any bounds checks.
875    ///
876    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
877    ///
878    /// # Safety
879    ///
880    /// The caller must ensure that the index is in bounds.
881    pub const unsafe fn split_at_mut_unchecked(&mut self, index: Size) -> (&mut Self, &mut [T]) {
882        // SAFETY: the caller must ensure the index is in bounds
883        let (left, right) = unsafe { self.as_mut_slice().split_at_mut_unchecked(index.get()) };
884
885        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
886        let left_non_empty = unsafe { Self::from_mut_slice_unchecked(left) };
887
888        (left_non_empty, right)
889    }
890
891    /// Splits the slice into two at the given non-zero index, returning [`None`] if out of bounds.
892    ///
893    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
894    pub const fn split_at_checked(&self, index: Size) -> Option<(&Self, &[T])> {
895        let Some((left, right)) = self.as_slice().split_at_checked(index.get()) else {
896            return None;
897        };
898
899        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
900        let left_non_empty = unsafe { Self::from_slice_unchecked(left) };
901
902        Some((left_non_empty, right))
903    }
904
905    /// Splits the mutable slice into two at the given non-zero index,
906    /// returning [`None`] if out of bounds.
907    ///
908    /// The index has to be non-zero in order to guarantee non-emptiness of the left slice.
909    pub const fn split_at_mut_checked(&mut self, index: Size) -> Option<(&mut Self, &mut [T])> {
910        let Some((left, right)) = self.as_mut_slice().split_at_mut_checked(index.get()) else {
911            return None;
912        };
913
914        // SAFETY: splitting non-empty slice at non-zero index yields non-empty left slice
915        let left_non_empty = unsafe { Self::from_mut_slice_unchecked(left) };
916
917        Some((left_non_empty, right))
918    }
919
920    // NOTE: other methods are available via deref coercion to `[T]`
921}
922
923impl<T: Clone> NonEmptySlice<T> {
924    /// Clones all items from another non-empty slice into this one.
925    ///
926    /// # Panics
927    ///
928    /// Panics if the slices have different lengths.
929    pub fn clone_from_non_empty_slice(&mut self, other: &Self) {
930        self.as_mut_slice().clone_from_slice(other.as_slice());
931    }
932}
933
934type Bytes = [u8];
935
936impl NonEmptyBytes {
937    /// Checks if all bytes in the slice are within the ASCII range.
938    #[must_use]
939    pub const fn is_ascii(&self) -> bool {
940        self.as_slice().is_ascii()
941    }
942
943    /// Checks that the two slices are ASCII case-insensitively equal.
944    #[must_use]
945    pub const fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
946        self.as_slice().eq_ignore_ascii_case(other.as_slice())
947    }
948
949    /// Converts the slice to its ASCII uppercase equivalent in-place.
950    pub const fn make_ascii_uppercase(&mut self) {
951        self.as_mut_slice().make_ascii_uppercase();
952    }
953
954    /// Converts the slice to its ASCII lowercase equivalent in-place.
955    pub const fn make_ascii_lowercase(&mut self) {
956        self.as_mut_slice().make_ascii_lowercase();
957    }
958
959    /// Returns new slice with leading ASCII whitespace bytes removed.
960    #[must_use]
961    pub const fn trim_ascii_start(&self) -> &Bytes {
962        self.as_slice().trim_ascii_start()
963    }
964
965    /// Returns new slice with trailing ASCII whitespace bytes removed.
966    #[must_use]
967    pub const fn trim_ascii_end(&self) -> &Bytes {
968        self.as_slice().trim_ascii_end()
969    }
970
971    /// Returns new slice with leading and trailing ASCII whitespace bytes removed.
972    #[must_use]
973    pub const fn trim_ascii(&self) -> &Bytes {
974        self.as_slice().trim_ascii()
975    }
976}
977
978impl<'a, T> IntoIterator for &'a NonEmptySlice<T> {
979    type Item = &'a T;
980
981    type IntoIter = Iter<'a, T>;
982
983    fn into_iter(self) -> Self::IntoIter {
984        self.iter()
985    }
986}
987
988impl<'a, T> IntoIterator for &'a mut NonEmptySlice<T> {
989    type Item = &'a mut T;
990
991    type IntoIter = IterMut<'a, T>;
992
993    fn into_iter(self) -> Self::IntoIter {
994        self.iter_mut()
995    }
996}
997
998impl<'a, T> IntoNonEmptyIterator for &'a NonEmptySlice<T> {
999    type IntoNonEmptyIter = NonEmptyIter<'a, T>;
1000
1001    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
1002        self.non_empty_iter()
1003    }
1004}
1005
1006impl<'a, T> IntoNonEmptyIterator for &'a mut NonEmptySlice<T> {
1007    type IntoNonEmptyIter = NonEmptyIterMut<'a, T>;
1008
1009    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
1010        self.non_empty_iter_mut()
1011    }
1012}