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