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