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