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