nonempty/lib.rs
1//! A Non-empty growable vector.
2//!
3//! Non-emptiness can be a powerful guarantee. If your main use of `Vec` is as
4//! an `Iterator`, then you may not need to distinguish on emptiness. But there
5//! are indeed times when the `Vec` you receive as as function argument needs to
6//! be non-empty or your function can't proceed. Similarly, there are times when
7//! the `Vec` you return to a calling user needs to promise it actually contains
8//! something.
9//!
10//! With `NonEmpty`, you're freed from the boilerplate of constantly needing to
11//! check `is_empty()` or pattern matching before proceeding, or erroring if you
12//! can't. So overall, code, type signatures, and logic become cleaner.
13//!
14//! Consider that unlike `Vec`, [`NonEmpty::first`] and [`NonEmpty::last`] don't
15//! return in `Option`, they always succeed.
16//!
17//! # Examples
18//!
19//! The simplest way to construct a [`NonEmpty`] is via the [`nonempty`] macro:
20//!
21//! ```
22//! # extern crate alloc;
23//! # use alloc::vec::Vec;
24//! use nonempty::{NonEmpty, nonempty};
25//!
26//! let l: NonEmpty<u32> = nonempty![1, 2, 3];
27//! assert_eq!(l.head, 1);
28//! ```
29//!
30//! Unlike the familiar `vec!` macro, `nonempty!` requires at least one element:
31//!
32//! ```
33//! # extern crate alloc;
34//! # use alloc::vec::Vec;
35//! use nonempty::nonempty;
36//!
37//! let l = nonempty![1];
38//!
39//! // Doesn't compile!
40//! // let l = nonempty![];
41//! ```
42//!
43//! Like `Vec`, you can also construct a [`NonEmpty`] the old fashioned way with
44//! [`NonEmpty::new`] or its constructor:
45//!
46//! ```
47//! # extern crate alloc;
48//! # use alloc::vec::Vec;
49//! use nonempty::NonEmpty;
50//!
51//! let mut l = NonEmpty { head: 42, tail: vec![36, 58] };
52//! assert_eq!(l.head, 42);
53//!
54//! l.push(9001);
55//! assert_eq!(l.last(), &9001);
56//! ```
57//!
58//! And if necessary, you're free to convert to and from `Vec`:
59//!
60//! ```
61//! use nonempty::{NonEmpty, nonempty};
62//!
63//! let l: NonEmpty<u32> = nonempty![42, 36, 58, 9001];
64//! let v: Vec<u32> = l.into();
65//! assert_eq!(v, vec![42, 36, 58, 9001]);
66//!
67//! let u: Option<NonEmpty<u32>> = NonEmpty::from_vec(v);
68//! assert_eq!(Some(nonempty![42, 36, 58, 9001]), u);
69//! ```
70//!
71//! # Caveats
72//!
73//! Since `NonEmpty` must have a least one element, it is not possible to
74//! implement the `FromIterator` trait for it. We can't know, in general, if
75//! any given `Iterator` actually contains something.
76
77#![no_std]
78
79//! # Features
80//!
81//! * `serialize`: `serde` support.
82//! * `arbitrary`: `arbitrary` support.
83#[cfg(feature = "arbitrary")]
84use arbitrary::Arbitrary;
85#[cfg(feature = "serialize")]
86use serde::{
87 ser::{SerializeSeq, Serializer},
88 Deserialize, Serialize,
89};
90
91use core::iter;
92use core::mem;
93use core::{cmp::Ordering, num::NonZeroUsize};
94
95#[cfg(feature = "std")]
96extern crate std;
97
98#[cfg_attr(test, macro_use)]
99extern crate alloc;
100use alloc::vec::{self, Vec};
101
102pub mod nonzero;
103
104/// Like the `vec!` macro, but enforces at least one argument. A nice short-hand
105/// for constructing [`NonEmpty`] values.
106///
107/// ```
108/// # extern crate alloc;
109/// # use alloc::vec::Vec;
110/// use nonempty::{NonEmpty, nonempty};
111///
112/// let v = nonempty![1, 2, 3];
113/// assert_eq!(v, NonEmpty { head: 1, tail: vec![2, 3] });
114///
115/// let v = nonempty![1];
116/// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() });
117///
118/// // Accepts trailing commas
119/// let v = nonempty![1,];
120/// assert_eq!(v, NonEmpty { head: 1, tail: Vec::new() });
121///
122/// // Doesn't compile!
123/// // let v = nonempty![];
124/// ```
125#[macro_export]
126macro_rules! nonempty {
127 ($h:expr, $( $x:expr ),* $(,)?) => {{
128 let tail = vec![$($x),*];
129 $crate::NonEmpty { head: $h, tail }
130 }};
131 ($h:expr) => {
132 $crate::NonEmpty {
133 head: $h,
134 tail: alloc::vec::Vec::new(),
135 }
136 };
137}
138
139/// Non-empty vector.
140#[cfg_attr(feature = "serialize", derive(Deserialize))]
141#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
142#[cfg_attr(feature = "serialize", serde(try_from = "Vec<T>"))]
143#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
144pub struct NonEmpty<T> {
145 pub head: T,
146 pub tail: Vec<T>,
147}
148
149// Nb. `Serialize` is implemented manually, as serde's `into` container attribute
150// requires a `T: Clone` bound which we'd like to avoid.
151#[cfg(feature = "serialize")]
152impl<T> Serialize for NonEmpty<T>
153where
154 T: Serialize,
155{
156 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
157 where
158 S: Serializer,
159 {
160 let mut seq = serializer.serialize_seq(Some(self.len()))?;
161 for e in self {
162 seq.serialize_element(e)?;
163 }
164 seq.end()
165 }
166}
167
168pub struct Iter<'a, T> {
169 head: Option<&'a T>,
170 tail: &'a [T],
171}
172
173impl<'a, T> Iterator for Iter<'a, T> {
174 type Item = &'a T;
175
176 fn next(&mut self) -> Option<Self::Item> {
177 if let Some(value) = self.head.take() {
178 Some(value)
179 } else if let Some((first, rest)) = self.tail.split_first() {
180 self.tail = rest;
181 Some(first)
182 } else {
183 None
184 }
185 }
186}
187
188impl<T> DoubleEndedIterator for Iter<'_, T> {
189 fn next_back(&mut self) -> Option<Self::Item> {
190 if let Some((last, rest)) = self.tail.split_last() {
191 self.tail = rest;
192 Some(last)
193 } else if let Some(first_value) = self.head.take() {
194 Some(first_value)
195 } else {
196 None
197 }
198 }
199}
200
201impl<T> ExactSizeIterator for Iter<'_, T> {
202 fn len(&self) -> usize {
203 self.tail.len() + self.head.map_or(0, |_| 1)
204 }
205}
206
207impl<T> core::iter::FusedIterator for Iter<'_, T> {}
208
209impl<T> NonEmpty<T> {
210 /// Alias for [`NonEmpty::singleton`].
211 pub const fn new(e: T) -> Self {
212 Self::singleton(e)
213 }
214
215 /// Converts from `&NonEmpty<T>` to `NonEmpty<&T>`.
216 pub fn as_ref(&self) -> NonEmpty<&T> {
217 NonEmpty {
218 head: &self.head,
219 tail: self.tail.iter().collect(),
220 }
221 }
222
223 /// Attempt to convert an iterator into a `NonEmpty` vector.
224 /// Returns `None` if the iterator was empty.
225 pub fn collect<I>(iter: I) -> Option<NonEmpty<T>>
226 where
227 I: IntoIterator<Item = T>,
228 {
229 let mut iter = iter.into_iter();
230 let head = iter.next()?;
231 Some(Self {
232 head,
233 tail: iter.collect(),
234 })
235 }
236
237 /// Create a new non-empty list with an initial element.
238 pub const fn singleton(head: T) -> Self {
239 NonEmpty {
240 head,
241 tail: Vec::new(),
242 }
243 }
244
245 /// Always returns false.
246 pub const fn is_empty(&self) -> bool {
247 false
248 }
249
250 /// Get the first element. Never fails.
251 pub const fn first(&self) -> &T {
252 &self.head
253 }
254
255 /// Get the mutable reference to the first element. Never fails.
256 ///
257 /// # Examples
258 ///
259 /// ```
260 /// use nonempty::NonEmpty;
261 ///
262 /// let mut non_empty = NonEmpty::new(42);
263 /// let head = non_empty.first_mut();
264 /// *head += 1;
265 /// assert_eq!(non_empty.first(), &43);
266 ///
267 /// let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
268 /// let head = non_empty.first_mut();
269 /// *head *= 42;
270 /// assert_eq!(non_empty.first(), &42);
271 /// ```
272 pub fn first_mut(&mut self) -> &mut T {
273 &mut self.head
274 }
275
276 /// Get the possibly-empty tail of the list.
277 ///
278 /// ```
279 /// use nonempty::NonEmpty;
280 ///
281 /// let non_empty = NonEmpty::new(42);
282 /// assert_eq!(non_empty.tail(), &[]);
283 ///
284 /// let non_empty = NonEmpty::from((1, vec![4, 2, 3]));
285 /// assert_eq!(non_empty.tail(), &[4, 2, 3]);
286 /// ```
287 pub fn tail(&self) -> &[T] {
288 &self.tail
289 }
290
291 /// Push an element to the end of the list.
292 pub fn push(&mut self, e: T) {
293 self.tail.push(e)
294 }
295
296 /// Pop an element from the end of the list.
297 pub fn pop(&mut self) -> Option<T> {
298 self.tail.pop()
299 }
300
301 /// Inserts an element at position index within the vector, shifting all elements after it to the right.
302 ///
303 /// # Panics
304 ///
305 /// Panics if index > len.
306 ///
307 /// # Examples
308 ///
309 /// ```
310 /// use nonempty::NonEmpty;
311 ///
312 /// let mut non_empty = NonEmpty::from((1, vec![2, 3]));
313 /// non_empty.insert(1, 4);
314 /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3])));
315 /// non_empty.insert(4, 5);
316 /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3, 5])));
317 /// non_empty.insert(0, 42);
318 /// assert_eq!(non_empty, NonEmpty::from((42, vec![1, 4, 2, 3, 5])));
319 /// ```
320 pub fn insert(&mut self, index: usize, element: T) {
321 let len = self.len();
322 assert!(index <= len);
323
324 if index == 0 {
325 let head = mem::replace(&mut self.head, element);
326 self.tail.insert(0, head);
327 } else {
328 self.tail.insert(index - 1, element);
329 }
330 }
331
332 /// Get the length of the list.
333 pub fn len(&self) -> usize {
334 self.tail.len() + 1
335 }
336
337 /// Gets the length of the list as a NonZeroUsize.
338 pub fn len_nonzero(&self) -> NonZeroUsize {
339 unsafe { NonZeroUsize::new_unchecked(self.tail.len().saturating_add(1)) }
340 }
341
342 /// Get the capacity of the list.
343 pub fn capacity(&self) -> usize {
344 self.tail.capacity() + 1
345 }
346
347 /// Get the last element. Never fails.
348 pub fn last(&self) -> &T {
349 match self.tail.last() {
350 None => &self.head,
351 Some(e) => e,
352 }
353 }
354
355 /// Get the last element mutably.
356 pub fn last_mut(&mut self) -> &mut T {
357 match self.tail.last_mut() {
358 None => &mut self.head,
359 Some(e) => e,
360 }
361 }
362
363 /// Check whether an element is contained in the list.
364 ///
365 /// ```
366 /// use nonempty::NonEmpty;
367 ///
368 /// let mut l = NonEmpty::from((42, vec![36, 58]));
369 ///
370 /// assert!(l.contains(&42));
371 /// assert!(!l.contains(&101));
372 /// ```
373 pub fn contains(&self, x: &T) -> bool
374 where
375 T: PartialEq,
376 {
377 self.iter().any(|e| e == x)
378 }
379
380 /// Get an element by index.
381 pub fn get(&self, index: usize) -> Option<&T> {
382 if index == 0 {
383 Some(&self.head)
384 } else {
385 self.tail.get(index - 1)
386 }
387 }
388
389 /// Get an element by index, mutably.
390 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
391 if index == 0 {
392 Some(&mut self.head)
393 } else {
394 self.tail.get_mut(index - 1)
395 }
396 }
397
398 /// Truncate the list to a certain size. Must be greater than `0`.
399 pub fn truncate(&mut self, len: usize) {
400 assert!(len >= 1);
401 self.tail.truncate(len - 1);
402 }
403
404 /// ```
405 /// use nonempty::NonEmpty;
406 ///
407 /// let mut l = NonEmpty::from((42, vec![36, 58]));
408 ///
409 /// let mut l_iter = l.iter();
410 ///
411 /// assert_eq!(l_iter.len(), 3);
412 /// assert_eq!(l_iter.next(), Some(&42));
413 /// assert_eq!(l_iter.next(), Some(&36));
414 /// assert_eq!(l_iter.next(), Some(&58));
415 /// assert_eq!(l_iter.next(), None);
416 /// ```
417 pub fn iter(&self) -> Iter<T> {
418 Iter {
419 head: Some(&self.head),
420 tail: &self.tail,
421 }
422 }
423
424 /// ```
425 /// use nonempty::NonEmpty;
426 ///
427 /// let mut l = NonEmpty::new(42);
428 /// l.push(36);
429 /// l.push(58);
430 ///
431 /// for i in l.iter_mut() {
432 /// *i *= 10;
433 /// }
434 ///
435 /// let mut l_iter = l.iter();
436 ///
437 /// assert_eq!(l_iter.next(), Some(&420));
438 /// assert_eq!(l_iter.next(), Some(&360));
439 /// assert_eq!(l_iter.next(), Some(&580));
440 /// assert_eq!(l_iter.next(), None);
441 /// ```
442 pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> + '_ {
443 iter::once(&mut self.head).chain(self.tail.iter_mut())
444 }
445
446 /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
447 /// proceeding with a computation. Using `from_slice` will give us a proof
448 /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
449 /// the caller to handle the `None` case.
450 ///
451 /// # Example Use
452 ///
453 /// ```
454 /// use nonempty::NonEmpty;
455 ///
456 /// let non_empty_vec = NonEmpty::from_slice(&[1, 2, 3, 4, 5]);
457 /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
458 ///
459 /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_slice(&[]);
460 /// assert!(empty_vec.is_none());
461 /// ```
462 pub fn from_slice(slice: &[T]) -> Option<NonEmpty<T>>
463 where
464 T: Clone,
465 {
466 slice.split_first().map(|(h, t)| NonEmpty {
467 head: h.clone(),
468 tail: t.into(),
469 })
470 }
471
472 /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
473 /// proceeding with a computation. Using `from_vec` will give us a proof
474 /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
475 /// the caller to handle the `None` case.
476 ///
477 /// This version will consume the `Vec` you pass in. If you would rather pass the data as a
478 /// slice then use `NonEmpty::from_slice`.
479 ///
480 /// # Example Use
481 ///
482 /// ```
483 /// use nonempty::NonEmpty;
484 ///
485 /// let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]);
486 /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
487 ///
488 /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_vec(vec![]);
489 /// assert!(empty_vec.is_none());
490 /// ```
491 pub fn from_vec(mut vec: Vec<T>) -> Option<NonEmpty<T>> {
492 if vec.is_empty() {
493 None
494 } else {
495 let head = vec.remove(0);
496 Some(NonEmpty { head, tail: vec })
497 }
498 }
499
500 /// Deconstruct a `NonEmpty` into its head and tail.
501 /// This operation never fails since we are guaranteed
502 /// to have a head element.
503 ///
504 /// # Example Use
505 ///
506 /// ```
507 /// use nonempty::NonEmpty;
508 ///
509 /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
510 ///
511 /// // Guaranteed to have the head and we also get the tail.
512 /// assert_eq!(non_empty.split_first(), (&1, &[2, 3, 4, 5][..]));
513 ///
514 /// let non_empty = NonEmpty::new(1);
515 ///
516 /// // Guaranteed to have the head element.
517 /// assert_eq!(non_empty.split_first(), (&1, &[][..]));
518 /// ```
519 pub fn split_first(&self) -> (&T, &[T]) {
520 (&self.head, &self.tail)
521 }
522
523 /// Deconstruct a `NonEmpty` into its first, last, and
524 /// middle elements, in that order.
525 ///
526 /// If there is only one element then last is `None`.
527 ///
528 /// # Example Use
529 ///
530 /// ```
531 /// use nonempty::NonEmpty;
532 ///
533 /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
534 ///
535 /// // When there are two or more elements, the last element is represented
536 /// // as a `Some`. Elements preceding it, except for the first, are returned
537 /// // in the middle.
538 /// assert_eq!(non_empty.split(), (&1, &[2, 3, 4][..], Some(&5)));
539 ///
540 /// let non_empty = NonEmpty::new(1);
541 ///
542 /// // The last element is `None` when there's only one element.
543 /// assert_eq!(non_empty.split(), (&1, &[][..], None));
544 /// ```
545 pub fn split(&self) -> (&T, &[T], Option<&T>) {
546 match self.tail.split_last() {
547 None => (&self.head, &[], None),
548 Some((last, middle)) => (&self.head, middle, Some(last)),
549 }
550 }
551
552 /// Append a `Vec` to the tail of the `NonEmpty`.
553 ///
554 /// # Example Use
555 ///
556 /// ```
557 /// use nonempty::NonEmpty;
558 ///
559 /// let mut non_empty = NonEmpty::new(1);
560 /// let mut vec = vec![2, 3, 4, 5];
561 /// non_empty.append(&mut vec);
562 ///
563 /// let mut expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
564 ///
565 /// assert_eq!(non_empty, expected);
566 /// ```
567 pub fn append(&mut self, other: &mut Vec<T>) {
568 self.tail.append(other)
569 }
570
571 /// A structure preserving `map`. This is useful for when
572 /// we wish to keep the `NonEmpty` structure guaranteeing
573 /// that there is at least one element. Otherwise, we can
574 /// use `nonempty.iter().map(f)`.
575 ///
576 /// # Examples
577 ///
578 /// ```
579 /// use nonempty::NonEmpty;
580 ///
581 /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
582 ///
583 /// let squares = non_empty.map(|i| i * i);
584 ///
585 /// let expected = NonEmpty::from((1, vec![4, 9, 16, 25]));
586 ///
587 /// assert_eq!(squares, expected);
588 /// ```
589 pub fn map<U, F>(self, mut f: F) -> NonEmpty<U>
590 where
591 F: FnMut(T) -> U,
592 {
593 NonEmpty {
594 head: f(self.head),
595 tail: self.tail.into_iter().map(f).collect(),
596 }
597 }
598
599 /// A structure preserving, fallible mapping function.
600 pub fn try_map<E, U, F>(self, mut f: F) -> Result<NonEmpty<U>, E>
601 where
602 F: FnMut(T) -> Result<U, E>,
603 {
604 Ok(NonEmpty {
605 head: f(self.head)?,
606 tail: self.tail.into_iter().map(f).collect::<Result<_, _>>()?,
607 })
608 }
609
610 /// When we have a function that goes from some `T` to a `NonEmpty<U>`,
611 /// we may want to apply it to a `NonEmpty<T>` but keep the structure flat.
612 /// This is where `flat_map` shines.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// use nonempty::NonEmpty;
618 ///
619 /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
620 ///
621 /// let windows = non_empty.flat_map(|i| {
622 /// let mut next = NonEmpty::new(i + 5);
623 /// next.push(i + 6);
624 /// next
625 /// });
626 ///
627 /// let expected = NonEmpty::from((6, vec![7, 7, 8, 8, 9, 9, 10, 10, 11]));
628 ///
629 /// assert_eq!(windows, expected);
630 /// ```
631 pub fn flat_map<U, F>(self, mut f: F) -> NonEmpty<U>
632 where
633 F: FnMut(T) -> NonEmpty<U>,
634 {
635 let mut heads = f(self.head);
636 let mut tails = self
637 .tail
638 .into_iter()
639 .flat_map(|t| f(t).into_iter())
640 .collect();
641 heads.append(&mut tails);
642 heads
643 }
644
645 /// Flatten nested `NonEmpty`s into a single one.
646 ///
647 /// # Examples
648 ///
649 /// ```
650 /// use nonempty::NonEmpty;
651 ///
652 /// let non_empty = NonEmpty::from((
653 /// NonEmpty::from((1, vec![2, 3])),
654 /// vec![NonEmpty::from((4, vec![5]))],
655 /// ));
656 ///
657 /// let expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
658 ///
659 /// assert_eq!(NonEmpty::flatten(non_empty), expected);
660 /// ```
661 pub fn flatten(full: NonEmpty<NonEmpty<T>>) -> Self {
662 full.flat_map(|n| n)
663 }
664
665 /// Binary searches this sorted non-empty vector for a given element.
666 ///
667 /// If the value is found then Result::Ok is returned, containing the index of the matching element.
668 /// If there are multiple matches, then any one of the matches could be returned.
669 ///
670 /// If the value is not found then Result::Err is returned, containing the index where a
671 /// matching element could be inserted while maintaining sorted order.
672 ///
673 /// # Examples
674 ///
675 /// ```
676 /// use nonempty::NonEmpty;
677 ///
678 /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
679 /// assert_eq!(non_empty.binary_search(&0), Ok(0));
680 /// assert_eq!(non_empty.binary_search(&13), Ok(9));
681 /// assert_eq!(non_empty.binary_search(&4), Err(7));
682 /// assert_eq!(non_empty.binary_search(&100), Err(13));
683 /// let r = non_empty.binary_search(&1);
684 /// assert!(match r { Ok(1..=4) => true, _ => false, });
685 /// ```
686 ///
687 /// If you want to insert an item to a sorted non-empty vector, while maintaining sort order:
688 ///
689 /// ```
690 /// use nonempty::NonEmpty;
691 ///
692 /// let mut non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
693 /// let num = 42;
694 /// let idx = non_empty.binary_search(&num).unwrap_or_else(|x| x);
695 /// non_empty.insert(idx, num);
696 /// assert_eq!(non_empty, NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55])));
697 /// ```
698 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
699 where
700 T: Ord,
701 {
702 self.binary_search_by(|p| p.cmp(x))
703 }
704
705 /// Binary searches this sorted non-empty with a comparator function.
706 ///
707 /// The comparator function should implement an order consistent with the sort order of the underlying slice,
708 /// returning an order code that indicates whether its argument is Less, Equal or Greater the desired target.
709 ///
710 /// If the value is found then Result::Ok is returned, containing the index of the matching element.
711 /// If there are multiple matches, then any one of the matches could be returned.
712 /// If the value is not found then Result::Err is returned, containing the index where a matching element could be
713 /// inserted while maintaining sorted order.
714 ///
715 /// # Examples
716 ///
717 /// Looks up a series of four elements. The first is found, with a uniquely determined
718 /// position; the second and third are not found; the fourth could match any position in `[1,4]`.
719 ///
720 /// ```
721 /// use nonempty::NonEmpty;
722 ///
723 /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
724 /// let seek = 0;
725 /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
726 /// let seek = 13;
727 /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
728 /// let seek = 4;
729 /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
730 /// let seek = 100;
731 /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
732 /// let seek = 1;
733 /// let r = non_empty.binary_search_by(|probe| probe.cmp(&seek));
734 /// assert!(match r { Ok(1..=4) => true, _ => false, });
735 /// ```
736 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
737 where
738 F: FnMut(&'a T) -> Ordering,
739 {
740 match f(&self.head) {
741 Ordering::Equal => Ok(0),
742 Ordering::Greater => Err(0),
743 Ordering::Less => self
744 .tail
745 .binary_search_by(f)
746 .map(|index| index + 1)
747 .map_err(|index| index + 1),
748 }
749 }
750
751 /// Binary searches this sorted non-empty vector with a key extraction function.
752 ///
753 /// Assumes that the vector is sorted by the key.
754 ///
755 /// If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches,
756 /// then any one of the matches could be returned. If the value is not found then Result::Err is returned,
757 /// containing the index where a matching element could be inserted while maintaining sorted order.
758 ///
759 /// # Examples
760 ///
761 /// Looks up a series of four elements in a non-empty vector of pairs sorted by their second elements.
762 /// The first is found, with a uniquely determined position; the second and third are not found;
763 /// the fourth could match any position in [1, 4].
764 ///
765 /// ```
766 /// use nonempty::NonEmpty;
767 ///
768 /// let non_empty = NonEmpty::from((
769 /// (0, 0),
770 /// vec![(2, 1), (4, 1), (5, 1), (3, 1),
771 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
772 /// (1, 21), (2, 34), (4, 55)]
773 /// ));
774 ///
775 /// assert_eq!(non_empty.binary_search_by_key(&0, |&(a,b)| b), Ok(0));
776 /// assert_eq!(non_empty.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
777 /// assert_eq!(non_empty.binary_search_by_key(&4, |&(a,b)| b), Err(7));
778 /// assert_eq!(non_empty.binary_search_by_key(&100, |&(a,b)| b), Err(13));
779 /// let r = non_empty.binary_search_by_key(&1, |&(a,b)| b);
780 /// assert!(match r { Ok(1..=4) => true, _ => false, });
781 /// ```
782 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
783 where
784 B: Ord,
785 F: FnMut(&'a T) -> B,
786 {
787 self.binary_search_by(|k| f(k).cmp(b))
788 }
789
790 /// Returns the maximum element in the non-empty vector.
791 ///
792 /// This will return the first item in the vector if the tail is empty.
793 ///
794 /// # Examples
795 ///
796 /// ```
797 /// use nonempty::NonEmpty;
798 ///
799 /// let non_empty = NonEmpty::new(42);
800 /// assert_eq!(non_empty.maximum(), &42);
801 ///
802 /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
803 /// assert_eq!(non_empty.maximum(), &76);
804 /// ```
805 pub fn maximum(&self) -> &T
806 where
807 T: Ord,
808 {
809 self.maximum_by(|i, j| i.cmp(j))
810 }
811
812 /// Returns the minimum element in the non-empty vector.
813 ///
814 /// This will return the first item in the vector if the tail is empty.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use nonempty::NonEmpty;
820 ///
821 /// let non_empty = NonEmpty::new(42);
822 /// assert_eq!(non_empty.minimum(), &42);
823 ///
824 /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
825 /// assert_eq!(non_empty.minimum(), &-34);
826 /// ```
827 pub fn minimum(&self) -> &T
828 where
829 T: Ord,
830 {
831 self.minimum_by(|i, j| i.cmp(j))
832 }
833
834 /// Returns the element that gives the maximum value with respect to the specified comparison function.
835 ///
836 /// This will return the first item in the vector if the tail is empty.
837 ///
838 /// # Examples
839 ///
840 /// ```
841 /// use nonempty::NonEmpty;
842 ///
843 /// let non_empty = NonEmpty::new((0, 42));
844 /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
845 ///
846 /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
847 /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(4, 42));
848 /// ```
849 pub fn maximum_by<F>(&self, mut compare: F) -> &T
850 where
851 F: FnMut(&T, &T) -> Ordering,
852 {
853 let mut max = &self.head;
854 for i in self.tail.iter() {
855 max = match compare(max, i) {
856 Ordering::Equal => max,
857 Ordering::Less => i,
858 Ordering::Greater => max,
859 };
860 }
861 max
862 }
863
864 /// Returns the element that gives the minimum value with respect to the specified comparison function.
865 ///
866 /// This will return the first item in the vector if the tail is empty.
867 ///
868 /// ```
869 /// use nonempty::NonEmpty;
870 ///
871 /// let non_empty = NonEmpty::new((0, 42));
872 /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
873 ///
874 /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
875 /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 76));
876 /// ```
877 pub fn minimum_by<F>(&self, mut compare: F) -> &T
878 where
879 F: FnMut(&T, &T) -> Ordering,
880 {
881 self.maximum_by(|a, b| compare(a, b).reverse())
882 }
883
884 /// Returns the element that gives the maximum value with respect to the specified function.
885 ///
886 /// This will return the first item in the vector if the tail is empty.
887 ///
888 /// # Examples
889 ///
890 /// ```
891 /// use nonempty::NonEmpty;
892 ///
893 /// let non_empty = NonEmpty::new((0, 42));
894 /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(0, 42));
895 ///
896 /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
897 /// assert_eq!(non_empty.maximum_by_key(|(k, _)| *k), &(4, 42));
898 /// assert_eq!(non_empty.maximum_by_key(|(k, _)| -k), &(0, 76));
899 /// ```
900 pub fn maximum_by_key<U, F>(&self, mut f: F) -> &T
901 where
902 U: Ord,
903 F: FnMut(&T) -> U,
904 {
905 self.maximum_by(|i, j| f(i).cmp(&f(j)))
906 }
907
908 /// Returns the element that gives the minimum value with respect to the specified function.
909 ///
910 /// This will return the first item in the vector if the tail is empty.
911 ///
912 /// # Examples
913 ///
914 /// ```
915 /// use nonempty::NonEmpty;
916 ///
917 /// let non_empty = NonEmpty::new((0, 42));
918 /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 42));
919 ///
920 /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
921 /// assert_eq!(non_empty.minimum_by_key(|(k, _)| *k), &(0, 76));
922 /// assert_eq!(non_empty.minimum_by_key(|(k, _)| -k), &(4, 42));
923 /// ```
924 pub fn minimum_by_key<U, F>(&self, mut f: F) -> &T
925 where
926 U: Ord,
927 F: FnMut(&T) -> U,
928 {
929 self.minimum_by(|i, j| f(i).cmp(&f(j)))
930 }
931
932 /// Sorts the nonempty.
933 ///
934 /// The implementation uses [`slice::sort`](slice::sort) for the tail and then checks where the
935 /// head belongs. If the head is already the smallest element, this should be as fast as sorting a
936 /// slice. However, if the head needs to be inserted, then it incurs extra cost for removing
937 /// the new head from the tail and adding the old head at the correct index.
938 ///
939 /// # Examples
940 ///
941 /// ```
942 /// use nonempty::nonempty;
943 ///
944 /// let mut non_empty = nonempty![-5, 4, 1, -3, 2];
945 ///
946 /// non_empty.sort();
947 /// assert!(non_empty == nonempty![-5, -3, 1, 2, 4]);
948 /// ```
949 pub fn sort(&mut self)
950 where
951 T: Ord,
952 {
953 self.tail.sort();
954 let index = match self.tail.binary_search(&self.head) {
955 Ok(index) => index,
956 Err(index) => index,
957 };
958
959 if index != 0 {
960 let new_head = self.tail.remove(0);
961 let head = mem::replace(&mut self.head, new_head);
962 self.tail.insert(index - 1, head);
963 }
964 }
965}
966
967impl<T: Default> Default for NonEmpty<T> {
968 fn default() -> Self {
969 Self::new(T::default())
970 }
971}
972
973impl<T> From<NonEmpty<T>> for Vec<T> {
974 /// Turns a non-empty list into a Vec.
975 fn from(nonempty: NonEmpty<T>) -> Vec<T> {
976 iter::once(nonempty.head).chain(nonempty.tail).collect()
977 }
978}
979
980impl<T> From<NonEmpty<T>> for (T, Vec<T>) {
981 /// Turns a non-empty list into a Vec.
982 fn from(nonempty: NonEmpty<T>) -> (T, Vec<T>) {
983 (nonempty.head, nonempty.tail)
984 }
985}
986
987impl<T> From<(T, Vec<T>)> for NonEmpty<T> {
988 /// Turns a pair of an element and a Vec into
989 /// a NonEmpty.
990 fn from((head, tail): (T, Vec<T>)) -> Self {
991 NonEmpty { head, tail }
992 }
993}
994
995impl<T> IntoIterator for NonEmpty<T> {
996 type Item = T;
997 type IntoIter = iter::Chain<iter::Once<T>, vec::IntoIter<Self::Item>>;
998
999 fn into_iter(self) -> Self::IntoIter {
1000 iter::once(self.head).chain(self.tail)
1001 }
1002}
1003
1004impl<'a, T> IntoIterator for &'a NonEmpty<T> {
1005 type Item = &'a T;
1006 type IntoIter = iter::Chain<iter::Once<&'a T>, core::slice::Iter<'a, T>>;
1007
1008 fn into_iter(self) -> Self::IntoIter {
1009 iter::once(&self.head).chain(self.tail.iter())
1010 }
1011}
1012
1013impl<T> core::ops::Index<usize> for NonEmpty<T> {
1014 type Output = T;
1015
1016 /// ```
1017 /// use nonempty::NonEmpty;
1018 ///
1019 /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
1020 ///
1021 /// assert_eq!(non_empty[0], 1);
1022 /// assert_eq!(non_empty[1], 2);
1023 /// assert_eq!(non_empty[3], 4);
1024 /// ```
1025 fn index(&self, index: usize) -> &T {
1026 if index > 0 {
1027 &self.tail[index - 1]
1028 } else {
1029 &self.head
1030 }
1031 }
1032}
1033
1034impl<T> core::ops::IndexMut<usize> for NonEmpty<T> {
1035 fn index_mut(&mut self, index: usize) -> &mut T {
1036 if index > 0 {
1037 &mut self.tail[index - 1]
1038 } else {
1039 &mut self.head
1040 }
1041 }
1042}
1043
1044impl<A> Extend<A> for NonEmpty<A> {
1045 fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
1046 self.tail.extend(iter)
1047 }
1048}
1049
1050#[cfg(feature = "serialize")]
1051pub mod serialize {
1052 use core::{convert::TryFrom, fmt};
1053
1054 use alloc::vec::Vec;
1055
1056 use super::NonEmpty;
1057
1058 #[derive(Debug)]
1059 pub enum Error {
1060 Empty,
1061 }
1062
1063 impl fmt::Display for Error {
1064 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1065 match self {
1066 Self::Empty => f.write_str(
1067 "the vector provided was empty, NonEmpty needs at least one element",
1068 ),
1069 }
1070 }
1071 }
1072
1073 impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
1074 type Error = Error;
1075
1076 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1077 NonEmpty::from_vec(vec).ok_or(Error::Empty)
1078 }
1079 }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use alloc::{string::String, vec::Vec};
1085
1086 use crate::NonEmpty;
1087
1088 #[test]
1089 fn test_from_conversion() {
1090 let result = NonEmpty::from((1, vec![2, 3, 4, 5]));
1091 let expected = NonEmpty {
1092 head: 1,
1093 tail: vec![2, 3, 4, 5],
1094 };
1095 assert_eq!(result, expected);
1096 }
1097
1098 #[test]
1099 fn test_into_iter() {
1100 let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1101 for (i, n) in nonempty.into_iter().enumerate() {
1102 assert_eq!(i as i32, n);
1103 }
1104 }
1105
1106 #[test]
1107 fn test_iter_syntax() {
1108 let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1109 for n in &nonempty {
1110 let _ = *n; // Prove that we're dealing with references.
1111 }
1112 for _ in nonempty {}
1113 }
1114
1115 #[test]
1116 fn test_iter_both_directions() {
1117 let mut nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1118 assert_eq!(nonempty.iter().cloned().collect::<Vec<_>>(), [0, 1, 2, 3]);
1119 assert_eq!(
1120 nonempty.iter().rev().cloned().collect::<Vec<_>>(),
1121 [3, 2, 1, 0]
1122 );
1123 assert_eq!(
1124 nonempty.iter_mut().rev().collect::<Vec<_>>(),
1125 [&mut 3, &mut 2, &mut 1, &mut 0]
1126 );
1127 }
1128
1129 #[test]
1130 fn test_iter_both_directions_at_once() {
1131 let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
1132 let mut i = nonempty.iter();
1133 assert_eq!(i.next(), Some(&0));
1134 assert_eq!(i.next_back(), Some(&3));
1135 assert_eq!(i.next(), Some(&1));
1136 assert_eq!(i.next_back(), Some(&2));
1137 assert_eq!(i.next(), None);
1138 assert_eq!(i.next_back(), None);
1139 }
1140
1141 #[test]
1142 fn test_mutate_head() {
1143 let mut non_empty = NonEmpty::new(42);
1144 non_empty.head += 1;
1145 assert_eq!(non_empty.head, 43);
1146
1147 let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
1148 non_empty.head *= 42;
1149 assert_eq!(non_empty.head, 42);
1150 }
1151
1152 #[test]
1153 fn test_to_nonempty() {
1154 use core::iter::{empty, once};
1155
1156 assert_eq!(NonEmpty::<()>::collect(empty()), None);
1157 assert_eq!(NonEmpty::<()>::collect(once(())), Some(NonEmpty::new(())));
1158 assert_eq!(
1159 NonEmpty::<u8>::collect(once(1).chain(once(2))),
1160 Some(nonempty!(1, 2))
1161 );
1162 }
1163
1164 #[test]
1165 fn test_try_map() {
1166 assert_eq!(
1167 nonempty!(1, 2, 3, 4).try_map(Ok::<_, String>),
1168 Ok(nonempty!(1, 2, 3, 4))
1169 );
1170 assert_eq!(
1171 nonempty!(1, 2, 3, 4).try_map(|i| if i % 2 == 0 { Ok(i) } else { Err("not even") }),
1172 Err("not even")
1173 );
1174 }
1175
1176 #[test]
1177 fn test_nontrivial_minimum_by_key() {
1178 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1179 struct Position {
1180 x: i32,
1181 y: i32,
1182 }
1183 impl Position {
1184 pub fn distance_squared(&self, other: Position) -> u32 {
1185 let dx = self.x - other.x;
1186 let dy = self.y - other.y;
1187 (dx * dx + dy * dy) as u32
1188 }
1189 }
1190 let positions = nonempty![
1191 Position { x: 1, y: 1 },
1192 Position { x: 0, y: 0 },
1193 Position { x: 3, y: 4 }
1194 ];
1195 let target = Position { x: 1, y: 2 };
1196 let closest = positions.minimum_by_key(|position| position.distance_squared(target));
1197 assert_eq!(closest, &Position { x: 1, y: 1 });
1198 }
1199
1200 #[test]
1201 fn test_sort() {
1202 let mut numbers = nonempty![1];
1203 numbers.sort();
1204 assert_eq!(numbers, nonempty![1]);
1205
1206 let mut numbers = nonempty![2, 1, 3];
1207 numbers.sort();
1208 assert_eq!(numbers, nonempty![1, 2, 3]);
1209
1210 let mut numbers = nonempty![1, 3, 2];
1211 numbers.sort();
1212 assert_eq!(numbers, nonempty![1, 2, 3]);
1213
1214 let mut numbers = nonempty![3, 2, 1];
1215 numbers.sort();
1216 assert_eq!(numbers, nonempty![1, 2, 3]);
1217 }
1218
1219 #[cfg(feature = "serialize")]
1220 mod serialize {
1221 use crate::NonEmpty;
1222 use alloc::boxed::Box;
1223 use serde::{Deserialize, Serialize};
1224
1225 #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
1226 pub struct SimpleSerializable(pub i32);
1227
1228 #[test]
1229 fn test_simple_round_trip() -> Result<(), Box<dyn core::error::Error>> {
1230 // Given
1231 let mut non_empty = NonEmpty::new(SimpleSerializable(42));
1232 non_empty.push(SimpleSerializable(777));
1233
1234 // When
1235 let res = serde_json::from_str::<'_, NonEmpty<SimpleSerializable>>(
1236 &serde_json::to_string(&non_empty)?,
1237 )?;
1238
1239 // Then
1240 assert_eq!(res, non_empty);
1241
1242 Ok(())
1243 }
1244
1245 #[test]
1246 fn test_serialization() -> Result<(), Box<dyn core::error::Error>> {
1247 let ne = nonempty![1, 2, 3, 4, 5];
1248 let ve = vec![1, 2, 3, 4, 5];
1249
1250 assert_eq!(serde_json::to_string(&ne)?, serde_json::to_string(&ve)?);
1251
1252 Ok(())
1253 }
1254 }
1255
1256 #[cfg(feature = "arbitrary")]
1257 mod arbitrary {
1258 use crate::NonEmpty;
1259 use arbitrary::{Arbitrary, Unstructured};
1260
1261 #[test]
1262 fn test_arbitrary_empty_tail() -> arbitrary::Result<()> {
1263 let mut u = Unstructured::new(&[1, 2, 3, 4]);
1264 let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1265 assert!(!ne.is_empty());
1266 assert_eq!(
1267 ne,
1268 NonEmpty {
1269 head: 67305985,
1270 tail: vec![],
1271 }
1272 );
1273 Ok(())
1274 }
1275
1276 #[test]
1277 fn test_arbitrary_with_tail() -> arbitrary::Result<()> {
1278 let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
1279 let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1280 assert!(!ne.is_empty());
1281 assert_eq!(
1282 ne,
1283 NonEmpty {
1284 head: 67305985,
1285 tail: vec![526086],
1286 }
1287 );
1288 Ok(())
1289 }
1290
1291 #[test]
1292 fn test_arbitrary_with_split() -> arbitrary::Result<()> {
1293 let mut u = Unstructured::new(&[1, 2, 3, 4, 5, 6, 7, 8]);
1294 let ne = NonEmpty::<i32>::arbitrary(&mut u)?;
1295 let (head, middle, last) = ne.split();
1296 let mut tail = middle.to_vec();
1297 tail.extend(last);
1298 assert_eq!(ne, NonEmpty { head: *head, tail });
1299 Ok(())
1300 }
1301 }
1302}