not_empty/
slice.rs

1//! A dynamically-sized view into a contiguous sequence, `[T]`, that is not
2//! empty.
3//!
4//! See also the [`NonEmptySlice<T>`] type.
5
6use crate::EmptyError;
7#[cfg(any(feature = "alloc", feature = "std"))]
8use crate::{alloc::*, NonEmptyVec};
9
10use core::{
11    array::TryFromSliceError,
12    cmp::Ordering,
13    convert::{TryFrom, TryInto},
14    fmt,
15    hash::{Hash, Hasher},
16    hint,
17    num::NonZeroUsize,
18    ops,
19    slice::{self, SliceIndex},
20};
21
22/// A slice that is guaranteed to not be empty.
23///
24/// The layout of a [`NonEmptySlice<T>`] is idential to [`[T]`](prim@slice).
25/// However, many methods have been overridden or optimized to reflect that the
26/// slice's length can never be zero.
27#[repr(transparent)]
28pub struct NonEmptySlice<T> {
29    pub(crate) inner: [T],
30}
31
32impl<T> NonEmptySlice<T> {
33    ////////////////////////////////////////////////////////////////////////////
34    // Constructors
35    ////////////////////////////////////////////////////////////////////////////
36
37    /// Converts [`&[T]`](prim@slice) to [`&NonEmptySlice<T>`](Self) without
38    /// checking if the given slice is not empty.
39    ///
40    /// This is a cost-free conversion.
41    ///
42    /// # Safety
43    ///
44    /// The slice must not be empty.
45    ///
46    /// # Examples
47    ///
48    /// Basic usage:
49    ///
50    /// ```
51    /// use not_empty::NonEmptySlice;
52    ///
53    /// let slice = &[1, 2, 3];
54    /// let nonempty: &NonEmptySlice<_> = unsafe { NonEmptySlice::new_unchecked(slice) };
55    /// ```
56    #[inline]
57    #[track_caller]
58    pub const unsafe fn new_unchecked(slice: &[T]) -> &NonEmptySlice<T> {
59        debug_assert!(
60            !slice.is_empty(),
61            "non-empty slice initialized with an empty slice"
62        );
63        &*(slice as *const [T] as *const NonEmptySlice<T>)
64    }
65
66    /// Creates a non-empty slice if the given slice is not empty.
67    ///
68    /// # Errors
69    ///
70    /// Returns an [`EmptyError`] if the given slice is empty.
71    ///
72    /// # Examples
73    ///
74    /// Basic usage:
75    ///
76    /// ```
77    /// use not_empty::NonEmptySlice;
78    ///
79    /// # fn main() -> Result<(), not_empty::EmptyError> {
80    /// let slice = &[1, 2, 3];
81    /// let nonempty: &NonEmptySlice<_> = NonEmptySlice::new(slice)?;
82    /// assert!(nonempty.len().get() == 3);
83    ///
84    /// let empty: &[i32] = &[];
85    /// assert!(NonEmptySlice::new(empty).is_err());
86    /// # Ok(())
87    /// # }
88    /// ```
89    #[inline]
90    pub const fn new(slice: &[T]) -> Result<&NonEmptySlice<T>, EmptyError> {
91        if slice.is_empty() {
92            Err(EmptyError)
93        } else {
94            Ok(unsafe { NonEmptySlice::new_unchecked(slice) })
95        }
96    }
97
98    /// Converts [`&mut [T]`](prim@slice) to [`&mut NonEmptySlice<T>`](Self)
99    /// without checking if the given mutable slice is not empty.
100    ///
101    /// This is a cost-free conversion.
102    ///
103    /// # Safety
104    ///
105    /// The mutable slice must not be empty.
106    ///
107    /// # Examples
108    ///
109    /// Basic usage:
110    ///
111    /// ```
112    /// use not_empty::NonEmptySlice;
113    ///
114    /// let slice = &mut [1, 2, 3];
115    /// let nonempty: &mut NonEmptySlice<_> = unsafe { NonEmptySlice::new_mut_unchecked(slice) };
116    /// ```
117    #[must_use]
118    #[inline]
119    pub unsafe fn new_mut_unchecked(slice: &mut [T]) -> &mut NonEmptySlice<T> {
120        debug_assert!(
121            !slice.is_empty(),
122            "mutable non-empty slice initialized with an empty mutable slice"
123        );
124        &mut *(slice as *mut [T] as *mut NonEmptySlice<T>)
125    }
126
127    /// Creates a non-empty mutable slice if the given mutable slice is not
128    /// empty.
129    ///
130    /// # Errors
131    ///
132    /// Returns an [`EmptyError`] if the given mutable slice is empty.
133    ///
134    /// # Examples
135    ///
136    /// Basic usage:
137    ///
138    /// ```
139    /// use not_empty::NonEmptySlice;
140    ///
141    /// # fn main() -> Result<(), not_empty::EmptyError> {
142    /// let slice = &mut [1, 2, 3];
143    /// let nonempty: &mut NonEmptySlice<_> = NonEmptySlice::new_mut(slice)?;
144    /// assert!(nonempty.len().get() == 3);
145    ///
146    /// let empty: &mut [i32] = &mut [];
147    /// assert!(NonEmptySlice::new_mut(empty).is_err());
148    /// # Ok(())
149    /// # }
150    /// ```
151    #[inline]
152    pub fn new_mut(slice: &mut [T]) -> Result<&mut NonEmptySlice<T>, EmptyError> {
153        (!slice.is_empty())
154            .then(|| unsafe { NonEmptySlice::new_mut_unchecked(slice) })
155            .ok_or(EmptyError)
156    }
157
158    ////////////////////////////////////////////////////////////////////////////
159    // `not_empty` overrides to slice
160    ////////////////////////////////////////////////////////////////////////////
161
162    /// Returns the number of elements in the slice.
163    ///
164    /// Unlike [`slice::len`], this returns a [`NonZeroUsize`] instead of a
165    /// [`usize`].
166    ///
167    /// # Examples
168    ///
169    /// Basic usage:
170    ///
171    /// ```
172    /// use core::num::NonZeroUsize;
173    /// use not_empty::NonEmptySlice;
174    ///
175    /// # fn main() -> Result<(), not_empty::EmptyError> {
176    /// let slice = &[1, 2, 3];
177    /// let nonempty = NonEmptySlice::new(slice)?;
178    /// assert_eq!(nonempty.len(), NonZeroUsize::new(3).unwrap());
179    /// # Ok(())
180    /// # }
181    /// ```
182    #[must_use]
183    #[inline]
184    pub const fn len(&self) -> NonZeroUsize {
185        unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
186    }
187
188    /// A method which always returns `true`.
189    ///
190    /// Unlike a normal slice, this slice is never empty. It's incredibly likely
191    /// that, if you are using this check, it is absolutely unnecessary.
192    #[must_use]
193    #[inline]
194    #[allow(clippy::unused_self)]
195    pub const fn is_empty(&self) -> bool {
196        false
197    }
198
199    /// Returns the first element of the slice.
200    ///
201    /// Unlike [`slice::first`], this **does not** return an [`Option`].
202    ///
203    /// # Examples
204    ///
205    /// Basic usage:
206    ///
207    /// ```
208    /// use not_empty::NonEmptySlice;
209    ///
210    /// # fn main() -> Result<(), not_empty::EmptyError> {
211    /// let slice = &[1, 2, 3];
212    /// let nonempty = NonEmptySlice::new(slice)?;
213    /// assert_eq!(nonempty.first(), &1);
214    /// # Ok(())
215    /// # }
216    /// ```
217    #[must_use]
218    #[inline]
219    pub const fn first(&self) -> &T {
220        match self.inner.first() {
221            Some(element) => element,
222            None => unsafe { hint::unreachable_unchecked() },
223        }
224    }
225    /// Returns a mutable pointer to the first element of the slice.
226    ///
227    /// Unlike [`slice::first_mut`], this **does not** return an [`Option`].
228    ///
229    /// # Examples
230    ///
231    /// Basic usage:
232    ///
233    /// ```
234    /// use not_empty::NonEmptySlice;
235    ///
236    /// # fn main() -> Result<(), not_empty::EmptyError> {
237    /// let slice = &mut [0, 1, 2];
238    /// let nonempty = NonEmptySlice::new_mut(slice)?;
239    /// *nonempty.first_mut() = 5;
240    /// assert_eq!(nonempty, &[5, 1, 2]);
241    /// # Ok(())
242    /// # }
243    /// ```
244    #[must_use]
245    #[inline]
246    pub fn first_mut(&mut self) -> &mut T {
247        unsafe { self.inner.first_mut().unwrap_unchecked() }
248    }
249
250    /// Returns the first and all the rest of the elements of the slice.
251    ///
252    /// Unlike [`slice::split_first`], this **does not** return an [`Option`].
253    ///
254    /// # Examples
255    ///
256    /// Basic usage:
257    ///
258    /// ```
259    /// use not_empty::NonEmptySlice;
260    ///
261    /// # fn main() -> Result<(), not_empty::EmptyError> {
262    /// let slice = &[0, 1, 2];
263    /// let nonempty = NonEmptySlice::new(slice)?;
264    ///
265    /// let (first, elements) = nonempty.split_first();
266    /// assert_eq!(first, &0);
267    /// assert_eq!(elements, &[1, 2]);
268    /// # Ok(())
269    /// # }
270    /// ```
271    #[must_use]
272    #[inline]
273    pub const fn split_first(&self) -> (&T, &[T]) {
274        match self.inner.split_first() {
275            Some(tuple) => tuple,
276            None => unsafe { hint::unreachable_unchecked() },
277        }
278    }
279
280    /// Returns the first and all the rest of the elements of the slice.
281    ///
282    /// Unlike [`slice::split_first_mut`], this **does not** return an [`Option`].
283    ///
284    /// # Examples
285    ///
286    /// Basic usage:
287    ///
288    /// ```
289    /// use not_empty::NonEmptySlice;
290    ///
291    /// # fn main() -> Result<(), not_empty::EmptyError> {
292    /// let slice = &mut [0, 1, 2];
293    /// let nonempty = NonEmptySlice::new_mut(slice)?;
294    ///
295    /// let (first, elements) = nonempty.split_first_mut();
296    /// *first = 3;
297    /// elements[0] = 4;
298    /// elements[1] = 5;
299    ///
300    /// assert_eq!(slice, &[3, 4, 5]);
301    /// # Ok(())
302    /// # }
303    /// ```
304    #[must_use]
305    #[inline]
306    pub fn split_first_mut(&mut self) -> (&mut T, &mut [T]) {
307        unsafe { self.inner.split_first_mut().unwrap_unchecked() }
308    }
309
310    /// Returns the last element of the slice.
311    ///
312    /// Unlike [`slice::last`], this **does not** return an [`Option`].
313    ///
314    /// # Examples
315    ///
316    /// Basic usage:
317    ///
318    /// ```
319    /// use not_empty::NonEmptySlice;
320    ///
321    /// # fn main() -> Result<(), not_empty::EmptyError> {
322    /// let slice = &[1, 2, 3];
323    /// let nonempty = NonEmptySlice::new(slice)?;
324    /// assert_eq!(nonempty.last(), &3);
325    /// # Ok(())
326    /// # }
327    /// ```
328    #[must_use]
329    #[inline]
330    pub const fn last(&self) -> &T {
331        match self.inner.last() {
332            Some(element) => element,
333            None => unsafe { hint::unreachable_unchecked() },
334        }
335    }
336
337    /// Returns a mutable pointer to the last element of the slice.
338    ///
339    /// Unlike [`slice::last_mut`], this **does not** return an [`Option`].
340    ///
341    /// # Examples
342    ///
343    /// Basic usage:
344    ///
345    /// ```
346    /// use not_empty::NonEmptySlice;
347    ///
348    /// # fn main() -> Result<(), not_empty::EmptyError> {
349    /// let slice = &mut [0, 1, 2];
350    /// let nonempty = NonEmptySlice::new_mut(slice)?;
351    /// *nonempty.last_mut() = 10;
352    /// assert_eq!(nonempty, &[0, 1, 10]);
353    /// # Ok(())
354    /// # }
355    /// ```
356    #[must_use]
357    #[inline]
358    pub fn last_mut(&mut self) -> &mut T {
359        unsafe { self.inner.last_mut().unwrap_unchecked() }
360    }
361
362    /// Returns the last and all the rest of the elements of the slice.
363    ///
364    /// Unlike [`slice::split_last`], this **does not** return an [`Option`].
365    ///
366    /// # Examples
367    ///
368    /// Basic usage:
369    ///
370    /// ```
371    /// use not_empty::NonEmptySlice;
372    ///
373    /// # fn main() -> Result<(), not_empty::EmptyError> {
374    /// let slice = &[0, 1, 2];
375    /// let nonempty = NonEmptySlice::new(slice)?;
376    ///
377    /// let (last, elements) = nonempty.split_last();
378    /// assert_eq!(last, &2);
379    /// assert_eq!(elements, &[0, 1]);
380    /// # Ok(())
381    /// # }
382    /// ```
383    #[must_use]
384    #[inline]
385    pub const fn split_last(&self) -> (&T, &[T]) {
386        match self.inner.split_last() {
387            Some(tuple) => tuple,
388            None => unsafe { hint::unreachable_unchecked() },
389        }
390    }
391
392    /// Returns the last and all the rest of the elements of the slice.
393    ///
394    /// Unlike [`slice::split_last_mut`], this **does not** return an [`Option`].
395    ///
396    /// # Examples
397    ///
398    /// Basic usage:
399    ///
400    /// ```
401    /// use not_empty::NonEmptySlice;
402    ///
403    /// # fn main() -> Result<(), not_empty::EmptyError> {
404    /// let slice = &mut [0, 1, 2];
405    /// let nonempty = NonEmptySlice::new_mut(slice)?;
406    ///
407    /// let (last, elements) = nonempty.split_last_mut();
408    /// *last = 3;
409    /// elements[0] = 4;
410    /// elements[1] = 5;
411    ///
412    /// assert_eq!(slice, &[4, 5, 3]);
413    /// # Ok(())
414    /// # }
415    /// ```
416    #[must_use]
417    #[inline]
418    pub fn split_last_mut(&mut self) -> (&mut T, &mut [T]) {
419        unsafe { self.inner.split_last_mut().unwrap_unchecked() }
420    }
421
422    ////////////////////////////////////////////////////////////////////////////
423    // `alloc` methods
424    ////////////////////////////////////////////////////////////////////////////
425
426    /// Copies `self` into a new [`NonEmptyVec`].
427    ///
428    /// Unlike [`slice::to_vec`], this returns a [`NonEmptyVec<T>`] instead of a
429    /// [`Vec<T>`].
430    ///
431    /// # Examples
432    ///
433    /// Basic usage:
434    ///
435    /// ```
436    /// use not_empty::{NonEmptySlice, NonEmptyVec};
437    ///
438    /// # fn main() -> Result<(), not_empty::EmptyError> {
439    /// let slice = &[1, 2, 3];
440    /// let nonempty: &NonEmptySlice<_> = NonEmptySlice::new(slice)?;
441    /// let nonempty_vec: NonEmptyVec<_> = nonempty.to_vec();
442    ///
443    /// assert_eq!(nonempty_vec, not_empty::vec![1, 2, 3]);
444    /// # Ok(())
445    /// # }
446    /// ```
447    #[cfg(any(feature = "alloc", feature = "std"))]
448    #[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
449    #[must_use]
450    #[inline]
451    pub fn to_vec(&self) -> NonEmptyVec<T>
452    where
453        T: Clone,
454    {
455        let vec = self.inner.to_vec();
456        unsafe { NonEmptyVec::new_unchecked(vec) }
457    }
458
459    /// Converts `self` into a non-empty vector without clones or allocation.
460    ///
461    /// Unlike [`slice::into_vec`], this returns a [`NonEmptyVec<T>`] instead of
462    /// a [`Vec<T>`].
463    ///
464    /// The resulting [`NonEmptyVec<T>`] can get converted back into a box
465    /// via [`NonEmptyVec::into_boxed_slice`].
466    ///
467    /// # Examples
468    ///
469    /// Basic usage:
470    ///
471    /// ```
472    /// use not_empty::{NonEmptySlice, NonEmptyVec};
473    ///
474    /// # fn main() -> Result<(), not_empty::EmptyError> {
475    /// let boxed_slice: Box<[_]> = Box::new([10, 40, 30]);
476    /// let boxed_nonempty: Box<NonEmptySlice<_>> = boxed_slice.try_into()?;
477    /// let nonempty_vec = boxed_nonempty.into_vec();
478    ///
479    /// assert_eq!(nonempty_vec, not_empty::vec![10, 40, 30]);
480    /// # Ok(())
481    /// # }
482    /// ```
483    #[cfg(any(feature = "alloc", feature = "std"))]
484    #[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
485    #[must_use]
486    #[inline]
487    pub fn into_vec(self: Box<NonEmptySlice<T>>) -> NonEmptyVec<T> {
488        let len = self.len();
489        let ptr = Box::into_raw(self).cast::<T>();
490        unsafe { NonEmptyVec::from_raw_parts(ptr, len, len) }
491    }
492}
493
494impl NonEmptySlice<u8> {
495    /// Returns a non-empty vector containing a copy of this slice where each
496    /// byte is mapped to its ASCII upper case equivalent.
497    ///
498    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', but non-ASCII letters
499    /// are unchanged.
500    ///
501    /// To uppercase the value in-place, use [`make_ascii_uppercase`].
502    ///
503    /// [`make_ascii_uppercase`]: slice::make_ascii_uppercase
504    #[cfg(any(feature = "alloc", feature = "std"))]
505    #[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
506    #[must_use]
507    #[inline]
508    pub fn to_ascii_uppercase(&self) -> NonEmptyVec<u8> {
509        unsafe { NonEmptyVec::new_unchecked(self.inner.to_ascii_uppercase()) }
510    }
511
512    /// Returns a non-empty vector containing a copy of this slice where each
513    /// byte is mapped to its ASCII lower case equivalent.
514    ///
515    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', but non-ASCII letters
516    /// are unchanged.
517    ///
518    /// To uppercase the value in-place, use [`make_ascii_lowercase`].
519    ///
520    /// [`make_ascii_lowercase`]: slice::make_ascii_lowercase
521    #[cfg(any(feature = "alloc", feature = "std"))]
522    #[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
523    #[must_use]
524    #[inline]
525    pub fn to_ascii_lowercase(&self) -> NonEmptyVec<u8> {
526        unsafe { NonEmptyVec::new_unchecked(self.inner.to_ascii_lowercase()) }
527    }
528}
529
530////////////////////////////////////////////////////////////////////////////////
531// Formatting implementations
532////////////////////////////////////////////////////////////////////////////////
533
534impl<T> fmt::Debug for NonEmptySlice<T>
535where
536    T: fmt::Debug,
537{
538    #[inline]
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        fmt::Debug::fmt(&self.inner, f)
541    }
542}
543
544////////////////////////////////////////////////////////////////////////////////
545// Dereferencing implementations
546////////////////////////////////////////////////////////////////////////////////
547
548impl<T> ops::Deref for NonEmptySlice<T> {
549    type Target = [T];
550
551    #[inline]
552    fn deref(&self) -> &Self::Target {
553        &self.inner
554    }
555}
556
557impl<T> ops::DerefMut for NonEmptySlice<T> {
558    #[inline]
559    fn deref_mut(&mut self) -> &mut Self::Target {
560        &mut self.inner
561    }
562}
563
564////////////////////////////////////////////////////////////////////////////////
565// Indexing implementations
566////////////////////////////////////////////////////////////////////////////////
567
568impl<T, I: SliceIndex<[T]>> ops::Index<I> for NonEmptySlice<T> {
569    type Output = I::Output;
570
571    #[inline]
572    fn index(&self, index: I) -> &Self::Output {
573        ops::Index::<I>::index(&self.inner, index)
574    }
575}
576
577impl<T, I: SliceIndex<[T]>> ops::IndexMut<I> for NonEmptySlice<T> {
578    #[inline]
579    fn index_mut(&mut self, index: I) -> &mut Self::Output {
580        ops::IndexMut::index_mut(&mut self.inner, index)
581    }
582}
583
584////////////////////////////////////////////////////////////////////////////////
585// Iterator traits
586////////////////////////////////////////////////////////////////////////////////
587
588impl<'a, T> IntoIterator for &'a NonEmptySlice<T> {
589    type Item = &'a T;
590    type IntoIter = slice::Iter<'a, T>;
591
592    #[inline]
593    fn into_iter(self) -> Self::IntoIter {
594        self.iter()
595    }
596}
597
598impl<'a, T> IntoIterator for &'a mut NonEmptySlice<T> {
599    type Item = &'a mut T;
600    type IntoIter = slice::IterMut<'a, T>;
601
602    #[inline]
603    fn into_iter(self) -> Self::IntoIter {
604        self.iter_mut()
605    }
606}
607
608////////////////////////////////////////////////////////////////////////////////
609// `as_*` implementations
610////////////////////////////////////////////////////////////////////////////////
611
612impl<T> AsRef<[T]> for NonEmptySlice<T> {
613    #[inline]
614    fn as_ref(&self) -> &[T] {
615        &self.inner
616    }
617}
618
619impl<T> AsMut<[T]> for NonEmptySlice<T> {
620    #[inline]
621    fn as_mut(&mut self) -> &mut [T] {
622        &mut self.inner
623    }
624}
625
626////////////////////////////////////////////////////////////////////////////////
627// `borrow` implementations
628////////////////////////////////////////////////////////////////////////////////
629
630#[cfg(any(feature = "alloc", feature = "std"))]
631#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
632impl<T> Borrow<[T]> for NonEmptySlice<T> {
633    #[inline]
634    fn borrow(&self) -> &[T] {
635        self
636    }
637}
638
639#[cfg(any(feature = "alloc", feature = "std"))]
640#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
641impl<T> BorrowMut<[T]> for NonEmptySlice<T> {
642    fn borrow_mut(&mut self) -> &mut [T] {
643        self
644    }
645}
646
647#[cfg(any(feature = "alloc", feature = "std"))]
648#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
649impl<T: Clone> ToOwned for NonEmptySlice<T> {
650    type Owned = NonEmptyVec<T>;
651
652    #[inline]
653    fn to_owned(&self) -> Self::Owned {
654        self.to_vec()
655    }
656
657    #[inline]
658    fn clone_into(&self, target: &mut Self::Owned) {
659        target.truncate(self.len());
660
661        let (init, tail) = self.split_at(target.len().get());
662
663        target.clone_from_slice(init);
664        target.extend_from_slice(tail);
665    }
666}
667
668////////////////////////////////////////////////////////////////////////////////
669// Partial equivalence implementations
670////////////////////////////////////////////////////////////////////////////////
671
672impl<T, U> PartialEq<NonEmptySlice<U>> for NonEmptySlice<T>
673where
674    T: PartialEq<U>,
675{
676    #[inline]
677    fn eq(&self, other: &NonEmptySlice<U>) -> bool {
678        self.inner == other.inner
679    }
680}
681
682impl<T, U> PartialEq<[U]> for NonEmptySlice<T>
683where
684    T: PartialEq<U>,
685{
686    #[inline]
687    fn eq(&self, other: &[U]) -> bool {
688        &self.inner == other
689    }
690}
691
692impl<T, U> PartialEq<NonEmptySlice<U>> for [T]
693where
694    T: PartialEq<U>,
695{
696    #[inline]
697    fn eq(&self, other: &NonEmptySlice<U>) -> bool {
698        self == &other.inner
699    }
700}
701
702impl<T, U, const N: usize> PartialEq<[U; N]> for NonEmptySlice<T>
703where
704    T: PartialEq<U>,
705{
706    #[inline]
707    fn eq(&self, other: &[U; N]) -> bool {
708        &self.inner == other
709    }
710}
711
712impl<T, U, const N: usize> PartialEq<NonEmptySlice<U>> for [T; N]
713where
714    T: PartialEq<U>,
715{
716    #[inline]
717    fn eq(&self, other: &NonEmptySlice<U>) -> bool {
718        self == &other.inner
719    }
720}
721
722#[cfg(any(feature = "alloc", feature = "std"))]
723#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
724impl<T, U> PartialEq<VecDeque<U>> for NonEmptySlice<T>
725where
726    T: PartialEq<U>,
727{
728    // This is a workaround since rustlib's PartialEq implementation isn't
729    // symmetric.
730    fn eq(&self, other: &VecDeque<U>) -> bool {
731        if self.inner.len() != other.len() {
732            return false;
733        }
734
735        let (oa, ob) = other.as_slices();
736        let (sa, sb) = self.split_at(oa.len());
737
738        sa == oa && sb == ob
739    }
740}
741
742#[cfg(any(feature = "alloc", feature = "std"))]
743#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
744impl<T, U> PartialEq<NonEmptySlice<U>> for VecDeque<T>
745where
746    T: PartialEq<U>,
747{
748    fn eq(&self, other: &NonEmptySlice<U>) -> bool {
749        self == &&other.inner
750    }
751}
752
753#[cfg(any(feature = "alloc", feature = "std"))]
754#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
755impl<T, U> PartialEq<Vec<U>> for NonEmptySlice<T>
756where
757    T: PartialEq<U>,
758{
759    #[inline]
760    fn eq(&self, other: &Vec<U>) -> bool {
761        &self.inner == other
762    }
763}
764
765#[cfg(any(feature = "alloc", feature = "std"))]
766#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
767impl<T, U> PartialEq<NonEmptySlice<U>> for Vec<T>
768where
769    T: PartialEq<U>,
770{
771    #[inline]
772    fn eq(&self, other: &NonEmptySlice<U>) -> bool {
773        self == &other.inner
774    }
775}
776
777////////////////////////////////////////////////////////////////////////////////
778// Other comparison traits
779////////////////////////////////////////////////////////////////////////////////
780
781impl<T> Eq for NonEmptySlice<T> where T: Ord {}
782
783impl<T> PartialOrd for NonEmptySlice<T>
784where
785    T: PartialOrd,
786{
787    #[inline]
788    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
789        self.inner.partial_cmp(&other.inner)
790    }
791}
792
793impl<T> Ord for NonEmptySlice<T>
794where
795    T: Ord,
796{
797    #[inline]
798    fn cmp(&self, other: &Self) -> Ordering {
799        self.inner.cmp(&other.inner)
800    }
801}
802
803////////////////////////////////////////////////////////////////////////////////
804// Hashing
805////////////////////////////////////////////////////////////////////////////////
806
807impl<T> Hash for NonEmptySlice<T>
808where
809    T: Hash,
810{
811    fn hash<H: Hasher>(&self, state: &mut H) {
812        self.inner.hash(state);
813    }
814}
815
816////////////////////////////////////////////////////////////////////////////////
817// Conversions
818////////////////////////////////////////////////////////////////////////////////
819
820impl<'a, T> From<&'a NonEmptySlice<T>> for &'a [T] {
821    #[inline]
822    fn from(slice: &'a NonEmptySlice<T>) -> Self {
823        slice
824    }
825}
826
827impl<'a, T> From<&'a mut NonEmptySlice<T>> for &'a mut [T] {
828    #[inline]
829    fn from(slice: &'a mut NonEmptySlice<T>) -> Self {
830        slice
831    }
832}
833
834#[cfg(any(feature = "alloc", feature = "std"))]
835#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
836impl<T> From<Box<NonEmptySlice<T>>> for Box<[T]> {
837    fn from(boxed: Box<NonEmptySlice<T>>) -> Self {
838        let raw = Box::into_raw(boxed) as *mut [T];
839        unsafe { Box::from_raw(raw) }
840    }
841}
842
843#[cfg(any(feature = "alloc", feature = "std"))]
844#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
845impl<'a, T> From<&'a NonEmptySlice<T>> for Cow<'a, NonEmptySlice<T>>
846where
847    T: Clone,
848{
849    fn from(s: &'a NonEmptySlice<T>) -> Self {
850        Cow::Borrowed(s)
851    }
852}
853
854#[cfg(any(feature = "alloc", feature = "std"))]
855#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
856impl<T> From<&NonEmptySlice<T>> for Arc<NonEmptySlice<T>>
857where
858    T: Clone,
859{
860    #[inline]
861    fn from(s: &NonEmptySlice<T>) -> Self {
862        let arc: Arc<[T]> = Arc::from(&s.inner);
863        let ptr = Arc::into_raw(arc) as *const NonEmptySlice<T>;
864        unsafe { Arc::from_raw(ptr) }
865    }
866}
867
868#[cfg(any(feature = "alloc", feature = "std"))]
869#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
870impl<T> From<&NonEmptySlice<T>> for Rc<NonEmptySlice<T>>
871where
872    T: Clone,
873{
874    #[inline]
875    fn from(s: &NonEmptySlice<T>) -> Self {
876        let rc: Rc<[T]> = Rc::from(&s.inner);
877        let ptr = Rc::into_raw(rc) as *const NonEmptySlice<T>;
878        unsafe { Rc::from_raw(ptr) }
879    }
880}
881
882#[cfg(any(feature = "alloc", feature = "std"))]
883#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
884impl<'a, T> From<&'a NonEmptySlice<T>> for NonEmptyVec<T>
885where
886    T: Clone,
887{
888    #[inline]
889    fn from(slice: &'a NonEmptySlice<T>) -> Self {
890        let vec: Vec<T> = slice.inner.into();
891        unsafe { NonEmptyVec::new_unchecked(vec) }
892    }
893}
894
895#[cfg(any(feature = "alloc", feature = "std"))]
896#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
897impl<'a, T> From<&'a mut NonEmptySlice<T>> for NonEmptyVec<T>
898where
899    T: Clone,
900{
901    #[inline]
902    fn from(slice: &'a mut NonEmptySlice<T>) -> Self {
903        let vec: Vec<T> = slice.inner.into();
904        unsafe { NonEmptyVec::new_unchecked(vec) }
905    }
906}
907
908////////////////////////////////////////////////////////////////////////////////
909// Failable conversions
910////////////////////////////////////////////////////////////////////////////////
911
912impl<T, const N: usize> TryFrom<&NonEmptySlice<T>> for [T; N]
913where
914    T: Copy,
915{
916    type Error = TryFromSliceError;
917
918    #[inline]
919    fn try_from(value: &NonEmptySlice<T>) -> Result<Self, Self::Error> {
920        value.inner.try_into()
921    }
922}
923
924impl<T, const N: usize> TryFrom<&mut NonEmptySlice<T>> for [T; N]
925where
926    T: Copy,
927{
928    type Error = TryFromSliceError;
929
930    #[inline]
931    fn try_from(value: &mut NonEmptySlice<T>) -> Result<Self, Self::Error> {
932        value.inner.try_into()
933    }
934}
935
936impl<'a, T, const N: usize> TryFrom<&'a NonEmptySlice<T>> for &'a [T; N] {
937    type Error = TryFromSliceError;
938
939    #[inline]
940    fn try_from(value: &'a NonEmptySlice<T>) -> Result<Self, Self::Error> {
941        value.inner.try_into()
942    }
943}
944
945impl<'a, T, const N: usize> TryFrom<&'a mut NonEmptySlice<T>> for &'a mut [T; N] {
946    type Error = TryFromSliceError;
947
948    #[inline]
949    fn try_from(value: &'a mut NonEmptySlice<T>) -> Result<Self, Self::Error> {
950        (&mut value.inner).try_into()
951    }
952}
953
954#[cfg(any(feature = "alloc", feature = "std"))]
955#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
956impl<T, const N: usize> TryFrom<[T; N]> for Box<NonEmptySlice<T>> {
957    type Error = EmptyError;
958
959    /// Converts a `[T; N]` into a `Box<NonEmptySlice<T>>` if `N` is not zero.
960    ///
961    /// This conversion moves the array to newly heap-allocated memory.
962    ///
963    /// # Errors
964    ///
965    /// Returns an [`EmptyError`] if `N` is equal to zero.
966    ///
967    /// # Examples
968    ///
969    /// ```
970    /// use not_empty::NonEmptySlice;
971    ///
972    /// # fn main() -> Result<(), not_empty::EmptyError> {
973    /// let boxed: Box<NonEmptySlice<u8>> = Box::try_from([1, 2, 3])?;
974    /// println!("{boxed:?}");
975    /// # Ok(())
976    /// # }
977    /// ```
978    #[inline]
979    fn try_from(array: [T; N]) -> Result<Self, Self::Error> {
980        let boxed_array: Box<[T]> = Box::new(array);
981        boxed_array.try_into()
982    }
983}
984
985#[cfg(any(feature = "alloc", feature = "std"))]
986#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
987impl<T> TryFrom<Box<[T]>> for Box<NonEmptySlice<T>> {
988    type Error = EmptyError;
989
990    /// Converts a boxed slice into a boxed non-empty slice if the given slice
991    /// is not empty.
992    ///
993    /// # Errors
994    ///
995    /// Returns an [`EmptyError`] if the input slice is empty.
996    ///
997    /// # Examples
998    ///
999    /// ```
1000    /// use not_empty::NonEmptySlice;
1001    ///
1002    /// # fn main() -> Result<(), not_empty::EmptyError> {
1003    /// let boxed_slice: Box<[i32]> = Box::from([1, 2, 3]);
1004    /// let boxed_nonempty: Box<NonEmptySlice<i32>> = boxed_slice.try_into()?;
1005    /// # Ok(())
1006    /// # }
1007    /// ```
1008    fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1009        if boxed_slice.is_empty() {
1010            Err(EmptyError)
1011        } else {
1012            let raw = Box::into_raw(boxed_slice) as *mut NonEmptySlice<T>;
1013            Ok(unsafe { Box::from_raw(raw) })
1014        }
1015    }
1016}
1017
1018#[cfg(any(feature = "alloc", feature = "std"))]
1019#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1020impl<T> TryFrom<Box<[T]>> for NonEmptyVec<T> {
1021    type Error = EmptyError;
1022
1023    #[inline]
1024    fn try_from(value: Box<[T]>) -> Result<Self, Self::Error> {
1025        value.try_into().map(NonEmptySlice::into_vec)
1026    }
1027}
1028
1029impl<'a, T> TryFrom<&'a [T]> for &'a NonEmptySlice<T> {
1030    type Error = EmptyError;
1031
1032    #[inline]
1033    fn try_from(value: &'a [T]) -> Result<Self, Self::Error> {
1034        NonEmptySlice::new(value)
1035    }
1036}
1037
1038impl<'a, T> TryFrom<&'a mut [T]> for &'a mut NonEmptySlice<T> {
1039    type Error = EmptyError;
1040
1041    #[inline]
1042    fn try_from(value: &'a mut [T]) -> Result<Self, Self::Error> {
1043        NonEmptySlice::new_mut(value)
1044    }
1045}
1046
1047////////////////////////////////////////////////////////////////////////////////
1048// `net` implementations
1049////////////////////////////////////////////////////////////////////////////////
1050
1051#[cfg(feature = "std")]
1052#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
1053impl<'a> ToSocketAddrs for &'a NonEmptySlice<SocketAddr> {
1054    type Iter = core::iter::Cloned<slice::Iter<'a, SocketAddr>>;
1055
1056    #[inline]
1057    fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
1058        (&self.inner).to_socket_addrs()
1059    }
1060}
1061
1062////////////////////////////////////////////////////////////////////////////////
1063// `serde` implementations
1064////////////////////////////////////////////////////////////////////////////////
1065
1066#[cfg(feature = "serde")]
1067#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
1068impl<T> serde::Serialize for NonEmptySlice<T>
1069where
1070    T: serde::Serialize,
1071{
1072    #[inline]
1073    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1074    where
1075        S: serde::Serializer,
1076    {
1077        serde::Serialize::serialize(&self.inner, serializer)
1078    }
1079}
1080
1081#[cfg(feature = "serde")]
1082#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
1083impl<'de: 'a, 'a> serde::Deserialize<'de> for &'a NonEmptySlice<u8> {
1084    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1085    where
1086        D: serde::Deserializer<'de>,
1087    {
1088        let slice: &'de [u8] = serde::Deserialize::deserialize(deserializer)?;
1089        NonEmptySlice::new(slice).map_err(|_| {
1090            serde::de::Error::custom("cannot deserialize `NonEmptySlice` from an empty sequence")
1091        })
1092    }
1093}
1094
1095/// The nonempty equivalent of [`slice::from_raw_parts`].
1096#[allow(clippy::missing_safety_doc)]
1097#[must_use]
1098#[inline]
1099pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: NonZeroUsize) -> &'a NonEmptySlice<T> {
1100    NonEmptySlice::new_unchecked(slice::from_raw_parts(data, len.get()))
1101}
1102
1103/// The nonempty equivalent of [`slice::from_raw_parts_mut`].
1104#[allow(clippy::missing_safety_doc)]
1105#[must_use]
1106#[inline]
1107pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: NonZeroUsize) -> &'a NonEmptySlice<T> {
1108    NonEmptySlice::new_mut_unchecked(slice::from_raw_parts_mut(data, len.get()))
1109}
1110
1111/// Converts a reference to T into a slice of length 1 (without copying).
1112#[must_use]
1113#[inline]
1114pub const fn from_ref<T>(s: &T) -> &NonEmptySlice<T> {
1115    unsafe { NonEmptySlice::new_unchecked(slice::from_ref(s)) }
1116}
1117
1118/// Converts a mutable reference to T into a mutable slice of length 1 (without
1119/// copying).
1120#[must_use]
1121#[inline]
1122pub fn from_mut<T>(s: &mut T) -> &mut NonEmptySlice<T> {
1123    unsafe { NonEmptySlice::new_mut_unchecked(slice::from_mut(s)) }
1124}