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