nonempty_collections/vector.rs
1//! Non-empty Vectors.
2
3use crate::iter::FromNonEmptyIterator;
4use crate::iter::IntoNonEmptyIterator;
5use crate::iter::NonEmptyIterator;
6use crate::slice::NEChunks;
7use crate::Singleton;
8use core::fmt;
9use std::cmp::Ordering;
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::num::NonZeroUsize;
13use std::slice::SliceIndex;
14
15#[cfg(feature = "serde")]
16use serde::Deserialize;
17#[cfg(feature = "serde")]
18use serde::Serialize;
19
20/// Like the [`vec!`] macro, but enforces at least one argument. A nice
21/// short-hand for constructing [`NEVec`] values.
22///
23/// ```
24/// use nonempty_collections::nev;
25/// use nonempty_collections::NEVec;
26///
27/// let v = nev![1, 2, 3];
28/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1, 2, 3]);
29///
30/// let v = nev![1];
31/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1]);
32///
33/// let v = nev![1; 3];
34/// assert_eq!(v.into_iter().collect::<Vec<_>>(), vec![1; 3]);
35/// ```
36///
37/// This won't compile!
38/// ``` compile_fail
39/// use nonempty_collections::nev;
40/// let v = nev![];
41/// ```
42///
43/// Neither will this.
44/// ``` compile_fail
45/// use nonempty_collections::nev;
46/// let v = nev![1; 0];
47/// ```
48///
49/// Consider also [`crate::nem!`] and [`crate::nes!`].
50#[macro_export]
51macro_rules! nev {
52 () => {compile_error!("An NEVec cannot be empty")};
53 ($h:expr, $( $x:expr ),* $(,)?) => {{
54 let mut v = $crate::NEVec::new($h);
55 $( v.push($x); )*
56 v
57 }};
58 ($h:expr) => {
59 $crate::NEVec::new($h)
60 };
61 ($elem:expr; $n:expr) => {{
62 let n = const { ::std::num::NonZero::new($n).expect("Length cannot be 0") };
63 $crate::vector::NEVec::from_elem($elem, n)
64 }};
65}
66
67/// A non-empty, growable Vector.
68///
69/// The first element can always be accessed in constant time. Similarly,
70/// certain functions like [`NEVec::first`] and [`NEVec::last`] always succeed:
71///
72/// ```
73/// use nonempty_collections::nev;
74///
75/// let s = nev!["Fëanor", "Fingolfin", "Finarfin"];
76/// assert_eq!(&"Fëanor", s.first()); // There is always a first element.
77/// assert_eq!(&"Finarfin", s.last()); // There is always a last element.
78/// ```
79#[cfg_attr(
80 feature = "serde",
81 derive(Deserialize, Serialize),
82 serde(bound(serialize = "T: Clone + Serialize")),
83 serde(into = "Vec<T>", try_from = "Vec<T>")
84)]
85#[allow(clippy::unsafe_derive_deserialize)] // the non-empty invariant is enforced by the deserialize implementation
86#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
87pub struct NEVec<T> {
88 inner: Vec<T>,
89}
90
91impl<T> NEVec<T> {
92 /// Create a new non-empty list with an initial element.
93 #[must_use]
94 pub fn new(head: T) -> Self {
95 NEVec { inner: vec![head] }
96 }
97
98 /// Create a new non-empty list by repeating an element a non-zero number of times.
99 ///
100 /// ```
101 /// use nonempty_collections::*;
102 /// use std::num::NonZeroUsize;
103 ///
104 /// let n = NonZeroUsize::new(3).unwrap();
105 /// let mut v = NEVec::from_elem(1, n);
106 /// assert_eq!(v, nev![1, 1, 1]);
107 /// ```
108 #[must_use]
109 pub fn from_elem(elem: T, n: NonZeroUsize) -> Self
110 where
111 T: Clone,
112 {
113 NEVec {
114 inner: vec![elem; n.get()],
115 }
116 }
117
118 /// Creates a new `NEVec` with a single element and specified capacity.
119 #[must_use]
120 pub fn with_capacity(capacity: NonZeroUsize, head: T) -> Self {
121 let mut inner = Vec::with_capacity(capacity.get());
122 inner.push(head);
123 NEVec { inner }
124 }
125
126 /// Get the first element. Never fails.
127 #[must_use]
128 pub fn first(&self) -> &T {
129 unsafe { self.inner.get_unchecked(0) }
130 }
131
132 /// Get the mutable reference to the first element. Never fails.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use nonempty_collections::nev;
138 ///
139 /// let mut v = nev![42];
140 /// let head = v.first_mut();
141 /// *head += 1;
142 /// assert_eq!(v.first(), &43);
143 ///
144 /// let mut v = nev![1, 4, 2, 3];
145 /// let head = v.first_mut();
146 /// *head *= 42;
147 /// assert_eq!(v.first(), &42);
148 /// ```
149 #[must_use]
150 pub fn first_mut(&mut self) -> &mut T {
151 unsafe { self.inner.get_unchecked_mut(0) }
152 }
153
154 /// Push an element to the end of the list.
155 pub fn push(&mut self, e: T) {
156 self.inner.push(e);
157 }
158
159 /// Pop an element from the end of the list. Is a no-op when [`Self::len()`]
160 /// is 1.
161 ///
162 /// ```
163 /// use nonempty_collections::nev;
164 ///
165 /// let mut v = nev![1, 2];
166 /// assert_eq!(Some(2), v.pop());
167 /// assert_eq!(None, v.pop());
168 /// ```
169 pub fn pop(&mut self) -> Option<T> {
170 if self.len() > NonZeroUsize::MIN {
171 self.inner.pop()
172 } else {
173 None
174 }
175 }
176
177 /// Removes and returns the element at position `index` within the vector,
178 /// shifting all elements after it to the left.
179 ///
180 /// If this [`NEVec`] contains only one element, no removal takes place and
181 /// `None` will be returned. If there are more elements, the item at the
182 /// `index` is removed and returned.
183 ///
184 /// Note: Because this shifts over the remaining elements, it has a
185 /// worst-case performance of *O*(*n*). If you don't need the order of
186 /// elements to be preserved, use [`swap_remove`] instead.
187 ///
188 /// [`swap_remove`]: NEVec::swap_remove
189 ///
190 /// # Panics
191 ///
192 /// Panics if `index` is out of bounds and `self.len() > 1`
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use nonempty_collections::nev;
198 ///
199 /// let mut v = nev![1, 2, 3];
200 /// assert_eq!(v.remove(1), Some(2));
201 /// assert_eq!(nev![1, 3], v);
202 /// ```
203 pub fn remove(&mut self, index: usize) -> Option<T> {
204 (self.len() > NonZeroUsize::MIN).then(|| self.inner.remove(index))
205 }
206
207 /// Removes an element from the vector and returns it.
208 ///
209 /// If this [`NEVec`] contains only one element, no removal takes place and
210 /// `None` will be returned. If there are more elements, the item at the
211 /// `index` is removed and returned.
212 ///
213 /// The removed element is replaced by the last element of the vector.
214 ///
215 /// This does not preserve ordering of the remaining elements, but is
216 /// *O*(1). If you need to preserve the element order, use [`remove`]
217 /// instead.
218 ///
219 /// [`remove`]: NEVec::remove
220 ///
221 /// # Panics
222 ///
223 /// Panics if `index` is out of bounds and `self.len() > 1`
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// use nonempty_collections::nev;
229 ///
230 /// let mut v = nev![1, 2, 3, 4];
231 /// assert_eq!(v.swap_remove(1), Some(2));
232 /// assert_eq!(nev![1, 4, 3], v);
233 /// ```
234 pub fn swap_remove(&mut self, index: usize) -> Option<T> {
235 (self.len() > NonZeroUsize::MIN).then(|| self.inner.swap_remove(index))
236 }
237
238 /// Retains only the elements specified by the predicate.
239 ///
240 /// In other words, remove all elements `e` for which `f(&e)` returns
241 /// `false`. This method operates in place, visiting each element
242 /// exactly once in the original order, and preserves the order of the
243 /// retained elements.
244 ///
245 /// If there are one or more items retained `Ok(Self)` is returned with the
246 /// remaining items. If all items are removed, the inner `Vec` is returned
247 /// to allowed for reuse of the claimed memory.
248 ///
249 /// # Errors
250 /// Returns `Err` if no elements are retained.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use nonempty_collections::nev;
256 ///
257 /// let vec = nev![1, 2, 3, 4];
258 /// let vec = vec.retain(|&x| x % 2 == 0);
259 /// assert_eq!(Ok(nev![2, 4]), vec);
260 /// ```
261 pub fn retain<F>(self, mut f: F) -> Result<Self, Vec<T>>
262 where
263 F: FnMut(&T) -> bool,
264 {
265 self.retain_mut(|item| f(item))
266 }
267
268 /// Retains only the elements specified by the predicate, passing a mutable
269 /// reference to it.
270 ///
271 /// In other words, remove all elements `e` such that `f(&mut e)` returns
272 /// `false`. This method operates in place, visiting each element
273 /// exactly once in the original order, and preserves the order of the
274 /// retained elements.
275 ///
276 /// If there are one or more items retained `Ok(Self)` is returned with the
277 /// remaining items. If all items are removed, the inner `Vec` is returned
278 /// to allowed for reuse of the claimed memory.
279 ///
280 /// # Errors
281 /// Returns `Err` if no elements are retained.
282 ///
283 /// # Examples
284 ///
285 /// ```
286 /// use nonempty_collections::nev;
287 ///
288 /// let vec = nev![1, 2, 3, 4];
289 /// let vec = vec.retain_mut(|x| {
290 /// if *x <= 3 {
291 /// *x += 1;
292 /// true
293 /// } else {
294 /// false
295 /// }
296 /// });
297 /// assert_eq!(Ok(nev![2, 3, 4]), vec);
298 /// ```
299 pub fn retain_mut<F>(mut self, f: F) -> Result<Self, Vec<T>>
300 where
301 F: FnMut(&mut T) -> bool,
302 {
303 self.inner.retain_mut(f);
304 if self.inner.is_empty() {
305 Err(self.inner)
306 } else {
307 Ok(self)
308 }
309 }
310
311 /// Inserts an element at position index within the vector, shifting all
312 /// elements after it to the right.
313 ///
314 /// # Panics
315 ///
316 /// Panics if index > len.
317 ///
318 /// # Examples
319 ///
320 /// ```
321 /// use nonempty_collections::nev;
322 ///
323 /// let mut v = nev![1, 2, 3];
324 /// v.insert(1, 4);
325 /// assert_eq!(v, nev![1, 4, 2, 3]);
326 /// v.insert(4, 5);
327 /// assert_eq!(v, nev![1, 4, 2, 3, 5]);
328 /// v.insert(0, 42);
329 /// assert_eq!(v, nev![42, 1, 4, 2, 3, 5]);
330 /// ```
331 pub fn insert(&mut self, index: usize, element: T) {
332 self.inner.insert(index, element);
333 }
334
335 /// Get the length of the list.
336 #[must_use]
337 pub fn len(&self) -> NonZeroUsize {
338 unsafe { NonZeroUsize::new_unchecked(self.inner.len()) }
339 }
340
341 /// A `NEVec` is never empty.
342 #[deprecated(since = "0.1.0", note = "A NEVec is never empty.")]
343 #[must_use]
344 pub const fn is_empty(&self) -> bool {
345 false
346 }
347
348 /// Get the capacity of the list.
349 #[must_use]
350 pub fn capacity(&self) -> NonZeroUsize {
351 unsafe { NonZeroUsize::new_unchecked(self.inner.capacity()) }
352 }
353
354 /// Get the last element. Never fails.
355 #[must_use]
356 #[allow(clippy::missing_panics_doc)] // never fails
357 pub fn last(&self) -> &T {
358 self.inner.last().unwrap()
359 }
360
361 /// Get the last element mutably.
362 #[must_use]
363 #[allow(clippy::missing_panics_doc)] // never fails
364 pub fn last_mut(&mut self) -> &mut T {
365 self.inner.last_mut().unwrap()
366 }
367
368 /// Check whether an element is contained in the list.
369 ///
370 /// ```
371 /// use nonempty_collections::nev;
372 ///
373 /// let mut l = nev![42, 36, 58];
374 ///
375 /// assert!(l.contains(&42));
376 /// assert!(!l.contains(&101));
377 /// ```
378 #[must_use]
379 pub fn contains(&self, x: &T) -> bool
380 where
381 T: PartialEq,
382 {
383 self.inner.contains(x)
384 }
385
386 /// Get an element by index.
387 #[must_use]
388 pub fn get(&self, index: usize) -> Option<&T> {
389 self.inner.get(index)
390 }
391
392 /// Get an element by index, mutably.
393 #[must_use]
394 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
395 self.inner.get_mut(index)
396 }
397
398 /// Truncate the list to a certain size.
399 pub fn truncate(&mut self, len: NonZeroUsize) {
400 self.inner.truncate(len.get());
401 }
402
403 /// Returns a regular iterator over the values in this non-empty vector.
404 ///
405 /// For a `NonEmptyIterator` see `Self::nonempty_iter()`.
406 pub fn iter(&self) -> std::slice::Iter<'_, T> {
407 self.inner.iter()
408 }
409
410 /// Returns a regular mutable iterator over the values in this non-empty
411 /// vector.
412 ///
413 /// For a `NonEmptyIterator` see `Self::nonempty_iter_mut()`.
414 pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
415 self.inner.iter_mut()
416 }
417
418 /// ```
419 /// use nonempty_collections::*;
420 ///
421 /// let mut l = nev![42, 36, 58];
422 ///
423 /// let mut iter = l.nonempty_iter();
424 /// let (first, mut rest_iter) = iter.next();
425 ///
426 /// assert_eq!(first, &42);
427 /// assert_eq!(rest_iter.next(), Some(&36));
428 /// assert_eq!(rest_iter.next(), Some(&58));
429 /// assert_eq!(rest_iter.next(), None);
430 /// ```
431 pub fn nonempty_iter(&self) -> Iter<'_, T> {
432 Iter {
433 iter: self.inner.iter(),
434 }
435 }
436
437 /// Returns an iterator that allows modifying each value.
438 ///
439 /// # Examples
440 ///
441 /// ```
442 /// use nonempty_collections::*;
443 ///
444 /// let mut l = nev![42, 36, 58];
445 ///
446 /// for i in l.nonempty_iter_mut() {
447 /// *i *= 10;
448 /// }
449 ///
450 /// let mut iter = l.nonempty_iter();
451 /// let (first, mut rest_iter) = iter.next();
452 ///
453 /// assert_eq!(first, &420);
454 /// assert_eq!(rest_iter.next(), Some(&360));
455 /// assert_eq!(rest_iter.next(), Some(&580));
456 /// assert_eq!(rest_iter.next(), None);
457 /// ```
458 pub fn nonempty_iter_mut(&mut self) -> IterMut<'_, T> {
459 IterMut {
460 inner: self.inner.iter_mut(),
461 }
462 }
463
464 /// Creates a new non-empty vec by cloning the elements from the slice if it
465 /// is non-empty, returns `None` otherwise.
466 ///
467 /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is
468 /// `NEVec` before proceeding with a computation. Using `try_from_slice`
469 /// will give us a proof that we have a `NEVec` in the `Some` branch,
470 /// otherwise it allows the caller to handle the `None` case.
471 ///
472 /// # Example use
473 ///
474 /// ```
475 /// use nonempty_collections::nev;
476 /// use nonempty_collections::NEVec;
477 ///
478 /// let v_vec = NEVec::try_from_slice(&[1, 2, 3, 4, 5]);
479 /// assert_eq!(v_vec, Some(nev![1, 2, 3, 4, 5]));
480 ///
481 /// let empty_vec: Option<NEVec<&u32>> = NEVec::try_from_slice(&[]);
482 /// assert!(empty_vec.is_none());
483 /// ```
484 #[must_use]
485 pub fn try_from_slice(slice: &[T]) -> Option<NEVec<T>>
486 where
487 T: Clone,
488 {
489 if slice.is_empty() {
490 None
491 } else {
492 Some(NEVec {
493 inner: slice.to_vec(),
494 })
495 }
496 }
497
498 /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is
499 /// `NEVec` before proceeding with a computation. Using `try_from_vec` will
500 /// give us a proof that we have a `NEVec` in the `Some` branch,
501 /// otherwise it allows the caller to handle the `None` case.
502 ///
503 /// This version will consume the `Vec` you pass in. If you would rather
504 /// pass the data as a slice then use [`NEVec::try_from_slice`].
505 ///
506 /// # Example Use
507 ///
508 /// ```
509 /// use nonempty_collections::nev;
510 /// use nonempty_collections::NEVec;
511 ///
512 /// let v_vec = NEVec::try_from_vec(vec![1, 2, 3, 4, 5]);
513 /// assert_eq!(v_vec, Some(nev![1, 2, 3, 4, 5]));
514 ///
515 /// let empty_vec: Option<NEVec<&u32>> = NEVec::try_from_vec(vec![]);
516 /// assert!(empty_vec.is_none());
517 /// ```
518 #[must_use]
519 pub fn try_from_vec(vec: Vec<T>) -> Option<NEVec<T>> {
520 if vec.is_empty() {
521 None
522 } else {
523 Some(NEVec { inner: vec })
524 }
525 }
526
527 /// Deconstruct a `NEVec` into its head and tail. This operation never fails
528 /// since we are guaranteed to have a head element.
529 ///
530 /// # Example Use
531 ///
532 /// ```
533 /// use nonempty_collections::nev;
534 ///
535 /// let mut v = nev![1, 2, 3, 4, 5];
536 ///
537 /// // Guaranteed to have the head and we also get the tail.
538 /// assert_eq!(v.split_first(), (&1, &[2, 3, 4, 5][..]));
539 ///
540 /// let v = nev![1];
541 ///
542 /// // Guaranteed to have the head element.
543 /// assert_eq!(v.split_first(), (&1, &[][..]));
544 /// ```
545 #[must_use]
546 #[allow(clippy::missing_panics_doc)] // never fails
547 pub fn split_first(&self) -> (&T, &[T]) {
548 self.inner.split_first().unwrap()
549 }
550
551 /// Deconstruct a `NEVec` into its first, last, and
552 /// middle elements, in that order.
553 ///
554 /// If there is only one element then first == last.
555 ///
556 /// # Example Use
557 ///
558 /// ```
559 /// use nonempty_collections::nev;
560 ///
561 /// let mut v = nev![1, 2, 3, 4, 5];
562 ///
563 /// // Guaranteed to have the last element and the elements
564 /// // preceding it.
565 /// assert_eq!(v.split(), (&1, &[2, 3, 4][..], &5));
566 ///
567 /// let v = nev![1];
568 ///
569 /// // Guaranteed to have the last element.
570 /// assert_eq!(v.split(), (&1, &[][..], &1));
571 /// ```
572 #[must_use]
573 pub fn split(&self) -> (&T, &[T], &T) {
574 let (first, rest) = self.split_first();
575 if let Some((last, middle)) = rest.split_last() {
576 (first, middle, last)
577 } else {
578 (first, &[], first)
579 }
580 }
581
582 /// Append a `Vec` to the tail of the `NEVec`.
583 ///
584 /// # Example Use
585 ///
586 /// ```
587 /// use nonempty_collections::nev;
588 ///
589 /// let mut v = nev![1];
590 /// let mut vec = vec![2, 3, 4, 5];
591 /// v.append(&mut vec);
592 ///
593 /// let mut expected = nev![1, 2, 3, 4, 5];
594 /// assert_eq!(v, expected);
595 /// ```
596 pub fn append(&mut self, other: &mut Vec<T>) {
597 self.inner.append(other);
598 }
599
600 /// Binary searches this sorted non-empty vector for a given element.
601 ///
602 /// If the value is found then `Result::Ok` is returned, containing the
603 /// index of the matching element. If there are multiple matches, then any
604 /// one of the matches could be returned.
605 ///
606 /// # Errors
607 ///
608 /// If the value is not found then `Result::Err` is returned, containing the
609 /// index where a matching element could be inserted while maintaining
610 /// sorted order.
611 ///
612 /// # Examples
613 ///
614 /// ```
615 /// use nonempty_collections::nev;
616 ///
617 /// let v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
618 /// assert_eq!(v.binary_search(&0), Ok(0));
619 /// assert_eq!(v.binary_search(&13), Ok(9));
620 /// assert_eq!(v.binary_search(&4), Err(7));
621 /// assert_eq!(v.binary_search(&100), Err(13));
622 /// let r = v.binary_search(&1);
623 /// assert!(match r {
624 /// Ok(1..=4) => true,
625 /// _ => false,
626 /// });
627 /// ```
628 ///
629 /// If you want to insert an item to a sorted non-empty vector, while
630 /// maintaining sort order:
631 ///
632 /// ```
633 /// use nonempty_collections::nev;
634 ///
635 /// let mut v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
636 /// let num = 42;
637 /// let idx = v.binary_search(&num).unwrap_or_else(|x| x);
638 /// v.insert(idx, num);
639 /// assert_eq!(v, nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
640 /// ```
641 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
642 where
643 T: Ord,
644 {
645 self.binary_search_by(|p| p.cmp(x))
646 }
647
648 /// Binary searches this sorted non-empty with a comparator function.
649 ///
650 /// The comparator function should implement an order consistent with the
651 /// sort order of the underlying slice, returning an order code that
652 /// indicates whether its argument is Less, Equal or Greater the desired
653 /// target.
654 ///
655 /// If the value is found then `Result::Ok` is returned, containing the
656 /// index of the matching element. If there are multiple matches, then any
657 /// one of the matches could be returned.
658 ///
659 /// # Errors
660 /// If the value is not found then `Result::Err` is returned, containing the
661 /// index where a matching element could be inserted while maintaining
662 /// sorted order.
663 ///
664 /// # Examples
665 ///
666 /// Looks up a series of four elements. The first is found, with a uniquely
667 /// determined position; the second and third are not found; the fourth
668 /// could match any position from 1 to 4.
669 ///
670 /// ```
671 /// use nonempty_collections::nev;
672 ///
673 /// let v = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
674 /// let seek = 0;
675 /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
676 /// let seek = 13;
677 /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
678 /// let seek = 4;
679 /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
680 /// let seek = 100;
681 /// assert_eq!(v.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
682 /// let seek = 1;
683 /// let r = v.binary_search_by(|probe| probe.cmp(&seek));
684 /// assert!(match r {
685 /// Ok(1..=4) => true,
686 /// _ => false,
687 /// });
688 /// ```
689 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
690 where
691 F: FnMut(&'a T) -> Ordering,
692 {
693 self.inner.binary_search_by(f)
694 }
695
696 /// Binary searches this sorted non-empty vector with a key extraction
697 /// function.
698 ///
699 /// Assumes that the vector is sorted by the key.
700 ///
701 /// If the value is found then `Result::Ok` is returned, containing the
702 /// index of the matching element. If there are multiple matches, then any
703 /// one of the matches could be returned.
704 ///
705 /// # Errors
706 /// If the value is not found then `Result::Err` is returned, containing the
707 /// index where a matching element could be inserted while maintaining
708 /// sorted order.
709 ///
710 /// # Examples
711 ///
712 /// Looks up a series of four elements in a non-empty vector of pairs sorted
713 /// by their second elements. The first is found, with a uniquely determined
714 /// position; the second and third are not found; the fourth could match any
715 /// position in [1, 4].
716 ///
717 /// ```
718 /// use nonempty_collections::nev;
719 ///
720 /// let v = nev![
721 /// (0, 0),
722 /// (2, 1),
723 /// (4, 1),
724 /// (5, 1),
725 /// (3, 1),
726 /// (1, 2),
727 /// (2, 3),
728 /// (4, 5),
729 /// (5, 8),
730 /// (3, 13),
731 /// (1, 21),
732 /// (2, 34),
733 /// (4, 55)
734 /// ];
735 ///
736 /// assert_eq!(v.binary_search_by_key(&0, |&(a, b)| b), Ok(0));
737 /// assert_eq!(v.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
738 /// assert_eq!(v.binary_search_by_key(&4, |&(a, b)| b), Err(7));
739 /// assert_eq!(v.binary_search_by_key(&100, |&(a, b)| b), Err(13));
740 /// let r = v.binary_search_by_key(&1, |&(a, b)| b);
741 /// assert!(match r {
742 /// Ok(1..=4) => true,
743 /// _ => false,
744 /// });
745 /// ```
746 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
747 where
748 B: Ord,
749 F: FnMut(&'a T) -> B,
750 {
751 self.binary_search_by(|k| f(k).cmp(b))
752 }
753
754 /// Sorts the `NEVec` in place.
755 ///
756 /// See also [`slice::sort`].
757 ///
758 /// # Examples
759 ///
760 /// ```
761 /// use nonempty_collections::nev;
762 ///
763 /// let mut n = nev![5, 4, 3, 2, 1];
764 /// n.sort();
765 /// assert_eq!(nev![1, 2, 3, 4, 5], n);
766 ///
767 /// // Naturally, sorting a sorted result should remain the same.
768 /// n.sort();
769 /// assert_eq!(nev![1, 2, 3, 4, 5], n);
770 /// ```
771 pub fn sort(&mut self)
772 where
773 T: Ord,
774 {
775 self.inner.sort();
776 }
777
778 /// Like [`NEVec::sort`], but sorts the `NEVec` with a given comparison
779 /// function.
780 ///
781 /// See also [`slice::sort_by`].
782 ///
783 /// ```
784 /// use nonempty_collections::nev;
785 ///
786 /// let mut n = nev!["Sirion", "Gelion", "Narog"];
787 /// n.sort_by(|a, b| b.cmp(&a));
788 /// assert_eq!(nev!["Sirion", "Narog", "Gelion"], n);
789 /// ```
790 pub fn sort_by<F>(&mut self, f: F)
791 where
792 F: FnMut(&T, &T) -> Ordering,
793 {
794 self.inner.sort_by(f);
795 }
796
797 /// Like [`NEVec::sort`], but sorts the `NEVec` after first transforming
798 /// each element into something easily comparable. Beware of expensive key
799 /// functions, as the results of each call are not cached.
800 ///
801 /// See also [`slice::sort_by_key`].
802 ///
803 /// ```
804 /// use nonempty_collections::nev;
805 ///
806 /// let mut n = nev![-5, 4, -3, 2, 1];
807 /// n.sort_by_key(|x| x * x);
808 /// assert_eq!(nev![1, 2, -3, 4, -5], n);
809 ///
810 /// // Naturally, sorting a sorted result should remain the same.
811 /// n.sort_by_key(|x| x * x);
812 /// assert_eq!(nev![1, 2, -3, 4, -5], n);
813 /// ```
814 pub fn sort_by_key<K, F>(&mut self, f: F)
815 where
816 F: FnMut(&T) -> K,
817 K: Ord,
818 {
819 self.inner.sort_by_key(f);
820 }
821
822 /// Yields a `NESlice`.
823 #[must_use]
824 pub fn as_nonempty_slice(&self) -> crate::NESlice<'_, T> {
825 // SAFETY: `self.inner` is non-empty by the invariant of `NEVec`
826 unsafe { crate::NESlice::from_slice_unchecked(self.inner.as_slice()) }
827 }
828
829 /// Removes all but the first of consecutive elements in the vector that
830 /// resolve to the same key.
831 ///
832 /// If the vector is sorted, this removes all duplicates.
833 ///
834 /// # Examples
835 ///
836 /// ```
837 /// use nonempty_collections::nev;
838 /// let mut v = nev![10, 20, 21, 30, 20];
839 ///
840 /// v.dedup_by_key(|i| *i / 10);
841 ///
842 /// assert_eq!(nev![10, 20, 30, 20], v);
843 /// ```
844 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
845 where
846 F: FnMut(&mut T) -> K,
847 K: PartialEq,
848 {
849 self.dedup_by(|a, b| key(a) == key(b));
850 }
851
852 /// Removes all but the first of consecutive elements in the vector
853 /// satisfying a given equality relation.
854 ///
855 /// The `same_bucket` function is passed references to two elements from the
856 /// vector and must determine if the elements compare equal. The
857 /// elements are passed in opposite order from their order in the slice,
858 /// so if `same_bucket(a, b)` returns `true`, `a` is removed.
859 ///
860 /// If the vector is sorted, this removes all duplicates.
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// use nonempty_collections::nev;
866 /// let mut v = nev!["foo", "Foo", "foo", "bar", "Bar", "baz", "bar"];
867 ///
868 /// v.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
869 ///
870 /// assert_eq!(nev!["foo", "bar", "baz", "bar"], v);
871 /// ```
872 pub fn dedup_by<F>(&mut self, same_bucket: F)
873 where
874 F: FnMut(&mut T, &mut T) -> bool,
875 {
876 self.inner.dedup_by(same_bucket);
877 }
878
879 /// Returns a non-empty iterator over `chunk_size` elements of the `NEVec`
880 /// at a time, starting at the beginning of the `NEVec`.
881 ///
882 /// ```
883 /// use std::num::NonZeroUsize;
884 ///
885 /// use nonempty_collections::*;
886 ///
887 /// let v = nev![1, 2, 3, 4, 5, 6];
888 /// let n = NonZeroUsize::new(2).unwrap();
889 /// let r = v.nonempty_chunks(n).collect::<NEVec<_>>();
890 ///
891 /// let a = nev![1, 2];
892 /// let b = nev![3, 4];
893 /// let c = nev![5, 6];
894 ///
895 /// assert_eq!(
896 /// r,
897 /// nev![
898 /// a.as_nonempty_slice(),
899 /// b.as_nonempty_slice(),
900 /// c.as_nonempty_slice()
901 /// ]
902 /// );
903 /// ```
904 pub fn nonempty_chunks(&self, chunk_size: NonZeroUsize) -> NEChunks<'_, T> {
905 NEChunks {
906 inner: self.inner.chunks(chunk_size.get()),
907 }
908 }
909
910 /// Returns the index of the partition point according to the given
911 /// predicate (the index of the first element of the second partition).
912 ///
913 /// The vector is assumed to be partitioned according to the given
914 /// predicate. This means that all elements for which the predicate
915 /// returns true are at the start of the vector and all elements for
916 /// which the predicate returns false are at the end. For example, `[7,
917 /// 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
918 /// (all odd numbers are at the start, all even at the end).
919 ///
920 /// If this vector is not partitioned, the returned result is unspecified
921 /// and meaningless, as this method performs a kind of binary search.
922 ///
923 /// See also [`NEVec::binary_search`], [`NEVec::binary_search_by`], and
924 /// [`NEVec::binary_search_by_key`].
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// # use nonempty_collections::*;
930 /// #
931 /// let v = nev![1, 2, 3, 3, 5, 6, 7];
932 /// let i = v.partition_point(|&x| x < 5);
933 ///
934 /// assert_eq!(i, 4);
935 /// ```
936 ///
937 /// If all elements of the non-empty vector match the predicate, then the
938 /// length of the vector will be returned:
939 ///
940 /// ```
941 /// # use nonempty_collections::*;
942 /// #
943 /// let a = nev![2, 4, 8];
944 /// assert_eq!(a.partition_point(|&x| x < 100), a.len().get());
945 /// ```
946 ///
947 /// If you want to insert an item to a sorted vector, while maintaining
948 /// sort order:
949 ///
950 /// ```
951 /// # use nonempty_collections::*;
952 /// #
953 /// let mut s = nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
954 /// let num = 42;
955 /// let idx = s.partition_point(|&x| x < num);
956 /// s.insert(idx, num);
957 /// assert_eq!(s, nev![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
958 /// ```
959 #[must_use]
960 pub fn partition_point<P>(&self, mut pred: P) -> usize
961 where
962 P: FnMut(&T) -> bool,
963 {
964 self.binary_search_by(|x| {
965 if pred(x) {
966 Ordering::Less
967 } else {
968 Ordering::Greater
969 }
970 })
971 .unwrap_or_else(|i| i)
972 }
973}
974
975impl<T: PartialEq> NEVec<T> {
976 /// Removes consecutive repeated elements in the vector according to the
977 /// [`PartialEq`] trait implementation.
978 ///
979 /// If the vector is sorted, this removes all duplicates.
980 ///
981 /// # Examples
982 ///
983 /// ```
984 /// use nonempty_collections::nev;
985 /// let mut v = nev![1, 1, 1, 2, 3, 2, 2, 1];
986 /// v.dedup();
987 /// assert_eq!(nev![1, 2, 3, 2, 1], v);
988 /// ```
989 pub fn dedup(&mut self) {
990 self.dedup_by(|a, b| a == b);
991 }
992}
993
994impl<T> From<NEVec<T>> for Vec<T> {
995 /// Turns a non-empty list into a `Vec`.
996 fn from(nonempty: NEVec<T>) -> Vec<T> {
997 nonempty.inner
998 }
999}
1000
1001impl<T> From<(T, Vec<T>)> for NEVec<T> {
1002 /// Turns a pair of an element and a `Vec` into
1003 /// a `NEVec`.
1004 fn from((head, tail): (T, Vec<T>)) -> Self {
1005 let mut vec = vec![head];
1006 vec.extend(tail);
1007 NEVec { inner: vec }
1008 }
1009}
1010
1011impl<T> AsRef<Vec<T>> for NEVec<T> {
1012 fn as_ref(&self) -> &Vec<T> {
1013 self.inner.as_ref()
1014 }
1015}
1016
1017impl<T> AsMut<Vec<T>> for NEVec<T> {
1018 fn as_mut(&mut self) -> &mut Vec<T> {
1019 self.inner.as_mut()
1020 }
1021}
1022
1023/// ```
1024/// use nonempty_collections::*;
1025///
1026/// let v0 = nev![1, 2, 3];
1027/// let v1: NEVec<_> = v0.nonempty_iter().cloned().collect();
1028/// assert_eq!(v0, v1);
1029/// ```
1030impl<T> FromNonEmptyIterator<T> for NEVec<T> {
1031 fn from_nonempty_iter<I>(iter: I) -> Self
1032 where
1033 I: IntoNonEmptyIterator<Item = T>,
1034 {
1035 NEVec {
1036 inner: iter.into_nonempty_iter().into_iter().collect(),
1037 }
1038 }
1039}
1040
1041/// A non-empty iterator over the values of an [`NEVec`].
1042#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1043pub struct Iter<'a, T: 'a> {
1044 iter: std::slice::Iter<'a, T>,
1045}
1046
1047impl<T> NonEmptyIterator for Iter<'_, T> {}
1048
1049impl<'a, T> IntoIterator for Iter<'a, T> {
1050 type Item = &'a T;
1051
1052 type IntoIter = std::slice::Iter<'a, T>;
1053
1054 fn into_iter(self) -> Self::IntoIter {
1055 self.iter
1056 }
1057}
1058
1059// FIXME(#26925) Remove in favor of `#[derive(Clone)]` (see https://github.com/rust-lang/rust/issues/26925 for more info)
1060impl<T> Clone for Iter<'_, T> {
1061 fn clone(&self) -> Self {
1062 Iter {
1063 iter: self.iter.clone(),
1064 }
1065 }
1066}
1067
1068impl<T: Debug> Debug for Iter<'_, T> {
1069 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1070 self.iter.fmt(f)
1071 }
1072}
1073
1074/// A non-empty iterator over mutable values from an [`NEVec`].
1075#[derive(Debug)]
1076#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1077pub struct IterMut<'a, T: 'a> {
1078 inner: std::slice::IterMut<'a, T>,
1079}
1080
1081impl<T> NonEmptyIterator for IterMut<'_, T> {}
1082
1083impl<'a, T> IntoIterator for IterMut<'a, T> {
1084 type Item = &'a mut T;
1085
1086 type IntoIter = std::slice::IterMut<'a, T>;
1087
1088 fn into_iter(self) -> Self::IntoIter {
1089 self.inner
1090 }
1091}
1092
1093/// An owned non-empty iterator over values from an [`NEVec`].
1094#[derive(Clone)]
1095#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1096pub struct IntoIter<T> {
1097 inner: std::vec::IntoIter<T>,
1098}
1099
1100impl<T> NonEmptyIterator for IntoIter<T> {}
1101
1102impl<T> IntoIterator for IntoIter<T> {
1103 type Item = T;
1104
1105 type IntoIter = std::vec::IntoIter<T>;
1106
1107 fn into_iter(self) -> Self::IntoIter {
1108 self.inner
1109 }
1110}
1111
1112impl<T: Debug> Debug for IntoIter<T> {
1113 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1114 self.inner.fmt(f)
1115 }
1116}
1117
1118impl<T> IntoNonEmptyIterator for NEVec<T> {
1119 type IntoNEIter = IntoIter<T>;
1120
1121 fn into_nonempty_iter(self) -> Self::IntoNEIter {
1122 IntoIter {
1123 inner: self.inner.into_iter(),
1124 }
1125 }
1126}
1127
1128impl<'a, T> IntoNonEmptyIterator for &'a NEVec<T> {
1129 type IntoNEIter = Iter<'a, T>;
1130
1131 fn into_nonempty_iter(self) -> Self::IntoNEIter {
1132 self.nonempty_iter()
1133 }
1134}
1135
1136impl<T> IntoIterator for NEVec<T> {
1137 type Item = T;
1138 type IntoIter = std::vec::IntoIter<Self::Item>;
1139
1140 fn into_iter(self) -> Self::IntoIter {
1141 self.inner.into_iter()
1142 }
1143}
1144
1145impl<'a, T> IntoIterator for &'a NEVec<T> {
1146 type Item = &'a T;
1147 type IntoIter = std::slice::Iter<'a, T>;
1148
1149 fn into_iter(self) -> Self::IntoIter {
1150 self.iter()
1151 }
1152}
1153
1154impl<'a, T> IntoIterator for &'a mut NEVec<T> {
1155 type Item = &'a mut T;
1156 type IntoIter = std::slice::IterMut<'a, T>;
1157
1158 fn into_iter(self) -> Self::IntoIter {
1159 self.iter_mut()
1160 }
1161}
1162
1163impl<T, I> std::ops::Index<I> for NEVec<T>
1164where
1165 I: SliceIndex<[T]>,
1166{
1167 type Output = I::Output;
1168
1169 /// ```
1170 /// use nonempty_collections::nev;
1171 ///
1172 /// let v = nev![1, 2, 3, 4, 5];
1173 ///
1174 /// assert_eq!(v[0], 1);
1175 /// assert_eq!(v[1], 2);
1176 /// assert_eq!(v[3], 4);
1177 /// assert_eq!(&v[..], &[1, 2, 3, 4, 5]);
1178 /// assert_eq!(&v[2..], &[3, 4, 5]);
1179 /// assert_eq!(&v[..2], &[1, 2]);
1180 /// ```
1181 fn index(&self, index: I) -> &Self::Output {
1182 self.inner.index(index)
1183 }
1184}
1185
1186impl<T, I> std::ops::IndexMut<I> for NEVec<T>
1187where
1188 I: SliceIndex<[T]>,
1189{
1190 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1191 self.inner.index_mut(index)
1192 }
1193}
1194
1195impl<T: Debug> Debug for NEVec<T> {
1196 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1197 self.inner.fmt(f)
1198 }
1199}
1200
1201impl<T> TryFrom<Vec<T>> for NEVec<T> {
1202 type Error = crate::Error;
1203
1204 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1205 NEVec::try_from_vec(vec).ok_or(crate::Error::Empty)
1206 }
1207}
1208
1209impl<T> Extend<T> for NEVec<T> {
1210 fn extend<I>(&mut self, iter: I)
1211 where
1212 I: IntoIterator<Item = T>,
1213 {
1214 self.inner.extend(iter);
1215 }
1216}
1217
1218impl<T> Singleton for NEVec<T> {
1219 type Item = T;
1220
1221 /// ```
1222 /// use nonempty_collections::{NEVec, Singleton, nev};
1223 ///
1224 /// let v = NEVec::singleton(1);
1225 /// assert_eq!(nev![1], v);
1226 /// ```
1227 fn singleton(item: T) -> NEVec<T> {
1228 NEVec::new(item)
1229 }
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234 use crate::NEVec;
1235
1236 #[derive(Debug, Clone, PartialEq)]
1237 struct Foo {
1238 user: String,
1239 }
1240
1241 #[test]
1242 fn macro_usage() {
1243 let a = Foo {
1244 user: "a".to_string(),
1245 };
1246 let b = Foo {
1247 user: "b".to_string(),
1248 };
1249
1250 let v = nev![a, b];
1251 assert_eq!("a", v.first().user);
1252 }
1253
1254 #[test]
1255 fn macro_semicolon() {
1256 let a = Foo {
1257 user: "a".to_string(),
1258 };
1259 let v = nev![a.clone(); 3];
1260
1261 let expected = NEVec { inner: vec![a; 3] };
1262 assert_eq!(v, expected);
1263 }
1264
1265 #[test]
1266 fn test_from_conversion() {
1267 let result = NEVec::from((1, vec![2, 3, 4, 5]));
1268 let expected = NEVec {
1269 inner: vec![1, 2, 3, 4, 5],
1270 };
1271 assert_eq!(result, expected);
1272 }
1273
1274 #[test]
1275 fn test_into_iter() {
1276 let nonempty = NEVec::from((0usize, vec![1, 2, 3]));
1277 for (i, n) in nonempty.into_iter().enumerate() {
1278 assert_eq!(i, n);
1279 }
1280 }
1281
1282 #[test]
1283 fn test_iter_syntax() {
1284 let nonempty = NEVec::from((0, vec![1, 2, 3]));
1285 for n in &nonempty {
1286 assert_eq!(*n, *n); // Prove that we're dealing with references.
1287 }
1288 for _ in nonempty {}
1289 }
1290
1291 #[cfg(feature = "serde")]
1292 mod serialize {
1293 use serde::Deserialize;
1294 use serde::Serialize;
1295
1296 use crate::NEVec;
1297
1298 #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
1299 struct SimpleSerializable(i32);
1300
1301 #[test]
1302 fn test_simple_round_trip() -> Result<(), Box<dyn std::error::Error>> {
1303 // Given
1304 let mut v = NEVec::new(SimpleSerializable(42));
1305 v.push(SimpleSerializable(777));
1306 let expected_value = v.clone();
1307
1308 // When
1309 let res =
1310 serde_json::from_str::<'_, NEVec<SimpleSerializable>>(&serde_json::to_string(&v)?)?;
1311
1312 // Then
1313 assert_eq!(res, expected_value);
1314
1315 Ok(())
1316 }
1317 }
1318
1319 #[test]
1320 fn test_result_collect() {
1321 use crate::IntoNonEmptyIterator;
1322 use crate::NonEmptyIterator;
1323
1324 let nonempty = nev![2, 4, 8];
1325 let output = nonempty
1326 .into_nonempty_iter()
1327 .map(|n| {
1328 if n % 2 == 0 {
1329 Ok(n)
1330 } else {
1331 Err("odd number!")
1332 }
1333 })
1334 .collect::<Result<NEVec<u32>, &'static str>>();
1335
1336 assert_eq!(output, Ok(nev![2, 4, 8]));
1337
1338 let nonempty = nev![2, 1, 8];
1339 let output = nonempty
1340 .into_nonempty_iter()
1341 .map(|n| {
1342 if n % 2 == 0 {
1343 Ok(n)
1344 } else {
1345 Err("odd number!")
1346 }
1347 })
1348 .collect::<Result<NEVec<u32>, &'static str>>();
1349
1350 assert_eq!(output, Err("odd number!"));
1351 }
1352
1353 #[test]
1354 fn test_as_slice() {
1355 let nonempty = NEVec::from((0, vec![1, 2, 3]));
1356 assert_eq!(
1357 crate::NESlice::try_from_slice(&[0, 1, 2, 3]).unwrap(),
1358 nonempty.as_nonempty_slice(),
1359 );
1360 }
1361
1362 #[test]
1363 fn debug_impl() {
1364 let actual = format!("{:?}", nev![0, 1, 2, 3]);
1365 let expected = format!("{:?}", vec![0, 1, 2, 3]);
1366 assert_eq!(expected, actual);
1367 }
1368
1369 #[test]
1370 fn sorting() {
1371 let mut n = nev![1, 5, 4, 3, 2, 1];
1372 n.sort();
1373 assert_eq!(nev![1, 1, 2, 3, 4, 5], n);
1374
1375 let mut m = nev![1];
1376 m.sort();
1377 assert_eq!(nev![1], m);
1378 }
1379
1380 #[test]
1381 fn extend() {
1382 let mut n = nev![1, 2, 3];
1383 let v = vec![4, 5, 6];
1384 n.extend(v);
1385
1386 assert_eq!(n, nev![1, 2, 3, 4, 5, 6]);
1387 }
1388
1389 #[test]
1390 fn iter_mut() {
1391 let mut v = nev![0, 1, 2, 3];
1392
1393 v.iter_mut().for_each(|x| {
1394 *x += 1;
1395 });
1396
1397 assert_eq!(nev![1, 2, 3, 4], v);
1398
1399 for x in &mut v {
1400 *x -= 1;
1401 }
1402 assert_eq!(nev![0, 1, 2, 3], v);
1403 }
1404
1405 #[test]
1406 fn retain() {
1407 // retain all
1408 let v = nev![0, 1, 2, 3];
1409 let result = v.retain(|_| true);
1410 assert_eq!(
1411 Ok(nev![0, 1, 2, 3]),
1412 result,
1413 "retaining all values should not change anything"
1414 );
1415 // retain none
1416 let v = nev![0, 1, 2, 3];
1417 let result = v.retain(|_| false);
1418 assert_eq!(
1419 Err(vec![]),
1420 result,
1421 "removing all values should return a regular vec"
1422 );
1423 // retain one
1424 let v = nev![3, 7];
1425 let result = v.retain_mut(|x| *x == 3);
1426 assert_eq!(Ok(nev![3]), result, "only 3 should remain");
1427 }
1428
1429 #[test]
1430 fn retain_mut() {
1431 // retain all
1432 let v = nev![0, 1, 2, 3];
1433 let result = v.retain_mut(|x| {
1434 *x += 1;
1435 true
1436 });
1437 assert_eq!(
1438 Ok(nev![1, 2, 3, 4]),
1439 result,
1440 "each value must be incremented by 1"
1441 );
1442 let v = nev![0, 1, 2, 3];
1443 // retain none
1444 let result = v.retain_mut(|x| {
1445 *x += 1;
1446 false
1447 });
1448 assert_eq!(
1449 Err(vec![]),
1450 result,
1451 "removing all values should return a regular vec"
1452 );
1453 // retain one
1454 let v = nev![3, 7];
1455 let result = v.retain_mut(|x| {
1456 if *x == 3 {
1457 *x += 1;
1458 true
1459 } else {
1460 false
1461 }
1462 });
1463 assert_eq!(Ok(nev![4]), result, "only 3+1 = 4 should remain");
1464 }
1465}