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