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