Skip to main content

non_empty_slice/
slice.rs

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