not_empty/vec.rs
1use crate::{alloc::*, EmptyError, NonEmptySlice};
2
3#[cfg(feature = "std")]
4use core::num::NonZeroU8;
5use core::{
6 cmp::Ordering,
7 fmt,
8 hash::{Hash, Hasher},
9 mem::MaybeUninit,
10 num::NonZeroUsize,
11 ops, ptr,
12 slice::{self, SliceIndex},
13};
14
15/// A vector that is guaranteed to not be empty.
16///
17/// # [`Deref`](ops::Deref) Behavior
18///
19/// While [`NonEmptyVec<T>`] should be percieved as a smart pointer to a vector,
20/// [`NonEmptyVec<T>`] **does not** dereference to a [`Vec<T>`]. Instead, it
21/// dereferences to a [`NonEmptySlice<T>`], which dereferences to
22/// [`[T]`](prim@slice). The vector methods present are manual implementations
23/// or delegations that preserve the state of the non-empty vector.
24///
25/// # Layout
26///
27/// The layout of a [`NonEmptyVec<T>`] is *idential* to [`Vec<T>`].
28///
29/// # Caveats
30///
31/// Because [`NonEmptyVec<T>`] **does not** dereference to a vector, using one
32/// as a [`&Vec<T>`](Vec) parameter will require the use of [`as_vec`] to
33/// "dereference" the [`NonEmptyVec<T>`] as a [`&Vec<T>`](Vec). This is judged
34/// as acceptable since [`&Vec<T>`](Vec) parameters are rare in the wild.
35///
36/// Also, while you **can not** collect a [`NonEmptyVec<T>`] using
37/// [`Iterator::collect`], you **can** collect a [`NonEmptyVec<T>`] with the
38/// aid of [`IteratorExt`].
39///
40/// However, unlike most other "not empty" libraries, all other interoperability
41/// is remained intact without the need for a new interface. While the previous
42/// two cases are incredibly minor, they still are worth listing and considering
43/// before you adopt usage.
44///
45/// [`as_vec`]: NonEmptyVec::as_vec
46/// [`IteratorExt`]: crate::iter::IteratorExt
47///
48#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
49#[repr(transparent)]
50pub struct NonEmptyVec<T> {
51 pub(crate) inner: Vec<T>,
52}
53
54impl<T> NonEmptyVec<T> {
55 /// This is an incredibly unsafe constructor.
56 ///
57 /// This creates an *empty* [`NonEmptyVec<T>`]... You understand the risks
58 /// of that, right? If I could somehow write `unsafe unsafe`, it would be
59 /// appropriate here.
60 ///
61 /// You **can not** use any methods inspecting the vector *until* you
62 /// populate it with at least one element. To fail in doing so results in
63 /// undefined behavior.
64 ///
65 /// Unlike [`NonEmptyVec::new_unchecked`], there's no debug assertion. For
66 /// your sanity, I hope you know what you're doing.
67 ///
68 /// # Safety
69 ///
70 /// Using the non-empty vector before populating it is undefined behavior.
71 ///
72 /// # Examples
73 ///
74 /// Do not do this:
75 ///
76 /// ```should_panic
77 /// use not_empty::NonEmptyVec;
78 ///
79 /// let empty_nonempty = unsafe { NonEmptyVec::<i32>::empty() };
80 ///
81 /// // Well, well, well. If it isn't the consequences of my actions.
82 /// let first = empty_nonempty.first(); // signal 4 (SIGILL); illegal instruction
83 /// ```
84 ///
85 /// This, however, is technically fine.
86 ///
87 /// ```
88 /// extern crate alloc;
89 ///
90 /// use alloc::collections::TryReserveError;
91 /// use not_empty::prelude::*;
92 ///
93 /// fn process_data(data: &NonEmptySlice<u32>) -> Result<NonEmptyVec<u32>, TryReserveError> {
94 /// let mut output = unsafe { NonEmptyVec::empty() };
95 ///
96 /// // Pre-reserve the memory, exiting if we can't
97 /// output.try_reserve(data.len().get())?;
98 ///
99 /// // Now we know this can't OOM in the middle of our complex work
100 /// output.extend(data.iter().map(|&val| {
101 /// val * 2 + 5 // very complicated
102 /// }));
103 ///
104 /// Ok(output)
105 /// }
106 /// # process_data(¬_empty_vec![1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
107 /// ```
108 #[must_use]
109 #[inline]
110 pub unsafe fn empty() -> Self {
111 NonEmptyVec { inner: Vec::new() }
112 }
113
114 /// An incredibly unsafe constructor. Constructs a new, empty,
115 /// [`NonEmptyVec<T>`] with at least the specified capacity.
116 ///
117 /// You **can not** use any methods inspecting the vector *until* you
118 /// populate it with at least one element. To fail in doing so results in
119 /// undefined behavior.
120 ///
121 /// For more information on capacity, refer to [`Vec::with_capacity`].
122 ///
123 /// # Panics
124 ///
125 /// Panics if the new capacity exceeds [`isize::MAX`] bytes.
126 ///
127 /// # Safety
128 ///
129 /// Using the non-empty vector before populating it is undefined behavior.
130 ///
131 /// # Examples
132 ///
133 /// Do not do this:
134 ///
135 /// ```should_panic
136 /// use core::num::NonZeroUsize;
137 /// use not_empty::NonEmptyVec;
138 ///
139 /// let ten = unsafe { NonZeroUsize::new_unchecked(10) };
140 /// let empty_nonempty = unsafe { NonEmptyVec::<i32>::with_capacity(ten) };
141 ///
142 /// // Well, well, well. If it isn't the consequences of my actions.
143 /// let first = empty_nonempty.first(); // signal 4 (SIGILL); illegal instruction
144 /// ```
145 ///
146 /// This, however, is acceptable. However, be sure that it's absolutely
147 /// required first.
148 ///
149 /// ```
150 /// use core::num::NonZeroUsize;
151 /// use not_empty::NonEmptyVec;
152 ///
153 /// let ten = unsafe { NonZeroUsize::new_unchecked(10) };
154 /// let mut nonempty = unsafe { NonEmptyVec::with_capacity(ten) };
155 /// // Inspecting capacity is literally the only safe operation at this
156 /// // point in the example.
157 /// assert!(nonempty.capacity().get() >= 10);
158 ///
159 /// // These are all done without reallocating...
160 /// for i in 1..=10 {
161 /// nonempty.push(i);
162 /// }
163 ///
164 /// // Further inspection is now okay since elements have been added:
165 /// assert_eq!(nonempty.len().get(), 10);
166 /// assert!(nonempty.capacity().get() >= 10);
167 ///
168 /// // ... but this may make the vector reallocate
169 /// nonempty.push(11);
170 /// assert_eq!(nonempty.len().get(), 11);
171 /// assert!(nonempty.capacity().get() >= 11);
172 ///
173 /// // A vector of a zero-sized type will always over-allocate, since no
174 /// // allocation is necessary.
175 /// let vec_units: NonEmptyVec<()> = unsafe { NonEmptyVec::with_capacity(ten) };
176 /// assert_eq!(vec_units.capacity().get(), usize::MAX);
177 /// ```
178 #[must_use]
179 #[inline]
180 pub unsafe fn with_capacity(capacity: NonZeroUsize) -> Self {
181 NonEmptyVec {
182 inner: Vec::with_capacity(capacity.get()),
183 }
184 }
185
186 /// Creates a new non-empty vector without checking if the given vector is
187 /// not empty.
188 ///
189 /// This is a cost-free conversion.
190 ///
191 /// # Safety
192 ///
193 /// The vector must not be empty.
194 ///
195 /// # Examples
196 ///
197 /// Basic usage:
198 ///
199 /// ```
200 /// use not_empty::NonEmptyVec;
201 ///
202 /// let vec = vec![1, 2, 3];
203 /// let nonempty: NonEmptyVec<_> = unsafe { NonEmptyVec::new_unchecked(vec) };
204 /// ```
205 ///
206 /// For your convenience, consider using
207 /// [`not_empty_vec!`](crate::not_empty_vec) instead:
208 ///
209 /// ```
210 /// use not_empty::not_empty_vec;
211 ///
212 /// let nonempty = not_empty_vec![1, 2, 3];
213 /// ```
214 #[must_use]
215 #[inline]
216 #[track_caller]
217 pub unsafe fn new_unchecked(vec: Vec<T>) -> Self {
218 debug_assert!(
219 !vec.is_empty(),
220 "non-empty vector initialized with an empty vector"
221 );
222 NonEmptyVec { inner: vec }
223 }
224
225 /// Creates a new non-empty vector if the given vector is not empty.
226 ///
227 /// # Errors
228 ///
229 /// Returns an [`EmptyError`] if the given vector is empty.
230 ///
231 /// # Examples
232 ///
233 /// Basic usage:
234 ///
235 /// ```
236 /// use not_empty::NonEmptyVec;
237 ///
238 /// # fn main() -> Result<(), not_empty::EmptyError> {
239 /// let vec = vec![1, 2, 3];
240 /// let nonempty: NonEmptyVec<_> = NonEmptyVec::new(vec)?;
241 /// assert!(nonempty.len().get() == 3);
242 ///
243 /// let empty: Vec<i32> = vec![];
244 /// assert!(NonEmptyVec::new(empty).is_err());
245 /// # Ok(())
246 /// # }
247 /// ```
248 #[inline]
249 pub fn new(vec: Vec<T>) -> Result<Self, EmptyError> {
250 (!vec.is_empty())
251 .then(|| unsafe { NonEmptyVec::new_unchecked(vec) })
252 .ok_or(EmptyError)
253 }
254
255 /// Creates a `NonEmptyVec<T>` directly from the raw components of another
256 /// vector.
257 ///
258 /// # Safety
259 ///
260 /// This is highly unsafe, due to the number of invariants that aren't
261 /// checked:
262 ///
263 /// * `ptr` needs to have been previously allocated via
264 /// [`String`]/[`Vec<T>`] (at least, it's highly likely to be incorrect
265 /// if it wasn't.)
266 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
267 /// (`T` having a less strict alignment is not sufficient, the alignment
268 /// really needs to be equal to satisfy the [`dealloc`] requirement that
269 /// memory must be allocated and deallocated with the same layout.)
270 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes)
271 /// needs to be the same size as the pointer was allocated with. (Because
272 /// similar to alignment, [`dealloc`] must be called with the same layout
273 /// `size`.)
274 /// * `length` needs to be less than or equal to `capacity`.
275 ///
276 /// Violating these may cause problems like corrupting the allocator's
277 /// internal data structures. For example it is normally **not** safe
278 /// to build a [`NonEmptyVec<u8>`] from a pointer to a C `char` array with
279 /// length `size_t`, doing so is only safe if the array was initially
280 /// allocated by a `Vec` or `String`. It's also not safe to build one from a
281 /// `NonEmptyVec<u16>` and its length, because the allocator cares about the
282 /// alignment, and these two types have different alignments. The buffer was
283 /// allocated with alignment 2 (for `u16`), but after turning it into a
284 /// `NonEmptyVec<u8>` it'll be deallocated with alignment 1. To avoid these
285 /// issues, it is often preferable to do casting/transmuting using
286 /// [`slice::from_raw_parts`](crate::slice::from_raw_parts) instead.
287 ///
288 /// The ownership of `ptr` is effectively transferred to the
289 /// [`NonEmptyVec<T>`] which may then deallocate, reallocate or change the
290 /// contents of memory pointed to by the pointer at will. Ensure
291 /// that nothing else uses the pointer after calling this
292 /// function.
293 ///
294 /// [`dealloc`]: std::alloc::GlobalAlloc::dealloc
295 #[must_use]
296 #[inline]
297 pub unsafe fn from_raw_parts(
298 ptr: *mut T,
299 length: NonZeroUsize,
300 capacity: NonZeroUsize,
301 ) -> Self {
302 let vec = Vec::from_raw_parts(ptr, length.get(), capacity.get());
303 NonEmptyVec::new_unchecked(vec)
304 }
305
306 /// Returns a reference to the underlying vector.
307 ///
308 /// # Examples
309 ///
310 /// Basic usage:
311 ///
312 /// ```
313 /// fn needs_vec_ref(vec: &Vec<i32>) {
314 /// // ...
315 /// }
316 ///
317 /// let nonempty = not_empty::vec![1, 2, 3];
318 /// needs_vec_ref(nonempty.as_vec());
319 /// ```
320 #[must_use]
321 #[inline]
322 pub fn as_vec(&self) -> &Vec<T> {
323 &self.inner
324 }
325
326 /// Converts the [`NonEmptyVec<T>`] back into a [`Vec<T>`].
327 ///
328 /// # Examples
329 ///
330 /// Basic usage:
331 ///
332 /// ```
333 /// fn needs_vec(vec: Vec<i32>) {
334 /// // ...
335 /// }
336 ///
337 /// let nonempty = not_empty::vec![1, 2, 3];
338 /// needs_vec(nonempty.into_vec());
339 /// ```
340 #[must_use]
341 #[inline]
342 pub fn into_vec(self) -> Vec<T> {
343 self.inner
344 }
345
346 /// Returns the number of elements the vector can hold without reallocating.
347 ///
348 /// Unlike [`Vec::capacity`], this returns a [`NonZeroUsize`] instead of
349 /// a [`usize`].
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// let nonempty = not_empty::vec![1, 2, 3];
355 /// assert!(nonempty.capacity().get() == 3);
356 /// ```
357 #[must_use]
358 #[inline]
359 pub fn capacity(&self) -> NonZeroUsize {
360 unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
361 }
362
363 /// Reserves capacity for at least `additional` more elements to be inserted
364 /// in the given `NonEmptyVec<T>`. The collection may reserve more space to
365 /// speculatively avoid frequent reallocations. After calling `reserve`,
366 /// capacity will be greater than or equal to `self.len() + additional`.
367 /// Does nothing if capacity is already sufficient.
368 ///
369 /// For more information, refer to [`Vec::reserve`].
370 ///
371 /// # Panics
372 ///
373 /// Panics if the new capacity exceeds `isize::MAX` bytes.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// let mut nonempty = not_empty::vec![1];
379 /// nonempty.reserve(10);
380 /// assert!(nonempty.capacity().get() >= 11);
381 /// ```
382 #[cfg(not(no_global_oom_handling))]
383 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
384 #[inline]
385 pub fn reserve(&mut self, additional: usize) {
386 self.inner.reserve(additional);
387 }
388
389 /// Reserves the minimum capacity for at least `additional` more elements to
390 /// be inserted in the given `NonEmptyVec<T>`. Unlike [`reserve`], this will
391 /// not deliberately over-allocate to speculatively avoid frequent
392 /// allocations. After calling `reserve_exact`, capacity will be greater
393 /// than or equal to `self.len() + additional`. Does nothing if the capacity
394 /// is already sufficient.
395 ///
396 /// Note that the allocator may give the collection more space than it
397 /// requests. Therefore, capacity can not be relied upon to be precisely
398 /// minimal. Prefer [`reserve`] if future insertions are expected.
399 ///
400 /// For more information, refer to [`Vec::reserve_exact`]
401 ///
402 /// [`reserve`]: NonEmptyVec::reserve
403 ///
404 /// # Panics
405 ///
406 /// Panics if the new capacity exceeds `isize::MAX` bytes.
407 ///
408 /// # Examples
409 ///
410 /// ```
411 /// let mut nonempty = not_empty::vec![1];
412 /// nonempty.reserve_exact(10);
413 /// assert!(nonempty.capacity().get() >= 11);
414 /// ```
415 #[cfg(not(no_global_oom_handling))]
416 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
417 #[inline]
418 pub fn reserve_exact(&mut self, additional: usize) {
419 self.inner.reserve_exact(additional);
420 }
421
422 /// Tries to reserve capacity for at least `additional` more elements to be
423 /// inserted in the given `NonEmptyVec<T>`. The collection may reserve more
424 /// space to speculatively avoid frequent reallocations. After calling
425 /// `try_reserve`, capacity will be greater than or equal to
426 /// `self.len() + additional` if it returns `Ok(())`. Does nothing if
427 /// capacity is already sufficient.
428 ///
429 /// For more information, refer to [`Vec::try_reserve`].
430 ///
431 /// # Errors
432 ///
433 /// If the capacity overflows, or the allocator reports a failure, then an error
434 /// is returned.
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// # extern crate alloc;
440 /// use alloc::collections::TryReserveError;
441 /// use not_empty::prelude::*;
442 ///
443 /// fn process_data(data: &NonEmptySlice<u32>) -> Result<NonEmptyVec<u32>, TryReserveError> {
444 /// let mut output = unsafe { NonEmptyVec::empty() };
445 ///
446 /// // Pre-reserve the memory, exiting if we can't
447 /// output.try_reserve(data.len().get())?;
448 ///
449 /// // Now we know this can't OOM in the middle of our complex work
450 /// output.extend(data.iter().map(|&val| {
451 /// val * 2 + 5 // very complicated
452 /// }));
453 ///
454 /// Ok(output)
455 /// }
456 /// # process_data(¬_empty_vec![1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
457 /// ```
458 #[inline]
459 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
460 self.inner.try_reserve(additional)
461 }
462
463 /// Tries to reserve the minimum capacity for at least `additional`
464 /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
465 /// this will not deliberately over-allocate to speculatively avoid frequent
466 /// allocations. After calling `try_reserve_exact`, capacity will be greater
467 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
468 /// Does nothing if the capacity is already sufficient.
469 ///
470 /// Note that the allocator may give the collection more space than it
471 /// requests. Therefore, capacity can not be relied upon to be precisely
472 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
473 ///
474 /// [`try_reserve`]: NonEmptyVec::try_reserve
475 ///
476 /// # Errors
477 ///
478 /// If the capacity overflows, or the allocator reports a failure, then an error
479 /// is returned.
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// # extern crate alloc;
485 /// use alloc::collections::TryReserveError;
486 /// use not_empty::prelude::*;
487 ///
488 /// fn process_data(data: &NonEmptySlice<u32>) -> Result<NonEmptyVec<u32>, TryReserveError> {
489 /// let mut output = unsafe { NonEmptyVec::empty() };
490 ///
491 /// // Pre-reserve the memory, exiting if we can't
492 /// output.try_reserve_exact(data.len().get())?;
493 ///
494 /// // Now we know this can't OOM in the middle of our complex work
495 /// output.extend(data.iter().map(|&val| {
496 /// val * 2 + 5 // very complicated
497 /// }));
498 ///
499 /// Ok(output)
500 /// }
501 /// # process_data(¬_empty_vec![1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
502 /// ```
503 #[inline]
504 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
505 self.inner.try_reserve_exact(additional)
506 }
507
508 /// Shrinks the capacity of the vector as much as possible.
509 ///
510 /// It will drop down as close as possible to the length but the allocator
511 /// may still inform the vector that there is space for a few more elements.
512 ///
513 /// For more information, refer to [`Vec::shrink_to_fit`].
514 ///
515 /// # Examples
516 ///
517 /// ```
518 /// use core::num::NonZeroUsize;
519 /// use not_empty::NonEmptyVec;
520 ///
521 /// let mut nonempty = unsafe { NonEmptyVec::with_capacity(NonZeroUsize::new_unchecked(10)) };
522 /// nonempty.extend([1, 2, 3]);
523 /// assert_eq!(nonempty.capacity().get(), 10);
524 /// nonempty.shrink_to_fit();
525 /// assert!(nonempty.capacity().get() >= 3);
526 /// ```
527 #[cfg(not(no_global_oom_handling))]
528 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
529 #[inline]
530 pub fn shrink_to_fit(&mut self) {
531 self.inner.shrink_to_fit();
532 }
533
534 /// Shrinks the capacity of the vector with a lower bound.
535 ///
536 /// The capacity will remain at least as large as both the length and the
537 /// supplied value.
538 ///
539 /// If the current capacity is less than the lower limit, this is a no-op.
540 ///
541 /// For more information, refer to [`Vec::shrink_to`].
542 ///
543 /// # Examples
544 ///
545 /// ```
546 /// use core::num::NonZeroUsize;
547 /// use not_empty::NonEmptyVec;
548 ///
549 /// let mut nonempty = unsafe { NonEmptyVec::with_capacity(NonZeroUsize::new_unchecked(10)) };
550 /// nonempty.extend([1, 2, 3]);
551 /// assert_eq!(nonempty.capacity().get(), 10);
552 ///
553 /// nonempty.shrink_to(4);
554 /// assert!(nonempty.capacity().get() >= 4);
555 ///
556 /// nonempty.shrink_to(0);
557 /// assert!(nonempty.capacity().get() >= 3);
558 /// ```
559 #[cfg(not(no_global_oom_handling))]
560 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
561 #[inline]
562 pub fn shrink_to(&mut self, min_capacity: usize) {
563 self.inner.shrink_to(min_capacity);
564 }
565
566 /// Converts this [`NonEmptyVec<T>`] into [`Box<NonEmptySlice<T>>`].
567 ///
568 /// This will drop any excess capacity.
569 ///
570 /// # Examples
571 ///
572 /// Basic usage:
573 ///
574 /// ```
575 /// let nonempty = not_empty::vec![1, 2, 3];
576 /// let slice = nonempty.into_boxed_slice();
577 /// ```
578 ///
579 /// Any excess capacity is removed:
580 ///
581 /// ```
582 /// use core::num::NonZeroUsize;
583 /// use not_empty::{NonEmptySlice, NonEmptyVec};
584 ///
585 /// let mut nonempty = unsafe { NonEmptyVec::with_capacity(NonZeroUsize::new_unchecked(10)) };
586 /// nonempty.extend([1, 2 ,3]);
587 /// assert_eq!(nonempty.capacity().get(), 10);
588 ///
589 /// let slice: Box<NonEmptySlice<_>> = nonempty.into_boxed_slice();
590 /// assert_eq!(slice.into_vec().capacity().get(), 3);
591 /// ```
592 #[cfg(not(no_global_oom_handling))]
593 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
594 #[must_use]
595 #[inline]
596 pub fn into_boxed_slice(self) -> Box<NonEmptySlice<T>> {
597 let b = self.inner.into_boxed_slice();
598 let raw = Box::into_raw(b) as *mut NonEmptySlice<T>;
599 unsafe { Box::from_raw(raw) }
600 }
601
602 /// Shortens the vector, keeping the first `len` elements and dropping the
603 /// rest.
604 ///
605 /// If `len` is greater than the vector's current length, this has no
606 /// effect.
607 ///
608 /// The [`drain`](NonEmptyVec::drain) method can emulate `truncate`, but
609 /// causes the excess elements to be returned instead of dropped.
610 ///
611 /// This method has no effect on the allocated capacity of the vector.
612 ///
613 /// # Examples
614 ///
615 /// Truncating a five element vector to two elements:
616 ///
617 /// ```
618 /// use core::num::NonZeroUsize;
619 ///
620 /// let mut vec = not_empty::vec![1, 2, 3, 4, 5];
621 /// vec.truncate(unsafe { NonZeroUsize::new_unchecked(2) });
622 /// assert_eq!(vec, [1, 2]);
623 /// ```
624 ///
625 /// No truncation occurs when `len` is greater than the vector's current
626 /// length:
627 ///
628 /// ```
629 /// use core::num::NonZeroUsize;
630 ///
631 /// let mut vec = not_empty::vec![1, 2, 3];
632 /// vec.truncate(unsafe { NonZeroUsize::new_unchecked(8) });
633 /// assert_eq!(vec, [1, 2, 3]);
634 /// ```
635 #[inline]
636 pub fn truncate(&mut self, len: NonZeroUsize) {
637 self.inner.truncate(len.get());
638 }
639
640 /// Extracts a [`NonEmptySlice`] containing the entire vector.
641 #[must_use]
642 #[inline]
643 pub fn as_slice(&self) -> &NonEmptySlice<T> {
644 unsafe { NonEmptySlice::new_unchecked(&self.inner) }
645 }
646
647 /// Extracts a mutable [`NonEmptySlice`] containing the entire vector.
648 #[must_use]
649 #[inline]
650 pub fn as_mut_slice(&mut self) -> &mut NonEmptySlice<T> {
651 unsafe { NonEmptySlice::new_mut_unchecked(&mut self.inner) }
652 }
653
654 /// Returns a raw pointer to the vector’s buffer, or a dangling raw pointer
655 /// valid for zero sized reads if the vector didn’t allocate.
656 ///
657 /// For more information, refer to [`Vec::as_ptr`].
658 #[must_use]
659 #[inline]
660 pub fn as_ptr(&self) -> *const T {
661 self.inner.as_ptr()
662 }
663
664 /// Returns an unsafe mutable pointer to the vector’s buffer, or a dangling
665 /// raw pointer valid for zero sized reads if the vector didn’t allocate.
666 ///
667 /// For more information, refer to [`Vec::as_mut_ptr`].
668 #[must_use]
669 #[inline]
670 pub fn as_mut_ptr(&mut self) -> *mut T {
671 self.inner.as_mut_ptr()
672 }
673
674 /// Forces the length of the vector to `new_len`.
675 ///
676 /// For more information, refer to [`Vec::set_len`].
677 ///
678 /// # Safety
679 ///
680 /// * `new_len` must be less than or equal to
681 /// [`capacity()`](NonEmptyVec::capacity).
682 /// * The elements at `old_len..new_len` must be initialized.
683 #[inline]
684 pub unsafe fn set_len(&mut self, new_len: NonZeroUsize) {
685 debug_assert!(new_len < self.capacity());
686 self.inner.set_len(new_len.get());
687 }
688
689 #[inline]
690 #[track_caller]
691 fn assert_nonempty(&self, method_name: &'static str) {
692 #[cfg_attr(panic = "abort", inline)]
693 #[cfg_attr(not(panic = "abort"), inline(never))]
694 #[cold]
695 #[track_caller]
696 fn assert_failed(method_name: &'static str) {
697 panic!("{method_name} left the NonEmptyVec empty");
698 }
699
700 if cfg!(debug_assertions) && self.inner.is_empty() {
701 assert_failed(method_name);
702 }
703 }
704
705 /// Removes an element from the vector and returns it.
706 ///
707 /// The removed element is replaced by the last element of the vector..
708 ///
709 /// This does not preserve ordering, but is *O*(1). If you need to preserve
710 /// the element order, use [`remove`](NonEmptyVec::remove) instead.
711 ///
712 /// # Panics
713 ///
714 /// Panics if `index` is out of bounds.
715 ///
716 /// # Safety
717 ///
718 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
719 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
720 /// whether or not a [`NonEmptyVec`] is really the right choice for your
721 /// application.
722 #[must_use]
723 #[inline]
724 #[track_caller]
725 pub unsafe fn swap_remove(&mut self, index: usize) -> T {
726 let element = self.inner.swap_remove(index);
727 self.assert_nonempty("swap_remove");
728 element
729 }
730
731 /// Inserts an element at position `index` within the vector, shifting all
732 /// elements after it to the right.
733 ///
734 /// For more information, refer to [`Vec::insert`].
735 ///
736 /// # Panics
737 ///
738 /// Panics if `index > len`.
739 #[cfg(not(no_global_oom_handling))]
740 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
741 #[inline]
742 #[track_caller]
743 pub fn insert(&mut self, index: usize, element: T) {
744 self.inner.insert(index, element);
745 }
746
747 /// Removes and returns the element at position `index` within the vector,
748 /// shifting all elements after it to the left.
749 ///
750 /// Because this shifts over the remaining elements, it has a worst-case
751 /// performance of *O*(*n*). If you don't need the order of elements
752 /// to be preserved, use [`swap_remove`](NonEmptyVec::swap_remove) instead.
753 ///
754 /// For more information, refer to [`Vec::swap_remove`].
755 ///
756 /// # Panics
757 ///
758 /// Panics if `index` is out of bounds.
759 ///
760 /// # Safety
761 ///
762 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
763 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
764 /// whether or not a [`NonEmptyVec`] is really the right choice for your
765 /// application.
766 #[must_use]
767 #[inline]
768 #[track_caller]
769 pub unsafe fn remove(&mut self, index: usize) -> T {
770 let element = self.inner.remove(index);
771 self.assert_nonempty("remove");
772 element
773 }
774
775 /// Retains only the elements specified by the predicate.
776 ///
777 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
778 /// This method operates in place, visiting each element exactly once in the
779 /// original order, and preserves the order of the retained elements.
780 ///
781 /// For more information, refer to [`Vec::retain`].
782 ///
783 /// # Safety
784 ///
785 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
786 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
787 /// whether or not a [`NonEmptyVec`] is really the right choice for your
788 /// application.
789 #[inline]
790 #[track_caller]
791 pub unsafe fn retain<F>(&mut self, f: F)
792 where
793 F: FnMut(&T) -> bool,
794 {
795 self.inner.retain(f);
796 self.assert_nonempty("retain");
797 }
798
799 /// Retains only the elements specified by the predicate, passing a mutable
800 /// reference to it.
801 ///
802 /// In other words, remove all elements `e` such that `f(&mut e)` returns
803 /// `false`. This method operates in place, visiting each element exactly
804 /// once in the original order, and preserves the order of the retained
805 /// elements.
806 ///
807 /// For more information, refer to [`Vec::retain_mut`].
808 ///
809 /// # Safety
810 ///
811 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
812 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
813 /// whether or not a [`NonEmptyVec`] is really the right choice for your
814 /// application.
815 #[inline]
816 #[track_caller]
817 pub unsafe fn retain_mut<F>(&mut self, f: F)
818 where
819 F: FnMut(&mut T) -> bool,
820 {
821 self.inner.retain_mut(f);
822 self.assert_nonempty("retain_mut");
823 }
824
825 /// Removes all but the first of consecutive elements in the vector that
826 /// resolve to the same key.
827 ///
828 /// If the vector is sorted, this removes all duplicates.
829 ///
830 /// For more information, refer to [`Vec::dedup_by_key`].
831 #[inline]
832 pub fn dedup_by_key<F, K>(&mut self, key: F)
833 where
834 F: FnMut(&mut T) -> K,
835 K: PartialEq,
836 {
837 self.inner.dedup_by_key(key);
838 }
839
840 /// Removes all but the first of consecutive elements in the vector
841 /// satisfying a given equality relation.
842 ///
843 /// The `same_bucket` function is passed references to two elements from the
844 /// vector and must determine if the elements compare equal. The elements
845 /// are passed in opposite order from their order in the slice, so if
846 /// `same_bucket(a, b)` returns `true`, `a` is removed.
847 ///
848 /// If the vector is sorted, this removes all duplicates.
849 ///
850 /// For more information, refer to [`Vec::dedup_by`].
851 #[inline]
852 pub fn dedup_by<F>(&mut self, same_bucket: F)
853 where
854 F: FnMut(&mut T, &mut T) -> bool,
855 {
856 self.inner.dedup_by(same_bucket);
857 }
858
859 /// Appends an element to the back of a collection.
860 ///
861 /// For more information, refer to [`Vec::push`].
862 ///
863 /// # Panics
864 ///
865 /// Panics if the new capacity exceeds [`isize::MAX`] bytes.
866 #[cfg(not(no_global_oom_handling))]
867 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
868 #[inline]
869 #[track_caller]
870 pub fn push(&mut self, value: T) {
871 self.inner.push(value);
872 }
873
874 /// Removes the last element from a vector and returns it.
875 ///
876 /// Unlike [`Vec::pop`], this is never an [`Option`].
877 ///
878 /// # Safety
879 ///
880 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
881 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
882 /// whether or not a [`NonEmptyVec`] is really the right choice for your
883 /// application.
884 #[inline]
885 #[track_caller]
886 pub unsafe fn pop(&mut self) -> T {
887 let element = self.inner.pop().unwrap_unchecked();
888 self.assert_nonempty("pop");
889 element
890 }
891
892 /// Moves all the elements of `other` into `self`, leaving `other` empty.
893 ///
894 /// For more information, refer to [`Vec::append`].
895 ///
896 /// # Panics
897 ///
898 /// Panics if the new capacity exceeds `isize::MAX` bytes.
899 #[cfg(not(no_global_oom_handling))]
900 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
901 #[inline]
902 #[track_caller]
903 pub fn append(&mut self, other: &mut Vec<T>) {
904 self.inner.append(other);
905 }
906
907 /// Removes the specified range from the vector in bulk, returning all
908 /// removed elements as an iterator. If the iterator is dropped before
909 /// being fully consumed, it drops the remaining removed elements.
910 ///
911 /// The returned iterator keeps a mutable borrow on the vector to optimize
912 /// its implementation.
913 ///
914 /// # Panics
915 ///
916 /// Panics if the starting point is greater than the end point or if
917 /// the end point is greater than the length of the vector.
918 ///
919 /// # Safety
920 ///
921 /// This can not leave the [`NonEmptyVec`] empty. If it does, on debug
922 /// builds, it will panic. Otherwise, it is undefined behavior. Consider
923 /// whether or not a [`NonEmptyVec`] is really the right choice for your
924 /// application.
925 ///
926 /// # Leaking
927 ///
928 /// If the returned iterator goes out of scope without being dropped (due to
929 /// [`mem::forget`], for example), the vector may have lost and leaked
930 /// elements arbitrarily, including elements outside the range.
931 ///
932 ///
933 /// [`mem::forget`]: core::mem::forget
934 #[inline]
935 #[track_caller]
936 pub unsafe fn drain<R>(&mut self, range: R) -> vec::Drain<'_, T>
937 where
938 R: ops::RangeBounds<usize>,
939 {
940 // TODO: Use slice::range once stable
941 #[must_use]
942 #[track_caller]
943 fn slice_range_hack<R>(range: R, bounds: ops::RangeTo<usize>) -> ops::Range<usize>
944 where
945 R: ops::RangeBounds<usize>,
946 {
947 #[cfg_attr(panic = "abort", inline)]
948 #[cfg_attr(not(panic = "abort"), inline(never))]
949 #[cold]
950 #[track_caller]
951 const fn slice_start_index_overflow_fail() -> ! {
952 panic!("attempted to index slice from after maximum usize");
953 }
954
955 #[cfg_attr(panic = "abort", inline)]
956 #[cfg_attr(not(panic = "abort"), inline(never))]
957 #[cold]
958 #[track_caller]
959 const fn slice_end_index_overflow_fail() -> ! {
960 panic!("attempted to index slice up to maximum usize");
961 }
962
963 #[cfg_attr(panic = "abort", inline)]
964 #[cfg_attr(not(panic = "abort"), inline(never))]
965 #[cold]
966 #[track_caller]
967 const fn slice_index_order_fail() -> ! {
968 panic!("slice index start is larger than end");
969 }
970 #[cfg_attr(panic = "abort", inline)]
971 #[cfg_attr(not(panic = "abort"), inline(never))]
972 #[cold]
973 #[track_caller]
974 const fn slice_end_index_len_fail() -> ! {
975 panic!("slice end index is out of range for slice");
976 }
977
978 let len = bounds.end;
979 let start = match range.start_bound() {
980 ops::Bound::Included(&n) => n,
981 ops::Bound::Excluded(&n) => n
982 .checked_add(1)
983 .unwrap_or_else(|| slice_start_index_overflow_fail()),
984 ops::Bound::Unbounded => 0,
985 };
986 let end = match range.end_bound() {
987 ops::Bound::Included(&n) => n
988 .checked_add(1)
989 .unwrap_or_else(|| slice_end_index_overflow_fail()),
990 ops::Bound::Excluded(&n) => n,
991 ops::Bound::Unbounded => len,
992 };
993
994 if start > end {
995 slice_index_order_fail();
996 }
997 if end > len {
998 slice_end_index_len_fail();
999 }
1000
1001 ops::Range { start, end }
1002 }
1003
1004 #[cfg_attr(panic = "abort", inline)]
1005 #[cfg_attr(not(panic = "abort"), inline(never))]
1006 #[cold]
1007 #[track_caller]
1008 const fn assert_failed() -> ! {
1009 panic!("attempted to drain the entire vector");
1010 }
1011
1012 let len = self.inner.len();
1013 let normalized_range = slice_range_hack(range, ..len);
1014
1015 if cfg!(debug_assertions)
1016 && normalized_range.start == 0
1017 && normalized_range.end == (len - 1)
1018 {
1019 assert_failed();
1020 }
1021
1022 self.inner.drain(normalized_range)
1023 }
1024
1025 /// Returns the number of elements in the vector, also referred to as its
1026 /// 'length'.
1027 ///
1028 /// Unlike [`Vec::len`], this returrns a [`NonZeroUsize`].
1029 ///
1030 /// For more information, refer to [`Vec::len`].
1031 ///
1032 /// # Examples
1033 ///
1034 /// Basic usage:
1035 ///
1036 /// ```
1037 /// let a = not_empty::vec![1, 2, 3];
1038 /// assert_eq!(a.len().get(), 3);
1039 /// ```
1040 #[must_use]
1041 #[inline]
1042 pub fn len(&self) -> NonZeroUsize {
1043 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
1044 }
1045
1046 /// Splits the collection into two at the given index.
1047 ///
1048 /// Returns a newly allocated vector containing the elements in the range
1049 /// `[at, len)`. After the call, the original vector will be left containing
1050 /// the elements `[0, at)` with its previous capacity unchanged.
1051 ///
1052 /// Unlike [`Vec::split_off`], it's impossible to split at index zero.
1053 ///
1054 /// # Panics
1055 ///
1056 /// Panics if `at > len`.
1057 #[cfg(not(no_global_oom_handling))]
1058 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1059 #[must_use = "use `.truncate()` if you don't need the other half"]
1060 #[inline]
1061 #[track_caller]
1062 pub fn split_off(&mut self, at: NonZeroUsize) -> Vec<T> {
1063 self.inner.split_off(at.get())
1064 }
1065
1066 /// Resizes the `NonEmptyVec` in-place so that `len` is equal to `new_len`.
1067 ///
1068 /// If `new_len` is greater than `len`, the `NonEmptyVec` is extended by the
1069 /// difference, with each additional slot filled with the result of
1070 /// calling the closure `f`. The return values from `f` will end up
1071 /// in the `NonEmptyVec` in the order they have been generated.
1072 ///
1073 /// If `new_len` is less than `len`, the `NonEmptyVec` is simply truncated.
1074 ///
1075 /// This method uses a closure to create new values on every push. If
1076 /// you'd rather [`Clone`] a given value, use [`NonEmptyVec::resize`]. If
1077 /// you want to use the [`Default`] trait to generate values, you can
1078 /// pass [`Default::default`] as the second argument.
1079 ///
1080 /// For more information, refer to [`Vec::resize_with`].
1081 #[cfg(not(no_global_oom_handling))]
1082 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1083 #[inline]
1084 pub fn resize_with<F>(&mut self, new_len: NonZeroUsize, f: F)
1085 where
1086 F: FnMut() -> T,
1087 {
1088 self.inner.resize_with(new_len.get(), f);
1089 }
1090
1091 /// Consumes and leaks the `NonEmptyVec`, returning a mutable reference to
1092 /// the contents, `&'a mut NonEmptySlice<T>`. Note that the type `T` must
1093 /// outlive the chosen lifetime `'a`. If the type has only static
1094 /// references, or none at all, then this may be chosen to be `'static`.
1095 ///
1096 /// As of Rust 1.57, this method does not reallocate or shrink the
1097 /// `NonEmptyVec`, so the leaked allocation may include unused capacity that
1098 /// is not part of the returned slice.
1099 ///
1100 /// This function is mainly useful for data that lives for the remainder of
1101 /// the program's life. Dropping the returned reference will cause a memory
1102 /// leak.
1103 ///
1104 /// For more information, refer to [`Vec::leak`].
1105 #[cfg(not(no_global_oom_handling))]
1106 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1107 #[must_use]
1108 #[inline]
1109 pub fn leak<'a>(self) -> &'a mut NonEmptySlice<T> {
1110 unsafe { NonEmptySlice::new_mut_unchecked(self.inner.leak()) }
1111 }
1112
1113 /// Returns the remaining spare capacity of the vector as a slice of
1114 /// `MaybeUninit<T>`.
1115 ///
1116 /// For more information, refer to [`Vec::spare_capacity_mut`].
1117 #[must_use]
1118 #[inline]
1119 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1120 self.inner.spare_capacity_mut()
1121 }
1122}
1123
1124impl<T: Clone> NonEmptyVec<T> {
1125 /// Resizes the `NonEmptyVec` in-place so that `len` is equal to `new_len`.
1126 ///
1127 /// If `new_len` is greater than `len`, the `NonEmptyVec` is extended by the
1128 /// difference, with each additional slot filled with `value`.
1129 /// If `new_len` is less than `len`, the `NonEmptyVec` is simply truncated.
1130 ///
1131 /// This method requires `T` to implement [`Clone`],
1132 /// in order to be able to clone the passed value.
1133 /// If you need more flexibility (or want to rely on [`Default`] instead of
1134 /// [`Clone`]), use [`NonEmptyVec::resize_with`].
1135 /// If you only need to resize to a smaller size, use
1136 /// [`NonEmptyVec::truncate`].
1137 ///
1138 /// For more information, refer to [`Vec::resize`].
1139 #[cfg(not(no_global_oom_handling))]
1140 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1141 #[inline]
1142 pub fn resize(&mut self, new_len: NonZeroUsize, value: T) {
1143 self.inner.resize(new_len.get(), value);
1144 }
1145
1146 /// Clones and appends all elements in a slice to the `NonEmptyVec`.
1147 ///
1148 /// Iterates over the slice `other`, clones each element, and then appends
1149 /// it to this `NonEmptyVec`. The `other` slice is traversed in-order.
1150 ///
1151 /// Note that this function is same as [`extend`] except that it is
1152 /// specialized to work with slices instead. If and when Rust gets
1153 /// specialization this function will likely be deprecated (but still
1154 /// available).
1155 ///
1156 /// For more information, refer to [`Vec::extend_from_slice`].
1157 ///
1158 /// [`extend`]: NonEmptyVec::extend
1159 #[cfg(not(no_global_oom_handling))]
1160 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1161 #[inline]
1162 pub fn extend_from_slice(&mut self, other: &[T]) {
1163 self.inner.extend_from_slice(other);
1164 }
1165
1166 /// Copies elements from `src` range to the end of the vector.
1167 ///
1168 /// For more information, refer to [`Vec::extend_from_within`].
1169 ///
1170 /// # Panics
1171 ///
1172 /// Panics if the starting point is greater than the end point or if
1173 /// the end point is greater than the length of the vector.
1174 #[cfg(not(no_global_oom_handling))]
1175 #[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1176 #[inline]
1177 #[track_caller]
1178 pub fn extend_from_within<R>(&mut self, src: R)
1179 where
1180 R: ops::RangeBounds<usize>,
1181 {
1182 self.inner.extend_from_within(src);
1183 }
1184}
1185
1186impl<T: PartialEq> NonEmptyVec<T> {
1187 /// Removes consecutive repeated elements in the vector according to the
1188 /// [`PartialEq`] trait implementation.
1189 ///
1190 /// If the vector is sorted, this removes all duplicates.
1191 ///
1192 /// For more information, refer to [`Vec::dedup`].
1193 #[inline]
1194 pub fn dedup(&mut self) {
1195 self.inner.dedup();
1196 }
1197}
1198
1199////////////////////////////////////////////////////////////////////////////////
1200// Formatting
1201////////////////////////////////////////////////////////////////////////////////
1202
1203impl<T> fmt::Debug for NonEmptyVec<T>
1204where
1205 T: fmt::Debug,
1206{
1207 #[inline]
1208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1209 fmt::Debug::fmt(&self.inner, f)
1210 }
1211}
1212
1213////////////////////////////////////////////////////////////////////////////////
1214// Cloning
1215////////////////////////////////////////////////////////////////////////////////
1216
1217impl<T> Clone for NonEmptyVec<T>
1218where
1219 T: Clone,
1220{
1221 #[inline]
1222 fn clone(&self) -> Self {
1223 let vec = self.inner.clone();
1224 unsafe { NonEmptyVec::new_unchecked(vec) }
1225 }
1226
1227 #[inline]
1228 fn clone_from(&mut self, source: &Self) {
1229 self.inner.clone_from(&source.inner);
1230 }
1231}
1232
1233////////////////////////////////////////////////////////////////////////////////
1234// Dereferencing
1235////////////////////////////////////////////////////////////////////////////////
1236
1237impl<T> ops::Deref for NonEmptyVec<T> {
1238 type Target = NonEmptySlice<T>;
1239
1240 #[inline]
1241 fn deref(&self) -> &Self::Target {
1242 self.as_slice()
1243 }
1244}
1245
1246impl<T> ops::DerefMut for NonEmptyVec<T> {
1247 #[inline]
1248 fn deref_mut(&mut self) -> &mut Self::Target {
1249 self.as_mut_slice()
1250 }
1251}
1252
1253////////////////////////////////////////////////////////////////////////////////
1254// `as_*` traits
1255////////////////////////////////////////////////////////////////////////////////
1256
1257impl<T> AsRef<[T]> for NonEmptyVec<T> {
1258 #[inline]
1259 fn as_ref(&self) -> &[T] {
1260 self.as_slice().as_ref()
1261 }
1262}
1263
1264impl<T> AsMut<[T]> for NonEmptyVec<T> {
1265 #[inline]
1266 fn as_mut(&mut self) -> &mut [T] {
1267 self.as_mut_slice().as_mut()
1268 }
1269}
1270
1271#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1272impl<T> AsRef<NonEmptySlice<T>> for NonEmptyVec<T> {
1273 #[inline]
1274 fn as_ref(&self) -> &NonEmptySlice<T> {
1275 self.as_slice()
1276 }
1277}
1278
1279#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1280impl<T> AsMut<NonEmptySlice<T>> for NonEmptyVec<T> {
1281 #[inline]
1282 fn as_mut(&mut self) -> &mut NonEmptySlice<T> {
1283 self.as_mut_slice()
1284 }
1285}
1286
1287impl<T> AsRef<Vec<T>> for NonEmptyVec<T> {
1288 #[inline]
1289 fn as_ref(&self) -> &Vec<T> {
1290 &self.inner
1291 }
1292}
1293
1294////////////////////////////////////////////////////////////////////////////////
1295// `borrow` implementations
1296////////////////////////////////////////////////////////////////////////////////
1297
1298impl<T> Borrow<[T]> for NonEmptyVec<T> {
1299 #[inline]
1300 fn borrow(&self) -> &[T] {
1301 self
1302 }
1303}
1304
1305impl<T> BorrowMut<[T]> for NonEmptyVec<T> {
1306 #[inline]
1307 fn borrow_mut(&mut self) -> &mut [T] {
1308 self
1309 }
1310}
1311
1312#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1313impl<T> Borrow<NonEmptySlice<T>> for NonEmptyVec<T> {
1314 #[inline]
1315 fn borrow(&self) -> &NonEmptySlice<T> {
1316 self
1317 }
1318}
1319
1320#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1321impl<T> BorrowMut<NonEmptySlice<T>> for NonEmptyVec<T> {
1322 #[inline]
1323 fn borrow_mut(&mut self) -> &mut NonEmptySlice<T> {
1324 self
1325 }
1326}
1327
1328////////////////////////////////////////////////////////////////////////////////
1329// Index operations
1330////////////////////////////////////////////////////////////////////////////////
1331
1332impl<T, I> ops::Index<I> for NonEmptyVec<T>
1333where
1334 I: SliceIndex<[T]>,
1335{
1336 type Output = I::Output;
1337
1338 #[inline]
1339 fn index(&self, index: I) -> &Self::Output {
1340 ops::Index::index(&self.inner, index)
1341 }
1342}
1343
1344impl<T, I> ops::IndexMut<I> for NonEmptyVec<T>
1345where
1346 I: SliceIndex<[T]>,
1347{
1348 #[inline]
1349 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1350 ops::IndexMut::index_mut(&mut self.inner, index)
1351 }
1352}
1353
1354////////////////////////////////////////////////////////////////////////////////
1355// Iterator traits
1356////////////////////////////////////////////////////////////////////////////////
1357
1358#[cfg(not(no_global_oom_handling))]
1359#[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1360impl<'a, T> Extend<&'a T> for NonEmptyVec<T>
1361where
1362 T: 'a + Copy,
1363{
1364 #[inline]
1365 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1366 self.inner.extend(iter);
1367 }
1368}
1369
1370#[cfg(not(no_global_oom_handling))]
1371#[cfg_attr(doc_cfg, doc(cfg(not(no_global_oom_handling))))]
1372impl<T> Extend<T> for NonEmptyVec<T> {
1373 #[inline]
1374 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1375 self.inner.extend(iter);
1376 }
1377}
1378
1379impl<'a, T> IntoIterator for &'a NonEmptyVec<T> {
1380 type Item = &'a T;
1381 type IntoIter = slice::Iter<'a, T>;
1382
1383 #[inline]
1384 fn into_iter(self) -> Self::IntoIter {
1385 self.iter()
1386 }
1387}
1388
1389impl<'a, T> IntoIterator for &'a mut NonEmptyVec<T> {
1390 type Item = &'a mut T;
1391 type IntoIter = slice::IterMut<'a, T>;
1392
1393 #[inline]
1394 fn into_iter(self) -> Self::IntoIter {
1395 self.iter_mut()
1396 }
1397}
1398
1399impl<T> IntoIterator for NonEmptyVec<T> {
1400 type Item = T;
1401 type IntoIter = vec::IntoIter<T>;
1402
1403 #[inline]
1404 fn into_iter(self) -> Self::IntoIter {
1405 self.inner.into_iter()
1406 }
1407}
1408
1409////////////////////////////////////////////////////////////////////////////////
1410/// Collection equivalence
1411////////////////////////////////////////////////////////////////////////////////
1412
1413impl<T, U> PartialEq<VecDeque<U>> for NonEmptyVec<T>
1414where
1415 T: PartialEq<U>,
1416{
1417 // This is a workaround since rustlib's PartialEq implementation isn't
1418 // symmetric.
1419 fn eq(&self, other: &VecDeque<U>) -> bool {
1420 if self.inner.len() != other.len() {
1421 return false;
1422 }
1423
1424 let (oa, ob) = other.as_slices();
1425 let (sa, sb) = self.split_at(oa.len());
1426
1427 sa == oa && sb == ob
1428 }
1429}
1430
1431impl<T, U> PartialEq<NonEmptyVec<U>> for VecDeque<T>
1432where
1433 T: PartialEq<U>,
1434{
1435 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1436 self == &other.inner
1437 }
1438}
1439
1440impl<T, U> PartialEq<NonEmptyVec<U>> for NonEmptyVec<T>
1441where
1442 T: PartialEq<U>,
1443{
1444 #[inline]
1445 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1446 self.inner == other.inner
1447 }
1448}
1449
1450impl<T, U> PartialEq<Vec<U>> for NonEmptyVec<T>
1451where
1452 T: PartialEq<U>,
1453{
1454 #[inline]
1455 fn eq(&self, other: &Vec<U>) -> bool {
1456 &self.inner == other
1457 }
1458}
1459
1460impl<T, U> PartialEq<NonEmptyVec<U>> for Vec<T>
1461where
1462 T: PartialEq<U>,
1463{
1464 #[inline]
1465 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1466 self == &other.inner
1467 }
1468}
1469
1470#[cfg(any(feature = "alloc", feature = "std"))]
1471#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1472impl<T, U> PartialEq<NonEmptySlice<U>> for NonEmptyVec<T>
1473where
1474 T: PartialEq<U>,
1475{
1476 #[inline]
1477 fn eq(&self, other: &NonEmptySlice<U>) -> bool {
1478 self.as_slice() == other
1479 }
1480}
1481
1482#[cfg(any(feature = "alloc", feature = "std"))]
1483#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1484impl<T, U> PartialEq<NonEmptyVec<U>> for NonEmptySlice<T>
1485where
1486 T: PartialEq<U>,
1487{
1488 #[inline]
1489 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1490 self == other.as_slice()
1491 }
1492}
1493
1494impl<T, U> PartialEq<[U]> for NonEmptyVec<T>
1495where
1496 T: PartialEq<U>,
1497{
1498 #[inline]
1499 fn eq(&self, other: &[U]) -> bool {
1500 self.inner == other
1501 }
1502}
1503
1504impl<T, U> PartialEq<NonEmptyVec<U>> for [T]
1505where
1506 T: PartialEq<U>,
1507{
1508 #[inline]
1509 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1510 self == other.inner
1511 }
1512}
1513
1514impl<T, U, const N: usize> PartialEq<[U; N]> for NonEmptyVec<T>
1515where
1516 T: PartialEq<U>,
1517{
1518 #[inline]
1519 fn eq(&self, other: &[U; N]) -> bool {
1520 self.inner == other
1521 }
1522}
1523
1524impl<T, U, const N: usize> PartialEq<NonEmptyVec<U>> for [T; N]
1525where
1526 T: PartialEq<U>,
1527{
1528 #[inline]
1529 fn eq(&self, other: &NonEmptyVec<U>) -> bool {
1530 // Workaround for yet another asymmetric PartialEq implementation
1531 self == other.as_slice()
1532 }
1533}
1534
1535impl<T> Eq for NonEmptyVec<T> where T: Eq {}
1536
1537impl<T> PartialOrd for NonEmptyVec<T>
1538where
1539 T: PartialOrd,
1540{
1541 #[inline]
1542 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1543 PartialOrd::partial_cmp(&self.inner, &other.inner)
1544 }
1545}
1546
1547impl<T> Ord for NonEmptyVec<T>
1548where
1549 T: Ord,
1550{
1551 #[inline]
1552 fn cmp(&self, other: &Self) -> Ordering {
1553 Ord::cmp(&self.inner, &other.inner)
1554 }
1555}
1556
1557impl<T> Hash for NonEmptyVec<T>
1558where
1559 T: Hash,
1560{
1561 #[inline]
1562 fn hash<H: Hasher>(&self, state: &mut H) {
1563 self.inner.hash(state);
1564 }
1565}
1566
1567////////////////////////////////////////////////////////////////////////////////
1568// NonEmptyVec -> smart pointer holding a head-allocated slice
1569////////////////////////////////////////////////////////////////////////////////
1570
1571impl<T> From<NonEmptyVec<T>> for Arc<[T]> {
1572 #[inline]
1573 fn from(value: NonEmptyVec<T>) -> Self {
1574 Arc::from(value.inner)
1575 }
1576}
1577
1578impl<T> From<NonEmptyVec<T>> for Box<[T]> {
1579 #[inline]
1580 fn from(value: NonEmptyVec<T>) -> Self {
1581 value.inner.into_boxed_slice()
1582 }
1583}
1584
1585impl<'a, T> From<&'a NonEmptyVec<T>> for Cow<'a, [T]>
1586where
1587 T: Clone,
1588{
1589 #[inline]
1590 fn from(v: &'a NonEmptyVec<T>) -> Self {
1591 Cow::Borrowed(v)
1592 }
1593}
1594
1595impl<T> From<NonEmptyVec<T>> for Rc<[T]> {
1596 #[inline]
1597 fn from(value: NonEmptyVec<T>) -> Self {
1598 Rc::from(value.inner)
1599 }
1600}
1601
1602#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1603impl<T> From<NonEmptyVec<T>> for Arc<NonEmptySlice<T>> {
1604 #[inline]
1605 fn from(value: NonEmptyVec<T>) -> Self {
1606 let arc: Arc<[T]> = Arc::from(value);
1607 let ptr = Arc::into_raw(arc) as *const NonEmptySlice<T>;
1608 unsafe { Arc::from_raw(ptr) }
1609 }
1610}
1611
1612#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1613impl<T> From<NonEmptyVec<T>> for Box<NonEmptySlice<T>> {
1614 #[inline]
1615 fn from(value: NonEmptyVec<T>) -> Self {
1616 value.into_boxed_slice()
1617 }
1618}
1619
1620#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1621impl<'a, T> From<&'a NonEmptyVec<T>> for Cow<'a, NonEmptySlice<T>>
1622where
1623 T: Clone,
1624{
1625 #[inline]
1626 fn from(v: &'a NonEmptyVec<T>) -> Self {
1627 Cow::Borrowed(v)
1628 }
1629}
1630
1631#[cfg_attr(doc_cfg, doc(cfg(any(feature = "alloc", feature = "std"))))]
1632impl<T> From<NonEmptyVec<T>> for Rc<NonEmptySlice<T>> {
1633 #[inline]
1634 fn from(value: NonEmptyVec<T>) -> Self {
1635 let rc: Rc<[T]> = Rc::from(value);
1636 let ptr = Rc::into_raw(rc) as *const NonEmptySlice<T>;
1637 unsafe { Rc::from_raw(ptr) }
1638 }
1639}
1640
1641////////////////////////////////////////////////////////////////////////////////
1642// NonEmptyVec -> collections
1643////////////////////////////////////////////////////////////////////////////////
1644
1645#[cfg(feature = "std")]
1646#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
1647impl From<NonEmptyVec<NonZeroU8>> for CString {
1648 #[inline]
1649 fn from(value: NonEmptyVec<NonZeroU8>) -> Self {
1650 CString::from(value.inner)
1651 }
1652}
1653
1654impl<T> From<NonEmptyVec<T>> for Vec<T> {
1655 #[inline]
1656 fn from(value: NonEmptyVec<T>) -> Self {
1657 value.inner
1658 }
1659}
1660
1661impl<T> From<NonEmptyVec<T>> for VecDeque<T> {
1662 #[inline]
1663 fn from(value: NonEmptyVec<T>) -> Self {
1664 VecDeque::from(value.inner)
1665 }
1666}
1667
1668impl<T> From<NonEmptyVec<T>> for BinaryHeap<T>
1669where
1670 T: Ord,
1671{
1672 #[inline]
1673 fn from(value: NonEmptyVec<T>) -> Self {
1674 BinaryHeap::from(value.inner)
1675 }
1676}
1677
1678////////////////////////////////////////////////////////////////////////////////
1679// Failable conversions: collections -> NonEmptyVec
1680////////////////////////////////////////////////////////////////////////////////
1681
1682impl<T> TryFrom<&[T]> for NonEmptyVec<T>
1683where
1684 T: Clone,
1685{
1686 type Error = EmptyError;
1687
1688 #[inline]
1689 fn try_from(value: &[T]) -> Result<Self, Self::Error> {
1690 NonEmptyVec::new(value.into())
1691 }
1692}
1693
1694impl<T> TryFrom<&mut [T]> for NonEmptyVec<T>
1695where
1696 T: Clone,
1697{
1698 type Error = EmptyError;
1699
1700 #[inline]
1701 fn try_from(value: &mut [T]) -> Result<Self, Self::Error> {
1702 NonEmptyVec::new(value.into())
1703 }
1704}
1705
1706impl<'a, T> TryFrom<Cow<'a, [T]>> for NonEmptyVec<T>
1707where
1708 [T]: ToOwned<Owned = Vec<T>>,
1709{
1710 type Error = EmptyError;
1711
1712 fn try_from(value: Cow<'a, [T]>) -> Result<Self, Self::Error> {
1713 let vec = value.into_owned();
1714 NonEmptyVec::new(vec)
1715 }
1716}
1717
1718impl TryFrom<&str> for NonEmptyVec<u8> {
1719 type Error = EmptyError;
1720
1721 fn try_from(value: &str) -> Result<Self, Self::Error> {
1722 NonEmptyVec::new(value.into())
1723 }
1724}
1725
1726impl TryFrom<String> for NonEmptyVec<u8> {
1727 type Error = EmptyError;
1728
1729 #[inline]
1730 fn try_from(value: String) -> Result<Self, Self::Error> {
1731 NonEmptyVec::new(value.into())
1732 }
1733}
1734
1735#[cfg(feature = "std")]
1736#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
1737impl TryFrom<CString> for NonEmptyVec<u8> {
1738 type Error = EmptyError;
1739
1740 #[inline]
1741 fn try_from(value: CString) -> Result<Self, Self::Error> {
1742 NonEmptyVec::new(value.into())
1743 }
1744}
1745
1746impl<T> TryFrom<Vec<T>> for NonEmptyVec<T> {
1747 type Error = EmptyError;
1748
1749 #[inline]
1750 fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
1751 NonEmptyVec::new(value)
1752 }
1753}
1754
1755impl<T> TryFrom<VecDeque<T>> for NonEmptyVec<T> {
1756 type Error = EmptyError;
1757
1758 #[inline]
1759 fn try_from(value: VecDeque<T>) -> Result<Self, Self::Error> {
1760 NonEmptyVec::new(value.into())
1761 }
1762}
1763
1764impl<T> TryFrom<BinaryHeap<T>> for NonEmptyVec<T> {
1765 type Error = EmptyError;
1766
1767 #[inline]
1768 fn try_from(value: BinaryHeap<T>) -> Result<Self, Self::Error> {
1769 NonEmptyVec::new(value.into())
1770 }
1771}
1772
1773////////////////////////////////////////////////////////////////////////////////
1774/// Failable conversions: non-empty vector -> X
1775////////////////////////////////////////////////////////////////////////////////
1776
1777impl<T, const N: usize> TryFrom<NonEmptyVec<T>> for [T; N] {
1778 type Error = NonEmptyVec<T>;
1779
1780 fn try_from(mut value: NonEmptyVec<T>) -> Result<Self, Self::Error> {
1781 if value.inner.len() != N {
1782 return Err(value);
1783 }
1784
1785 // SAFETY: `.set_len(0)` is always sound. Also, the contract of the
1786 // newtype is invalidated, but since it drops here it's no issue.
1787 unsafe { value.inner.set_len(0) };
1788
1789 // SAFETY: A `Vec`'s pointer is always aligned properly, and the
1790 // alignment the array needs is the same as the items. It's already
1791 // known that there's enough items. The items will not double-drop as
1792 // the `set_len` tells the `Vec` not to also drop them.
1793 let array = unsafe { ptr::read(value.as_ptr().cast::<[T; N]>()) };
1794 Ok(array)
1795 }
1796}
1797
1798////////////////////////////////////////////////////////////////////////////////
1799// `io` implementations
1800////////////////////////////////////////////////////////////////////////////////
1801
1802#[cfg(feature = "std")]
1803#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
1804impl Write for NonEmptyVec<u8> {
1805 #[inline]
1806 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1807 Write::write(&mut self.inner, buf)
1808 }
1809
1810 #[inline]
1811 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
1812 Write::write_vectored(&mut self.inner, bufs)
1813 }
1814
1815 #[inline]
1816 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1817 Write::write_all(&mut self.inner, buf)
1818 }
1819
1820 #[inline]
1821 fn flush(&mut self) -> io::Result<()> {
1822 Write::flush(&mut self.inner)
1823 }
1824}
1825
1826////////////////////////////////////////////////////////////////////////////////
1827// `serde` implementations
1828////////////////////////////////////////////////////////////////////////////////
1829
1830#[cfg(feature = "serde")]
1831#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))]
1832impl<T> serde::Serialize for NonEmptyVec<T>
1833where
1834 T: serde::Serialize,
1835{
1836 #[inline]
1837 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1838 where
1839 S: serde::Serializer,
1840 {
1841 serde::Serialize::serialize(&self.inner, serializer)
1842 }
1843}
1844
1845#[cfg(all(feature = "serde", not(no_global_oom_handling)))]
1846#[cfg_attr(doc_cfg, doc(cfg(all(feature = "serde", not(no_global_oom_handling)))))]
1847impl<'de, T> serde::Deserialize<'de> for NonEmptyVec<T>
1848where
1849 T: serde::Deserialize<'de>,
1850{
1851 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1852 where
1853 D: serde::Deserializer<'de>,
1854 {
1855 let vec: Vec<T> = serde::Deserialize::deserialize(deserializer)?;
1856 NonEmptyVec::new(vec).map_err(|_| {
1857 serde::de::Error::custom("cannot deserialize `NonEmptyVec` from an empty sequence")
1858 })
1859 }
1860}