non_empty_slice/
vec.rs

1//! Non-empty [`Vec<T>`].
2
3#[cfg(not(any(feature = "std", feature = "alloc")))]
4compile_error!("expected either `std` or `alloc` to be enabled");
5
6#[cfg(feature = "std")]
7use std::{collections::TryReserveError, vec::IntoIter};
8
9#[cfg(all(not(feature = "std"), feature = "alloc"))]
10use alloc::{
11    borrow::ToOwned,
12    collections::TryReserveError,
13    vec::{IntoIter, Vec},
14};
15
16use core::{
17    borrow::{Borrow, BorrowMut},
18    mem::MaybeUninit,
19    ops::{Deref, DerefMut, Index, IndexMut, RangeBounds},
20    slice::{Iter, IterMut, SliceIndex, from_raw_parts_mut},
21};
22
23use non_empty_iter::{
24    FromNonEmptyIterator, IntoNonEmptyIterator, NonEmptyAdapter, NonEmptyIterator,
25};
26use non_zero_size::Size;
27use thiserror::Error;
28
29use crate::{
30    boxed::EmptyBoxedSlice,
31    format,
32    iter::{IntoNonEmptyIter, NonEmptyIter, NonEmptyIterMut},
33    slice::{EmptySlice, NonEmptySlice},
34};
35
36/// The error message used when the vector is empty.
37pub const EMPTY_VEC: &str = "the vector is empty";
38
39/// Similar to [`EmptySlice`], but holds the empty vector provided.
40///
41/// [`EmptySlice`]: crate::slice::EmptySlice
42#[derive(Error)]
43#[error("{EMPTY_VEC}")]
44#[cfg_attr(
45    feature = "diagnostics",
46    derive(miette::Diagnostic),
47    diagnostic(code(non_empty_slice::vec), help("make sure the vector is non-empty"))
48)]
49pub struct EmptyVec<T> {
50    vec: Vec<T>,
51}
52
53format::debug!(EmptyVec, vec);
54
55impl<T> EmptyVec<T> {
56    // NOTE: this is private to prevent creating this error with non-empty vectors
57    pub(crate) const fn new(vec: Vec<T>) -> Self {
58        Self { vec }
59    }
60
61    /// Returns the contained empty vector.
62    #[must_use]
63    pub fn get(self) -> Vec<T> {
64        self.vec
65    }
66
67    /// Constructs [`Self`] from [`EmptyBoxedSlice<T>`].
68    #[must_use]
69    pub fn from_empty_boxed_slice(empty: EmptyBoxedSlice<T>) -> Self {
70        Self::new(empty.get().into_vec())
71    }
72
73    /// Converts [`Self`] into [`EmptyBoxedSlice<T>`].
74    #[must_use]
75    pub fn into_empty_boxed_slice(self) -> EmptyBoxedSlice<T> {
76        EmptyBoxedSlice::from_empty_vec(self)
77    }
78}
79
80/// Represents empty byte vectors, [`EmptyVec<u8>`].
81pub type EmptyByteVec = EmptyVec<u8>;
82
83/// Represents non-empty [`Vec<T>`] values.
84#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
85#[repr(transparent)]
86pub struct NonEmptyVec<T> {
87    inner: Vec<T>,
88}
89
90impl<T: Clone> Clone for NonEmptyVec<T> {
91    fn clone(&self) -> Self {
92        // SAFETY: the vector is non-empty by construction
93        unsafe { Self::new_unchecked(self.as_vec().clone()) }
94    }
95
96    fn clone_from(&mut self, source: &Self) {
97        // SAFETY: cloning from non-empty vector can not make the vector empty
98        unsafe {
99            self.as_mut_vec().clone_from(source.as_vec());
100        }
101    }
102}
103
104/// Represents non-empty byte vectors, [`NonEmptyVec<u8>`].
105pub type NonEmptyByteVec = NonEmptyVec<u8>;
106
107impl<T: Clone> ToOwned for NonEmptySlice<T> {
108    type Owned = NonEmptyVec<T>;
109
110    fn to_owned(&self) -> Self::Owned {
111        self.to_non_empty_vec()
112    }
113}
114
115impl<T> Borrow<NonEmptySlice<T>> for NonEmptyVec<T> {
116    fn borrow(&self) -> &NonEmptySlice<T> {
117        self.as_non_empty_slice()
118    }
119}
120
121impl<T> BorrowMut<NonEmptySlice<T>> for NonEmptyVec<T> {
122    fn borrow_mut(&mut self) -> &mut NonEmptySlice<T> {
123        self.as_non_empty_mut_slice()
124    }
125}
126
127impl<T> Borrow<[T]> for NonEmptyVec<T> {
128    fn borrow(&self) -> &[T] {
129        self.as_slice()
130    }
131}
132
133impl<T> BorrowMut<[T]> for NonEmptyVec<T> {
134    fn borrow_mut(&mut self) -> &mut [T] {
135        self.as_mut_slice()
136    }
137}
138
139impl<T> TryFrom<Vec<T>> for NonEmptyVec<T> {
140    type Error = EmptyVec<T>;
141
142    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
143        Self::new(value)
144    }
145}
146
147impl<T> From<NonEmptyVec<T>> for Vec<T> {
148    fn from(non_empty: NonEmptyVec<T>) -> Self {
149        non_empty.into_vec()
150    }
151}
152
153impl<T: Clone> From<&NonEmptySlice<T>> for NonEmptyVec<T> {
154    fn from(non_empty: &NonEmptySlice<T>) -> Self {
155        non_empty.to_non_empty_vec()
156    }
157}
158
159impl<T: Clone> From<&mut NonEmptySlice<T>> for NonEmptyVec<T> {
160    fn from(non_empty: &mut NonEmptySlice<T>) -> Self {
161        non_empty.to_non_empty_vec()
162    }
163}
164
165impl<T: Clone> TryFrom<&[T]> for NonEmptyVec<T> {
166    type Error = EmptySlice;
167
168    fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
169        let non_empty_slice: &NonEmptySlice<T> = slice.try_into()?;
170
171        Ok(non_empty_slice.into())
172    }
173}
174
175impl<T: Clone> TryFrom<&mut [T]> for NonEmptyVec<T> {
176    type Error = EmptySlice;
177
178    fn try_from(slice: &mut [T]) -> Result<Self, Self::Error> {
179        let non_empty_slice: &mut NonEmptySlice<T> = slice.try_into()?;
180
181        Ok(non_empty_slice.into())
182    }
183}
184
185impl<T> AsRef<Self> for NonEmptyVec<T> {
186    fn as_ref(&self) -> &Self {
187        self
188    }
189}
190
191impl<T> AsMut<Self> for NonEmptyVec<T> {
192    fn as_mut(&mut self) -> &mut Self {
193        self
194    }
195}
196
197impl<T> AsRef<Vec<T>> for NonEmptyVec<T> {
198    fn as_ref(&self) -> &Vec<T> {
199        self.as_vec()
200    }
201}
202
203impl<T> AsRef<NonEmptySlice<T>> for NonEmptyVec<T> {
204    fn as_ref(&self) -> &NonEmptySlice<T> {
205        self.as_non_empty_slice()
206    }
207}
208
209impl<T> AsMut<NonEmptySlice<T>> for NonEmptyVec<T> {
210    fn as_mut(&mut self) -> &mut NonEmptySlice<T> {
211        self.as_non_empty_mut_slice()
212    }
213}
214
215impl<T> AsRef<[T]> for NonEmptyVec<T> {
216    fn as_ref(&self) -> &[T] {
217        self.as_slice()
218    }
219}
220
221impl<T> AsMut<[T]> for NonEmptyVec<T> {
222    fn as_mut(&mut self) -> &mut [T] {
223        self.as_mut_slice()
224    }
225}
226
227impl<T> Deref for NonEmptyVec<T> {
228    type Target = NonEmptySlice<T>;
229
230    fn deref(&self) -> &Self::Target {
231        self.as_non_empty_slice()
232    }
233}
234
235impl<T> DerefMut for NonEmptyVec<T> {
236    fn deref_mut(&mut self) -> &mut Self::Target {
237        self.as_non_empty_mut_slice()
238    }
239}
240
241impl<T, I: SliceIndex<[T]>> Index<I> for NonEmptyVec<T> {
242    type Output = I::Output;
243
244    fn index(&self, index: I) -> &Self::Output {
245        self.as_vec().index(index)
246    }
247}
248
249impl<T, I: SliceIndex<[T]>> IndexMut<I> for NonEmptyVec<T> {
250    fn index_mut(&mut self, index: I) -> &mut Self::Output {
251        // SAFETY: indexing can not make the vector empty
252        unsafe { self.as_mut_vec().index_mut(index) }
253    }
254}
255
256impl<T> NonEmptyVec<T> {
257    /// Constructs [`Self`], provided that the [`Vec<T>`] provided is non-empty.
258    ///
259    /// # Errors
260    ///
261    /// Returns [`EmptyVec<T>`] if the provided vector is empty.
262    ///
263    /// # Examples
264    ///
265    /// Basic snippet:
266    ///
267    /// ```
268    /// use non_empty_slice::NonEmptyVec;
269    ///
270    /// let non_empty_vec = NonEmptyVec::new(vec![1, 2, 3]).unwrap();
271    /// ```
272    ///
273    /// Handling possible errors and recovering empty vectors (see [`EmptyVec<T>`] for more):
274    ///
275    /// ```
276    /// use non_empty_slice::NonEmptyByteVec;
277    ///
278    /// let empty_vec = NonEmptyByteVec::new(Vec::new()).unwrap_err();
279    ///
280    /// let empty = empty_vec.get();
281    /// ```
282    pub const fn new(vector: Vec<T>) -> Result<Self, EmptyVec<T>> {
283        if vector.is_empty() {
284            return Err(EmptyVec::new(vector));
285        }
286
287        // SAFETY: the vector is non-empty at this point
288        Ok(unsafe { Self::new_unchecked(vector) })
289    }
290
291    /// Constructs [`Self`] without checking that the [`Vec<T>`] is non-empty.
292    ///
293    /// # Safety
294    ///
295    /// The caller must ensure that the vector is non-empty.
296    #[must_use]
297    pub const unsafe fn new_unchecked(inner: Vec<T>) -> Self {
298        Self { inner }
299    }
300
301    #[cfg(feature = "unsafe-assert")]
302    const fn assert_non_empty(&self) {
303        use core::hint::assert_unchecked;
304
305        // SAFETY: the vector is non-empty by construction
306        unsafe {
307            assert_unchecked(!self.as_vec_no_assert().is_empty());
308        }
309    }
310
311    const fn as_vec_no_assert(&self) -> &Vec<T> {
312        &self.inner
313    }
314
315    const unsafe fn as_mut_vec_no_assert(&mut self) -> &mut Vec<T> {
316        &mut self.inner
317    }
318
319    fn into_vec_no_assert(self) -> Vec<T> {
320        self.inner
321    }
322
323    /// Returns the contained slice reference as [`NonEmptySlice<T>`].
324    #[must_use]
325    pub const fn as_non_empty_slice(&self) -> &NonEmptySlice<T> {
326        // SAFETY: the slice is non-empty by construction
327        unsafe { NonEmptySlice::from_slice_unchecked(self.as_slice()) }
328    }
329
330    /// Returns the contained slice reference as mutable [`NonEmptySlice<T>`].
331    #[must_use]
332    pub const fn as_non_empty_mut_slice(&mut self) -> &mut NonEmptySlice<T> {
333        // SAFETY: the slice is non-empty by construction
334        unsafe { NonEmptySlice::from_mut_slice_unchecked(self.as_mut_slice()) }
335    }
336
337    /// Extracts the slice containing the entire vector.
338    #[must_use]
339    pub const fn as_slice(&self) -> &[T] {
340        self.as_vec().as_slice()
341    }
342
343    /// Extracts the mutable slice containing the entire vector.
344    #[must_use]
345    pub const fn as_mut_slice(&mut self) -> &mut [T] {
346        // SAFETY: getting mutable slice can not make the vector empty
347        unsafe { self.as_mut_vec().as_mut_slice() }
348    }
349
350    /// Returns the contained [`Vec<T>`] behind immutable reference.
351    #[must_use]
352    pub const fn as_vec(&self) -> &Vec<T> {
353        #[cfg(feature = "unsafe-assert")]
354        self.assert_non_empty();
355
356        self.as_vec_no_assert()
357    }
358
359    /// Returns the contained [`Vec<T>`] behind mutable reference.
360    ///
361    /// # Safety
362    ///
363    /// The caller must ensure that the returned vector remains non-empty.
364    #[must_use]
365    pub const unsafe fn as_mut_vec(&mut self) -> &mut Vec<T> {
366        #[cfg(feature = "unsafe-assert")]
367        self.assert_non_empty();
368
369        // SAFETY: the caller must ensure that the returned vector remains non-empty
370        unsafe { self.as_mut_vec_no_assert() }
371    }
372
373    /// Returns the contained [`Vec<T>`].
374    #[must_use]
375    pub fn into_vec(self) -> Vec<T> {
376        #[cfg(feature = "unsafe-assert")]
377        self.assert_non_empty();
378
379        self.into_vec_no_assert()
380    }
381}
382
383impl<T: Clone> NonEmptyVec<T> {
384    /// Constructs [`Self`] from [`NonEmptySlice<T>`] via cloning.
385    ///
386    /// # Examples
387    ///
388    /// Basic snippet:
389    ///
390    /// ```
391    /// use non_empty_slice::{NonEmptyByteVec, NonEmptyBytes};
392    ///
393    /// let nekit = NonEmptyBytes::from_slice(b"nekit").unwrap();
394    ///
395    /// let owned = NonEmptyByteVec::from_non_empty_slice(nekit);
396    /// ```
397    pub fn from_non_empty_slice(non_empty: &NonEmptySlice<T>) -> Self {
398        // SAFETY: the slice is non-empty by construction
399        unsafe { Self::new_unchecked(non_empty.to_vec()) }
400    }
401}
402
403impl<T: Copy> NonEmptySlice<T> {
404    /// Creates [`NonEmptyVec<T>`] by repeating this non-empty slice certain number of times.
405    ///
406    /// # Panics
407    ///
408    /// Panics on capacity overflow.
409    pub fn repeat(&self, count: Size) -> NonEmptyVec<T> {
410        let repeated = self.as_slice().repeat(count.get());
411
412        // SAFETY: repeating non-empty slice non-zero number of times yields non-empty vector
413        unsafe { NonEmptyVec::new_unchecked(repeated) }
414    }
415}
416
417impl<T: Clone> NonEmptySlice<T> {
418    /// Constructs [`Vec<T>`] from the slice via cloning.
419    pub fn to_vec(&self) -> Vec<T> {
420        self.as_slice().to_vec()
421    }
422
423    /// Constructs [`NonEmptyVec<T>`] from the non-empty slice via cloning.
424    pub fn to_non_empty_vec(&self) -> NonEmptyVec<T> {
425        NonEmptyVec::from_non_empty_slice(self)
426    }
427}
428
429impl<T> NonEmptyVec<T> {
430    /// Checks if the vector is empty. Always returns [`false`].
431    ///
432    /// This method is marked as deprecated since the vector is never empty.
433    #[must_use]
434    #[deprecated = "this vector is never empty"]
435    pub const fn is_empty(&self) -> bool {
436        false
437    }
438
439    /// Returns the length of the vector as [`Size`].
440    #[must_use]
441    pub const fn len(&self) -> Size {
442        self.as_non_empty_slice().len()
443    }
444
445    /// Returns the capacity of the vector as [`Size`].
446    #[must_use]
447    pub const fn capacity(&self) -> Size {
448        let capacity = self.as_vec().capacity();
449
450        // SAFETY: non-empty vector implies non-zero capacity
451        unsafe { Size::new_unchecked(capacity) }
452    }
453
454    /// Appends the given value to the end of the vector.
455    ///
456    /// # Panics
457    ///
458    /// Panics on capacity overflow.
459    pub fn push(&mut self, value: T) {
460        // SAFETY: pushing can not make the vector empty
461        unsafe {
462            self.as_mut_vec().push(value);
463        }
464    }
465
466    /// Reserves capacity for at least `additional` more values to be inserted into the vector.
467    ///
468    /// Note that the additional capacity is required to be non-zero via [`Size`].
469    ///
470    /// This method can over-allocate to speculatively avoid frequent reallocations.
471    ///
472    /// Does nothing if the capacity is already sufficient.
473    ///
474    /// # Panics
475    ///
476    /// Panics on capacity overflow.
477    pub fn reserve(&mut self, additional: Size) {
478        // SAFETY: reserving can not make the vector empty
479        unsafe {
480            self.as_mut_vec().reserve(additional.get());
481        }
482    }
483
484    /// Reserves the minimum capacity for exactly `additional` more values to be inserted
485    /// into the vector.
486    ///
487    /// Note that the additional capacity is required to be non-zero via [`Size`].
488    ///
489    /// Unlike [`reserve`], this method will not deliberately over-allocate
490    /// to speculatively avoid frequent reallocations.
491    ///
492    /// Does nothing if the capacity is already sufficient.
493    ///
494    /// # Panics
495    ///
496    /// Panics on capacity overflow.
497    ///
498    /// [`reserve`]: Self::reserve
499    pub fn reserve_exact(&mut self, additional: Size) {
500        // SAFETY: reserving can not make the vector empty
501        unsafe {
502            self.as_mut_vec().reserve_exact(additional.get());
503        }
504    }
505
506    /// Tries to reserve capacity for at least `additional` more values to be inserted
507    /// into the vector.
508    ///
509    /// Note that the additional capacity is required to be non-zero via [`Size`].
510    ///
511    /// This method can over-allocate to speculatively avoid frequent reallocations.
512    ///
513    /// Does nothing if the capacity is already sufficient.
514    ///
515    /// # Errors
516    ///
517    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
518    pub fn try_reserve(&mut self, additional: Size) -> Result<(), TryReserveError> {
519        // SAFETY: reserving can not make the vector empty
520        unsafe { self.as_mut_vec().try_reserve(additional.get()) }
521    }
522
523    /// Tries to reserve the minimum capacity for exactly `additional` more values
524    /// to be inserted into the vector.
525    ///
526    /// Note that the additional capacity is required to be non-zero via [`Size`].
527    ///
528    /// Unlike [`try_reserve`], this method will not deliberately over-allocate
529    /// to speculatively avoid frequent reallocations.
530    ///
531    /// Does nothing if the capacity is already sufficient.
532    ///
533    /// # Errors
534    ///
535    /// Returns [`TryReserveError`] if the allocation fails or capacity overflows.
536    ///
537    /// [`try_reserve`]: Self::try_reserve
538    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
539        // SAFETY: reserving can not make the vector empty
540        unsafe { self.as_mut_vec().try_reserve_exact(additional) }
541    }
542
543    /// Shrinks the capacity of the vector as much as possible.
544    pub fn shrink_to_fit(&mut self) {
545        // SAFETY: shrinking can not make the vector empty
546        unsafe {
547            self.as_mut_vec().shrink_to_fit();
548        }
549    }
550
551    /// Shrinks the capacity of the vector to the specified amount.
552    ///
553    /// The capacity will remain at least as large as both the length and the supplied amount.
554    ///
555    /// Does nothing if the current capacity is less than or equal to the given amount.
556    pub fn shrink_to(&mut self, capacity: Size) {
557        // SAFETY: shrinking can not make the vector empty
558        unsafe {
559            self.as_mut_vec().shrink_to(capacity.get());
560        }
561    }
562
563    /// Shortens the vector, keeping the first `len` items and dropping the rest.
564    pub fn truncate(&mut self, len: Size) {
565        // SAFETY: length provided is non-zero, so truncating can not make the vector empty
566        unsafe {
567            self.as_mut_vec().truncate(len.get());
568        }
569    }
570
571    /// Moves all the items out of `other` into `self`, leaving `other` empty.
572    ///
573    /// # Panics
574    ///
575    /// Panics on capacity overflow.
576    pub fn append(&mut self, other: &mut Vec<T>) {
577        // SAFETY: appending can not make the vector empty
578        unsafe {
579            self.as_mut_vec().append(other);
580        }
581    }
582
583    /// Inserts the given value at the specified index, shifting all items after it to the right.
584    ///
585    /// # Panics
586    ///
587    /// Panics if the index is out of bounds.
588    pub fn insert(&mut self, index: usize, value: T) {
589        // SAFETY: inserting can not make the vector empty
590        unsafe {
591            self.as_mut_vec().insert(index, value);
592        }
593    }
594
595    /// Checks whether the vector is almost empty, meaning it only contains one value.
596    #[must_use]
597    pub fn next_empty(&self) -> bool {
598        self.len() == Size::MIN
599    }
600
601    /// The negated version of [`next_empty`].
602    ///
603    /// [`next_empty`]: Self::next_empty
604    #[must_use]
605    pub fn next_non_empty(&self) -> bool {
606        !self.next_empty()
607    }
608
609    /// Peeks at the last item of the vector mutably.
610    pub const fn peek_mut(&mut self) -> PeekMut<'_, T> {
611        PeekMut::new(self)
612    }
613
614    /// Removes the last item from the vector and returns it,
615    /// or [`None`] if the vector would become empty.
616    pub fn pop(&mut self) -> Option<T> {
617        self.next_non_empty()
618            // SAFETY: popping only if the vector would remain non-empty
619            .then(|| unsafe { self.as_mut_vec().pop() })
620            .flatten()
621    }
622
623    /// Removes the last item from the vector if the predicate returns [`true`],
624    /// or [`None`] if [`false`] is returned or if the vector would become empty.
625    pub fn pop_if<P: FnOnce(&mut T) -> bool>(&mut self, predicate: P) -> Option<T> {
626        self.next_non_empty()
627            // SAFETY: popping only if the vector would remain non-empty
628            .then(|| unsafe { self.as_mut_vec().pop_if(predicate) })
629            .flatten()
630    }
631
632    /// Removes and returns the item at the given index within the vector,
633    /// shifting all items after it to the left.
634    ///
635    /// Returns [`None`] if the vector would become empty.
636    pub fn remove(&mut self, index: usize) -> Option<T> {
637        self.next_non_empty()
638            // SAFETY: removing only if the vector would remain non-empty
639            .then(|| unsafe { self.as_mut_vec().remove(index) })
640    }
641
642    /// Removes and returns the item at the given index within the vector,
643    /// replacing it with the last item of the vector.
644    ///
645    /// Returns [`None`] if the vector would become empty.
646    pub fn swap_remove(&mut self, index: usize) -> Option<T> {
647        self.next_non_empty()
648            // SAFETY: swap-removing only if the vector would remain non-empty
649            .then(|| unsafe { self.as_mut_vec().swap_remove(index) })
650    }
651
652    /// Splits the vector into two at the given non-zero index.
653    ///
654    /// The index has to be non-zero to guarantee the vector would remain non-empty.
655    ///
656    /// # Panics
657    ///
658    /// Panics if the provided index is out of bounds.
659    pub fn split_off(&mut self, at: Size) -> Vec<T> {
660        // SAFETY: splitting at non-zero index can not make the vector empty
661        unsafe { self.as_mut_vec().split_off(at.get()) }
662    }
663
664    /// Resizes the vector in-place so that its length is equal to `new`.
665    ///
666    /// If `new` is greater than [`len`], the vector is extended by the difference,
667    /// with each additional slot filled by the result of calling the provided function.
668    ///
669    /// The additional items will appear in the same order as they are generated.
670    ///
671    /// [`len`]: Self::len
672    pub fn resize_with<F: FnMut() -> T>(&mut self, new: Size, function: F) {
673        // SAFETY: resizing to non-zero length can not make the vector empty
674        unsafe {
675            self.as_mut_vec().resize_with(new.get(), function);
676        }
677    }
678
679    /// Consumes and leaks the vector, returning the mutable slice of its contents.
680    #[must_use]
681    pub fn leak<'a>(self) -> &'a mut [T] {
682        self.into_vec().leak()
683    }
684
685    /// Similar to [`leak`], but yields [`NonEmptySlice<T>`].
686    ///
687    /// [`leak`]: Self::leak
688    #[must_use]
689    pub fn leak_non_empty<'a>(self) -> &'a mut NonEmptySlice<T> {
690        // SAFETY: leaking non-empty vector yields non-empty mutable slice
691        unsafe { NonEmptySlice::from_mut_slice_unchecked(self.leak()) }
692    }
693
694    /// Forces the length of the vector to the given [`Size`].
695    ///
696    /// # Safety
697    ///
698    /// The `new` length must be less than or equal to the [`capacity`].
699    ///
700    /// The items at `len..new` must be initialized.
701    ///
702    /// [`capacity`]: Self::capacity
703    pub unsafe fn set_len(&mut self, new: Size) {
704        // SAFETY: setting non-zero length guarantees the vector is non-empty
705        // moreover, the caller must uphold all safety requirements of this method
706        unsafe { self.as_mut_vec().set_len(new.get()) }
707    }
708
709    /// Returns the spare capacity of the vector as mutable slice of [`MaybeUninit<T>`].
710    ///
711    /// This is useful for low-level manipulation of the vector, often coupled with [`set_len`].
712    ///
713    /// [`set_len`]: Self::set_len
714    pub fn spare_capacity_mut(&mut self) -> &mut MaybeUninitSlice<T> {
715        // SAFETY: returning spare capacity can not make the vector empty
716        unsafe { self.as_mut_vec().spare_capacity_mut() }
717    }
718
719    /// Splits the vector into the non-empty initialized part and the spare capacity part.
720    ///
721    /// This essentially returns [`as_non_empty_mut_slice`] and [`spare_capacity_mut`].
722    ///
723    /// [`as_non_empty_mut_slice`]: Self::as_non_empty_mut_slice
724    /// [`spare_capacity_mut`]: Self::spare_capacity_mut
725    pub const fn split_at_spare_mut(
726        &mut self,
727    ) -> (&mut NonEmptySlice<T>, &mut MaybeUninitSlice<T>) {
728        let len = self.len().get();
729
730        let capacity = self.capacity().get();
731
732        // SAFETY: nothing here changes the length of the vector, therefore it remains non-empty
733        let ptr = unsafe { self.as_mut_vec().as_mut_ptr() };
734
735        // SAFETY: possibly there are uninitialized items past `len`, but the pointer is immediately
736        // cast from `T` to `MaybeUninit<T>`, so this is safe
737        let spare_unsafe_ptr = unsafe { ptr.add(len) };
738
739        // cast from `T` to `MaybeUninit<T>`, making the pointer safe
740        let spare_ptr = spare_unsafe_ptr.cast();
741
742        let spare_len = capacity - len;
743
744        unsafe {
745            // SAFETY: `ptr` is valid for `len` items
746            let init = from_raw_parts_mut(ptr, len);
747
748            // SAFETY: `spare_ptr` points one item past `init`, so they do not overlap
749            let spare = from_raw_parts_mut(spare_ptr, spare_len);
750
751            // SAFETY: `len` is actually non-zero, therefore this is safe
752            let non_empty = NonEmptySlice::from_mut_slice_unchecked(init);
753
754            (non_empty, spare)
755        }
756    }
757}
758
759type MaybeUninitSlice<T> = [MaybeUninit<T>];
760
761impl<T> NonEmptyVec<T> {
762    /// Removes consecutive duplicated items in the vector, as determined by [`PartialEq`].
763    ///
764    /// If the vector is sorted, this will remove all duplicates.
765    pub fn dedup(&mut self)
766    where
767        T: PartialEq,
768    {
769        // SAFETY: deduping can not make the vector empty
770        unsafe {
771            self.as_mut_vec().dedup();
772        }
773    }
774
775    /// Removes consecutive duplicated items in the vector, as determined by the supplied function.
776    ///
777    /// The function provided receives mutable references to the items to be compared.
778    ///
779    /// The items are passed in the opposite order from their order in the vector,
780    /// so if `function(a, b)` returns [`true`], then `a` is removed.
781    ///
782    /// If the vector is sorted, this will remove all duplicates.
783    pub fn dedup_by<F: FnMut(&mut T, &mut T) -> bool>(&mut self, function: F) {
784        // SAFETY: deduping can not make the vector empty
785        unsafe {
786            self.as_mut_vec().dedup_by(function);
787        }
788    }
789
790    /// Removes consecutive duplicated items in the vector, as determined by the keys returned
791    /// from the provided function.
792    ///
793    /// If the vector is sorted, this will remove all duplicates.
794    pub fn dedup_by_key<F: FnMut(&mut T) -> K, K: PartialEq>(&mut self, function: F) {
795        // SAFETY: deduping can not make the vector empty
796        unsafe {
797            self.as_mut_vec().dedup_by_key(function);
798        }
799    }
800}
801
802impl<T: Clone> NonEmptyVec<T> {
803    /// Resizes the vector in-place so that its length is equal to provided [`Size`].
804    ///
805    /// If `new` is greater than [`len`], the vector is extended by the difference,
806    /// with each additional slot filled with `value` that is repeatedly cloned.
807    ///
808    /// Otherwise, the vector is simply truncated.
809    ///
810    /// [`len`]: Self::len
811    pub fn resize(&mut self, new: Size, value: T) {
812        // SAFETY: resizing to non-zero length can not make the vector empty
813        unsafe {
814            self.as_mut_vec().resize(new.get(), value);
815        }
816    }
817
818    /// Extends the vector by cloning all items from the provided value that can be
819    /// converted to [`[T]`](prim@slice).
820    ///
821    /// The `slice` provided is traversed in-order.
822    pub fn extend_from<S: AsRef<[T]>>(&mut self, slice: S) {
823        // SAFETY: extending can not make the vector empty
824        unsafe {
825            self.as_mut_vec().extend_from_slice(slice.as_ref());
826        }
827    }
828
829    /// Given the range within the vector, clones the items in that range
830    /// and appends them to the end of the vector.
831    ///
832    /// # Panics
833    ///
834    /// Panics if the range is out of bounds.
835    pub fn extend_from_within<R: RangeBounds<usize>>(&mut self, range: R) {
836        // SAFETY: extending can not make the vector empty
837        unsafe {
838            self.as_mut_vec().extend_from_within(range);
839        }
840    }
841}
842
843/// Peeks into the last item of the vector mutably.
844///
845/// This `struct` implements [`Deref`] and [`DerefMut`] to the last item of the vector.
846pub struct PeekMut<'a, T> {
847    non_empty: &'a mut NonEmptyVec<T>,
848}
849
850impl<'a, T> PeekMut<'a, T> {
851    /// Constructs [`Self`].
852    pub const fn new(non_empty: &'a mut NonEmptyVec<T>) -> Self {
853        Self { non_empty }
854    }
855
856    /// Removes the last item from the vector and returns it,
857    /// or [`None`] if the vector would become empty.
858    #[must_use]
859    pub fn pop(self) -> Option<T> {
860        self.non_empty.pop()
861    }
862}
863
864impl<T> Deref for PeekMut<'_, T> {
865    type Target = T;
866
867    fn deref(&self) -> &Self::Target {
868        self.non_empty.last()
869    }
870}
871
872impl<T> DerefMut for PeekMut<'_, T> {
873    fn deref_mut(&mut self) -> &mut Self::Target {
874        self.non_empty.last_mut()
875    }
876}
877
878impl<T> NonEmptyVec<T> {
879    /// Constructs [`Self`] containing the single value provided.
880    pub fn single(value: T) -> Self {
881        let vec = vec![value];
882
883        // SAFETY: non-empty construction
884        unsafe { Self::new_unchecked(vec) }
885    }
886
887    /// Constructs [`Self`] with the specified capacity, pushing the value provided.
888    ///
889    /// # Panics
890    ///
891    /// Panics on capacity overflow.
892    pub fn with_capacity_and_value(capacity: Size, value: T) -> Self {
893        let mut vec = Vec::with_capacity(capacity.get());
894
895        vec.push(value);
896
897        // SAFETY: non-empty construction
898        unsafe { Self::new_unchecked(vec) }
899    }
900}
901
902impl<T> NonEmptyVec<T> {
903    /// Returns regular by-reference iterator over the vector.
904    pub fn iter(&self) -> Iter<'_, T> {
905        self.as_slice().iter()
906    }
907
908    /// Returns regular by-mutable-reference iterator over the vector.
909    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
910        self.as_mut_slice().iter_mut()
911    }
912}
913
914impl<T> IntoIterator for NonEmptyVec<T> {
915    type Item = T;
916
917    type IntoIter = IntoIter<T>;
918
919    fn into_iter(self) -> Self::IntoIter {
920        self.into_vec().into_iter()
921    }
922}
923
924impl<'a, T> IntoIterator for &'a NonEmptyVec<T> {
925    type Item = &'a T;
926
927    type IntoIter = Iter<'a, T>;
928
929    fn into_iter(self) -> Self::IntoIter {
930        self.iter()
931    }
932}
933
934impl<'a, T> IntoIterator for &'a mut NonEmptyVec<T> {
935    type Item = &'a mut T;
936
937    type IntoIter = IterMut<'a, T>;
938
939    fn into_iter(self) -> Self::IntoIter {
940        self.iter_mut()
941    }
942}
943
944impl<T> Extend<T> for NonEmptyVec<T> {
945    fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
946        // SAFETY: extending can not make the vector empty
947        unsafe {
948            self.as_mut_vec().extend(iterable);
949        }
950    }
951}
952
953impl<'a, T: Copy + 'a> Extend<&'a T> for NonEmptyVec<T> {
954    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iterable: I) {
955        // SAFETY: extending can not make the vector empty
956        unsafe {
957            self.as_mut_vec().extend(iterable);
958        }
959    }
960}
961
962impl<T: Clone> NonEmptyVec<T> {
963    /// Constructs [`Self`] by repeating the provided value supplied number of times.
964    pub fn repeat(value: T, count: Size) -> Self {
965        let vec = vec![value; count.get()];
966
967        // SAFETY: non-empty construction
968        unsafe { Self::new_unchecked(vec) }
969    }
970}
971
972impl<T> NonEmptyVec<T> {
973    /// Returns non-empty by-reference iterator over the vector.
974    pub fn non_empty_iter(&self) -> NonEmptyIter<'_, T> {
975        // SAFETY: the slice is non-empty by construction
976        unsafe { NonEmptyAdapter::new(self.iter()) }
977    }
978
979    /// Returns non-empty by-mutable-reference iterator over the vector.
980    pub fn non_empty_iter_mut(&mut self) -> NonEmptyIterMut<'_, T> {
981        // SAFETY: the slice is non-empty by construction
982        unsafe { NonEmptyAdapter::new(self.iter_mut()) }
983    }
984}
985
986impl<T> FromNonEmptyIterator<T> for NonEmptyVec<T> {
987    fn from_non_empty_iter<I: IntoNonEmptyIterator<Item = T>>(iterable: I) -> Self {
988        let (item, iterator) = iterable.into_non_empty_iter().consume();
989
990        let mut output = Self::single(item);
991
992        output.extend(iterator);
993
994        output
995    }
996}
997
998impl<T> IntoNonEmptyIterator for NonEmptyVec<T> {
999    type IntoNonEmptyIter = IntoNonEmptyIter<T>;
1000
1001    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
1002        // SAFETY: the slice is non-empty by construction
1003        unsafe { NonEmptyAdapter::new(self.into_iter()) }
1004    }
1005}
1006
1007impl<'a, T> IntoNonEmptyIterator for &'a NonEmptyVec<T> {
1008    type IntoNonEmptyIter = NonEmptyIter<'a, T>;
1009
1010    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
1011        self.non_empty_iter()
1012    }
1013}
1014
1015impl<'a, T> IntoNonEmptyIterator for &'a mut NonEmptyVec<T> {
1016    type IntoNonEmptyIter = NonEmptyIterMut<'a, T>;
1017
1018    fn into_non_empty_iter(self) -> Self::IntoNonEmptyIter {
1019        self.non_empty_iter_mut()
1020    }
1021}