nonempty/
lib.rs

1//! A Non-empty growable vector.
2//!
3//! # Examples
4//!
5//! ```
6//! use nonempty::NonEmpty;
7//!
8//! let mut l = NonEmpty { head: 42, tail: vec![36, 58] };
9//!
10//! assert_eq!(l.head, 42);
11//!
12//! l.push(9001);
13//!
14//! assert_eq!(l.last(), &9001);
15//!
16//! let v: Vec<i32> = l.into();
17//! assert_eq!(v, vec![42, 36, 58, 9001]);
18//! ```
19#[cfg(feature = "serialize")]
20use serde::{Deserialize, Serialize};
21use std::cmp::Ordering;
22use std::mem;
23use std::{iter, vec};
24
25#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
26#[cfg_attr(
27    feature = "serialize",
28    serde(bound(serialize = "T: Clone + Serialize")),
29    serde(into = "Vec<T>", try_from = "Vec<T>")
30)]
31#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
32pub struct NonEmpty<T> {
33    pub head: T,
34    pub tail: Vec<T>,
35}
36
37impl<T> NonEmpty<T> {
38    /// Alias for [`NonEmpty::singleton`].
39    pub const fn new(e: T) -> Self {
40        Self::singleton(e)
41    }
42
43    /// Create a new non-empty list with an initial element.
44    pub const fn singleton(head: T) -> Self {
45        NonEmpty {
46            head,
47            tail: Vec::new(),
48        }
49    }
50
51    /// Always returns false.
52    pub const fn is_empty(&self) -> bool {
53        false
54    }
55
56    /// Get the first element. Never fails.
57    pub const fn first(&self) -> &T {
58        &self.head
59    }
60
61    /// Get the mutable reference to the first element. Never fails.
62    ///
63    /// # Examples
64    ///
65    /// ```
66    /// use nonempty::NonEmpty;
67    ///
68    /// let mut non_empty = NonEmpty::new(42);
69    /// let head = non_empty.first_mut();
70    /// *head += 1;
71    /// assert_eq!(non_empty.first(), &43);
72    ///
73    /// let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
74    /// let head = non_empty.first_mut();
75    /// *head *= 42;
76    /// assert_eq!(non_empty.first(), &42);
77    /// ```
78    pub fn first_mut(&mut self) -> &mut T {
79        &mut self.head
80    }
81
82    /// Get the possibly-empty tail of the list.
83    ///
84    /// ```
85    /// use nonempty::NonEmpty;
86    ///
87    /// let non_empty = NonEmpty::new(42);
88    /// assert_eq!(non_empty.tail(), &[]);
89    ///
90    /// let non_empty = NonEmpty::from((1, vec![4, 2, 3]));
91    /// assert_eq!(non_empty.tail(), &[4, 2, 3]);
92    /// ```
93    pub fn tail(&self) -> &[T] {
94        &self.tail
95    }
96
97    /// Push an element to the end of the list.
98    pub fn push(&mut self, e: T) {
99        self.tail.push(e)
100    }
101
102    /// Pop an element from the end of the list.
103    pub fn pop(&mut self) -> Option<T> {
104        self.tail.pop()
105    }
106
107    /// Inserts an element at position index within the vector, shifting all elements after it to the right.
108    ///
109    /// # Panics
110    ///
111    /// Panics if index > len.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// use nonempty::NonEmpty;
117    ///
118    /// let mut non_empty = NonEmpty::from((1, vec![2, 3]));
119    /// non_empty.insert(1, 4);
120    /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3])));
121    /// non_empty.insert(4, 5);
122    /// assert_eq!(non_empty, NonEmpty::from((1, vec![4, 2, 3, 5])));
123    /// non_empty.insert(0, 42);
124    /// assert_eq!(non_empty, NonEmpty::from((42, vec![1, 4, 2, 3, 5])));
125    /// ```
126    pub fn insert(&mut self, index: usize, element: T) {
127        let len = self.len();
128        assert!(index <= len);
129
130        if index == 0 {
131            let head = mem::replace(&mut self.head, element);
132            self.tail.insert(0, head);
133        } else {
134            self.tail.insert(index - 1, element);
135        }
136    }
137
138    /// Get the length of the list.
139    pub fn len(&self) -> usize {
140        self.tail.len() + 1
141    }
142
143    /// Get the capacity of the list.
144    pub fn capacity(&self) -> usize {
145        self.tail.capacity() + 1
146    }
147
148    /// Get the last element. Never fails.
149    pub fn last(&self) -> &T {
150        match self.tail.last() {
151            None => &self.head,
152            Some(e) => e,
153        }
154    }
155
156    /// Get the last element mutably.
157    pub fn last_mut(&mut self) -> &mut T {
158        match self.tail.last_mut() {
159            None => &mut self.head,
160            Some(e) => e,
161        }
162    }
163
164    /// Check whether an element is contained in the list.
165    ///
166    /// ```
167    /// use nonempty::NonEmpty;
168    ///
169    /// let mut l = NonEmpty::from((42, vec![36, 58]));
170    ///
171    /// assert!(l.contains(&42));
172    /// assert!(!l.contains(&101));
173    /// ```
174    pub fn contains(&self, x: &T) -> bool
175    where
176        T: PartialEq,
177    {
178        self.iter().any(|e| e == x)
179    }
180
181    /// Get an element by index.
182    pub fn get(&self, index: usize) -> Option<&T> {
183        if index == 0 {
184            Some(&self.head)
185        } else {
186            self.tail.get(index - 1)
187        }
188    }
189
190    /// Get an element by index, mutably.
191    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
192        if index == 0 {
193            Some(&mut self.head)
194        } else {
195            self.tail.get_mut(index - 1)
196        }
197    }
198
199    /// Truncate the list to a certain size. Must be greater than `0`.
200    pub fn truncate(&mut self, len: usize) {
201        assert!(len >= 1);
202        self.tail.truncate(len - 1);
203    }
204
205    /// ```
206    /// use nonempty::NonEmpty;
207    ///
208    /// let mut l = NonEmpty::from((42, vec![36, 58]));
209    ///
210    /// let mut l_iter = l.iter();
211    ///
212    /// assert_eq!(l_iter.next(), Some(&42));
213    /// assert_eq!(l_iter.next(), Some(&36));
214    /// assert_eq!(l_iter.next(), Some(&58));
215    /// assert_eq!(l_iter.next(), None);
216    /// ```
217    pub fn iter<'a>(&'a self) -> impl Iterator<Item = &T> + 'a {
218        iter::once(&self.head).chain(self.tail.iter())
219    }
220
221    /// ```
222    /// use nonempty::NonEmpty;
223    ///
224    /// let mut l = NonEmpty::new(42);
225    /// l.push(36);
226    /// l.push(58);
227    ///
228    /// for i in l.iter_mut() {
229    ///     *i *= 10;
230    /// }
231    ///
232    /// let mut l_iter = l.iter();
233    ///
234    /// assert_eq!(l_iter.next(), Some(&420));
235    /// assert_eq!(l_iter.next(), Some(&360));
236    /// assert_eq!(l_iter.next(), Some(&580));
237    /// assert_eq!(l_iter.next(), None);
238    /// ```
239    pub fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &mut T> + 'a {
240        iter::once(&mut self.head).chain(self.tail.iter_mut())
241    }
242
243    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
244    /// proceeding with a computation. Using `from_slice` will give us a proof
245    /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
246    /// the caller to handle the `None` case.
247    ///
248    /// # Example Use
249    ///
250    /// ```
251    /// use nonempty::NonEmpty;
252    ///
253    /// let non_empty_vec = NonEmpty::from_slice(&[1, 2, 3, 4, 5]);
254    /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
255    ///
256    /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_slice(&[]);
257    /// assert!(empty_vec.is_none());
258    /// ```
259    pub fn from_slice(slice: &[T]) -> Option<NonEmpty<T>>
260    where
261        T: Clone,
262    {
263        slice.split_first().map(|(h, t)| NonEmpty {
264            head: h.clone(),
265            tail: t.into(),
266        })
267    }
268
269    /// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
270    /// proceeding with a computation. Using `from_vec` will give us a proof
271    /// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
272    /// the caller to handle the `None` case.
273    ///
274    /// This version will consume the `Vec` you pass in. If you would rather pass the data as a
275    /// slice then use `NonEmpty::from_slice`.
276    ///
277    /// # Example Use
278    ///
279    /// ```
280    /// use nonempty::NonEmpty;
281    ///
282    /// let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]);
283    /// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
284    ///
285    /// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_vec(vec![]);
286    /// assert!(empty_vec.is_none());
287    /// ```
288    pub fn from_vec(mut vec: Vec<T>) -> Option<NonEmpty<T>> {
289        if vec.is_empty() {
290            None
291        } else {
292            let head = vec.remove(0);
293            Some(NonEmpty { head, tail: vec })
294        }
295    }
296
297    /// Deconstruct a `NonEmpty` into its head and tail.
298    /// This operation never fails since we are guranteed
299    /// to have a head element.
300    ///
301    /// # Example Use
302    ///
303    /// ```
304    /// use nonempty::NonEmpty;
305    ///
306    /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
307    ///
308    /// // Guaranteed to have the head and we also get the tail.
309    /// assert_eq!(non_empty.split_first(), (&1, &[2, 3, 4, 5][..]));
310    ///
311    /// let non_empty = NonEmpty::new(1);
312    ///
313    /// // Guaranteed to have the head element.
314    /// assert_eq!(non_empty.split_first(), (&1, &[][..]));
315    /// ```
316    pub fn split_first(&self) -> (&T, &[T]) {
317        (&self.head, &self.tail)
318    }
319
320    /// Deconstruct a `NonEmpty` into its first, last, and
321    /// middle elements, in that order.
322    ///
323    /// If there is only one element then first == last.
324    ///
325    /// # Example Use
326    ///
327    /// ```
328    /// use nonempty::NonEmpty;
329    ///
330    /// let mut non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
331    ///
332    /// // Guaranteed to have the last element and the elements
333    /// // preceding it.
334    /// assert_eq!(non_empty.split(), (&1, &[2, 3, 4][..], &5));
335    ///
336    /// let non_empty = NonEmpty::new(1);
337    ///
338    /// // Guaranteed to have the last element.
339    /// assert_eq!(non_empty.split(), (&1, &[][..], &1));
340    /// ```
341    pub fn split(&self) -> (&T, &[T], &T) {
342        match self.tail.split_last() {
343            None => (&self.head, &[], &self.head),
344            Some((last, middle)) => (&self.head, middle, last),
345        }
346    }
347
348    /// Append a `Vec` to the tail of the `NonEmpty`.
349    ///
350    /// # Example Use
351    ///
352    /// ```
353    /// use nonempty::NonEmpty;
354    ///
355    /// let mut non_empty = NonEmpty::new(1);
356    /// let mut vec = vec![2, 3, 4, 5];
357    /// non_empty.append(&mut vec);
358    ///
359    /// let mut expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
360    ///
361    /// assert_eq!(non_empty, expected);
362    /// ```
363    pub fn append(&mut self, other: &mut Vec<T>) {
364        self.tail.append(other)
365    }
366
367    /// A structure preserving `map`. This is useful for when
368    /// we wish to keep the `NonEmpty` structure guaranteeing
369    /// that there is at least one element. Otherwise, we can
370    /// use `nonempty.iter().map(f)`.
371    ///
372    /// # Examples
373    ///
374    /// ```
375    /// use nonempty::NonEmpty;
376    ///
377    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
378    ///
379    /// let squares = non_empty.map(|i| i * i);
380    ///
381    /// let expected = NonEmpty::from((1, vec![4, 9, 16, 25]));
382    ///
383    /// assert_eq!(squares, expected);
384    /// ```
385    pub fn map<U, F>(self, mut f: F) -> NonEmpty<U>
386    where
387        F: FnMut(T) -> U,
388    {
389        NonEmpty {
390            head: f(self.head),
391            tail: self.tail.into_iter().map(f).collect(),
392        }
393    }
394
395    /// When we have a function that goes from some `T` to a `NonEmpty<U>`,
396    /// we may want to apply it to a `NonEmpty<T>` but keep the structure flat.
397    /// This is where `flat_map` shines.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use nonempty::NonEmpty;
403    ///
404    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
405    ///
406    /// let windows = non_empty.flat_map(|i| {
407    ///     let mut next = NonEmpty::new(i + 5);
408    ///     next.push(i + 6);
409    ///     next
410    /// });
411    ///
412    /// let expected = NonEmpty::from((6, vec![7, 7, 8, 8, 9, 9, 10, 10, 11]));
413    ///
414    /// assert_eq!(windows, expected);
415    /// ```
416    pub fn flat_map<U, F>(self, mut f: F) -> NonEmpty<U>
417    where
418        F: FnMut(T) -> NonEmpty<U>,
419    {
420        let mut heads = f(self.head);
421        let mut tails = self
422            .tail
423            .into_iter()
424            .flat_map(|t| f(t).into_iter())
425            .collect();
426        heads.append(&mut tails);
427        heads
428    }
429
430    /// Flatten nested `NonEmpty`s into a single one.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use nonempty::NonEmpty;
436    ///
437    /// let non_empty = NonEmpty::from((
438    ///     NonEmpty::from((1, vec![2, 3])),
439    ///     vec![NonEmpty::from((4, vec![5]))],
440    /// ));
441    ///
442    /// let expected = NonEmpty::from((1, vec![2, 3, 4, 5]));
443    ///
444    /// assert_eq!(NonEmpty::flatten(non_empty), expected);
445    /// ```
446    pub fn flatten(full: NonEmpty<NonEmpty<T>>) -> Self {
447        full.flat_map(|n| n)
448    }
449
450    /// Binary searches this sorted non-empty vector for a given element.
451    ///
452    /// If the value is found then Result::Ok is returned, containing the index of the matching element.
453    /// If there are multiple matches, then any one of the matches could be returned.
454    ///
455    /// If the value is not found then Result::Err is returned, containing the index where a
456    /// matching element could be inserted while maintaining sorted order.
457    ///
458    /// # Examples
459    ///
460    /// ```
461    /// use nonempty::NonEmpty;
462    ///
463    /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
464    /// assert_eq!(non_empty.binary_search(&0),   Ok(0));
465    /// assert_eq!(non_empty.binary_search(&13),  Ok(9));
466    /// assert_eq!(non_empty.binary_search(&4),   Err(7));
467    /// assert_eq!(non_empty.binary_search(&100), Err(13));
468    /// let r = non_empty.binary_search(&1);
469    /// assert!(match r { Ok(1..=4) => true, _ => false, });
470    /// ```
471    ///
472    /// If you want to insert an item to a sorted non-empty vector, while maintaining sort order:
473    ///
474    /// ```
475    /// use nonempty::NonEmpty;
476    ///
477    /// let mut non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
478    /// let num = 42;
479    /// let idx = non_empty.binary_search(&num).unwrap_or_else(|x| x);
480    /// non_empty.insert(idx, num);
481    /// assert_eq!(non_empty, NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55])));
482    /// ```
483    pub fn binary_search(&self, x: &T) -> Result<usize, usize>
484    where
485        T: Ord,
486    {
487        self.binary_search_by(|p| p.cmp(x))
488    }
489
490    /// Binary searches this sorted non-empty with a comparator function.
491    ///
492    /// The comparator function should implement an order consistent with the sort order of the underlying slice,
493    /// returning an order code that indicates whether its argument is Less, Equal or Greater the desired target.
494    ///
495    /// If the value is found then Result::Ok is returned, containing the index of the matching element.
496    /// If there are multiple matches, then any one of the matches could be returned.
497    /// If the value is not found then Result::Err is returned, containing the index where a matching element could be
498    /// inserted while maintaining sorted order.
499    ///
500    /// # Examples
501    ///
502    /// Looks up a series of four elements. The first is found, with a uniquely determined
503    /// position; the second and third are not found; the fourth could match any position in [1,4].
504    ///
505    /// ```
506    /// use nonempty::NonEmpty;
507    ///
508    /// let non_empty = NonEmpty::from((0, vec![1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]));
509    /// let seek = 0;
510    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(0));
511    /// let seek = 13;
512    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
513    /// let seek = 4;
514    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
515    /// let seek = 100;
516    /// assert_eq!(non_empty.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
517    /// let seek = 1;
518    /// let r = non_empty.binary_search_by(|probe| probe.cmp(&seek));
519    /// assert!(match r { Ok(1..=4) => true, _ => false, });
520    /// ```
521    pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
522    where
523        F: FnMut(&'a T) -> Ordering,
524    {
525        match f(&self.head) {
526            Ordering::Equal => Ok(0),
527            Ordering::Greater => Err(0),
528            Ordering::Less => self
529                .tail
530                .binary_search_by(f)
531                .map(|index| index + 1)
532                .map_err(|index| index + 1),
533        }
534    }
535
536    /// Binary searches this sorted non-empty vector with a key extraction function.
537    ///
538    /// Assumes that the vector is sorted by the key.
539    ///
540    /// If the value is found then Result::Ok is returned, containing the index of the matching element. If there are multiple matches,
541    /// then any one of the matches could be returned. If the value is not found then Result::Err is returned,
542    /// containing the index where a matching element could be inserted while maintaining sorted order.
543    ///
544    /// # Examples
545    ///
546    /// Looks up a series of four elements in a non-empty vector of pairs sorted by their second elements.
547    /// The first is found, with a uniquely determined position; the second and third are not found;
548    /// the fourth could match any position in [1, 4].
549    ///
550    /// ```
551    /// use nonempty::NonEmpty;
552    ///
553    /// let non_empty = NonEmpty::from((
554    ///     (0, 0),
555    ///     vec![(2, 1), (4, 1), (5, 1), (3, 1),
556    ///          (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
557    ///          (1, 21), (2, 34), (4, 55)]
558    /// ));
559    ///
560    /// assert_eq!(non_empty.binary_search_by_key(&0, |&(a,b)| b),  Ok(0));
561    /// assert_eq!(non_empty.binary_search_by_key(&13, |&(a,b)| b),  Ok(9));
562    /// assert_eq!(non_empty.binary_search_by_key(&4, |&(a,b)| b),   Err(7));
563    /// assert_eq!(non_empty.binary_search_by_key(&100, |&(a,b)| b), Err(13));
564    /// let r = non_empty.binary_search_by_key(&1, |&(a,b)| b);
565    /// assert!(match r { Ok(1..=4) => true, _ => false, });
566    /// ```
567    pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
568    where
569        B: Ord,
570        F: FnMut(&'a T) -> B,
571    {
572        self.binary_search_by(|k| f(k).cmp(b))
573    }
574
575    /// Returns the maximum element in the non-empty vector.
576    ///
577    /// This will return the first item in the vector if the tail is empty.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use nonempty::NonEmpty;
583    ///
584    /// let non_empty = NonEmpty::new(42);
585    /// assert_eq!(non_empty.maximum(), &42);
586    ///
587    /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
588    /// assert_eq!(non_empty.maximum(), &76);
589    /// ```
590    pub fn maximum(&self) -> &T
591    where
592        T: Ord,
593    {
594        self.maximum_by(|i, j| i.cmp(j))
595    }
596
597    /// Returns the minimum element in the non-empty vector.
598    ///
599    /// This will return the first item in the vector if the tail is empty.
600    ///
601    /// # Examples
602    ///
603    /// ```
604    /// use nonempty::NonEmpty;
605    ///
606    /// let non_empty = NonEmpty::new(42);
607    /// assert_eq!(non_empty.minimum(), &42);
608    ///
609    /// let non_empty = NonEmpty::from((1, vec![-34, 42, 76, 4, 5]));
610    /// assert_eq!(non_empty.minimum(), &-34);
611    /// ```
612    pub fn minimum(&self) -> &T
613    where
614        T: Ord,
615    {
616        self.minimum_by(|i, j| i.cmp(j))
617    }
618
619    /// Returns the element that gives the maximum value with respect to the specified comparison function.
620    ///
621    /// This will return the first item in the vector if the tail is empty.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// use nonempty::NonEmpty;
627    ///
628    /// let non_empty = NonEmpty::new((0, 42));
629    /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
630    ///
631    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
632    /// assert_eq!(non_empty.maximum_by(|(k, _), (l, _)| k.cmp(l)), &(4, 42));
633    /// ```
634    pub fn maximum_by<F>(&self, compare: F) -> &T
635    where
636        F: Fn(&T, &T) -> Ordering,
637    {
638        let mut max = &self.head;
639        for i in self.tail.iter() {
640            max = match compare(&max, &i) {
641                Ordering::Equal => max,
642                Ordering::Less => &i,
643                Ordering::Greater => max,
644            };
645        }
646        max
647    }
648
649    /// Returns the element that gives the minimum value with respect to the specified comparison function.
650    ///
651    /// This will return the first item in the vector if the tail is empty.
652    ///
653    /// ```
654    /// use nonempty::NonEmpty;
655    ///
656    /// let non_empty = NonEmpty::new((0, 42));
657    /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 42));
658    ///
659    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
660    /// assert_eq!(non_empty.minimum_by(|(k, _), (l, _)| k.cmp(l)), &(0, 76));
661    /// ```
662    pub fn minimum_by<F>(&self, compare: F) -> &T
663    where
664        F: Fn(&T, &T) -> Ordering,
665    {
666        self.maximum_by(|a, b| compare(a, b).reverse())
667    }
668
669    /// Returns the element that gives the maximum value with respect to the specified function.
670    ///
671    /// This will return the first item in the vector if the tail is empty.
672    ///
673    /// # Examples
674    ///
675    /// ```
676    /// use nonempty::NonEmpty;
677    ///
678    /// let non_empty = NonEmpty::new((0, 42));
679    /// assert_eq!(non_empty.maximum_by_key(|(k, _)| k), &(0, 42));
680    ///
681    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
682    /// assert_eq!(non_empty.maximum_by_key(|(k, _)| k), &(4, 42));
683    /// ```
684    pub fn maximum_by_key<U, F>(&self, f: F) -> &T
685    where
686        U: Ord,
687        F: Fn(&T) -> &U,
688    {
689        self.maximum_by(|i, j| f(i).cmp(f(j)))
690    }
691
692    /// Returns the element that gives the minimum value with respect to the specified function.
693    ///
694    /// This will return the first item in the vector if the tail is empty.
695    ///
696    /// # Examples
697    ///
698    /// ```
699    /// use nonempty::NonEmpty;
700    ///
701    /// let non_empty = NonEmpty::new((0, 42));
702    /// assert_eq!(non_empty.minimum_by_key(|(k, _)| k), &(0, 42));
703    ///
704    /// let non_empty = NonEmpty::from(((2, 1), vec![(2, -34), (4, 42), (0, 76), (1, 4), (3, 5)]));
705    /// assert_eq!(non_empty.minimum_by_key(|(k, _)| k), &(0, 76));
706    /// ```
707    pub fn minimum_by_key<U, F>(&self, f: F) -> &T
708    where
709        U: Ord,
710        F: Fn(&T) -> &U,
711    {
712        self.minimum_by(|i, j| f(i).cmp(f(j)))
713    }
714}
715
716impl<T> From<NonEmpty<T>> for Vec<T> {
717    /// Turns a non-empty list into a Vec.
718    fn from(nonempty: NonEmpty<T>) -> Vec<T> {
719        iter::once(nonempty.head).chain(nonempty.tail).collect()
720    }
721}
722
723impl<T> From<NonEmpty<T>> for (T, Vec<T>) {
724    /// Turns a non-empty list into a Vec.
725    fn from(nonempty: NonEmpty<T>) -> (T, Vec<T>) {
726        (nonempty.head, nonempty.tail)
727    }
728}
729
730impl<T> From<(T, Vec<T>)> for NonEmpty<T> {
731    /// Turns a pair of an element and a Vec into
732    /// a NonEmpty.
733    fn from((head, tail): (T, Vec<T>)) -> Self {
734        NonEmpty { head, tail }
735    }
736}
737
738impl<T> IntoIterator for NonEmpty<T> {
739    type Item = T;
740    type IntoIter = iter::Chain<iter::Once<T>, vec::IntoIter<Self::Item>>;
741
742    fn into_iter(self) -> Self::IntoIter {
743        iter::once(self.head).chain(self.tail)
744    }
745}
746
747impl<'a, T> IntoIterator for &'a NonEmpty<T> {
748    type Item = &'a T;
749    type IntoIter = iter::Chain<iter::Once<&'a T>, std::slice::Iter<'a, T>>;
750
751    fn into_iter(self) -> Self::IntoIter {
752        iter::once(&self.head).chain(self.tail.iter())
753    }
754}
755
756impl<T> std::ops::Index<usize> for NonEmpty<T> {
757    type Output = T;
758
759    /// ```
760    /// use nonempty::NonEmpty;
761    ///
762    /// let non_empty = NonEmpty::from((1, vec![2, 3, 4, 5]));
763    ///
764    /// assert_eq!(non_empty[0], 1);
765    /// assert_eq!(non_empty[1], 2);
766    /// assert_eq!(non_empty[3], 4);
767    /// ```
768    fn index(&self, index: usize) -> &T {
769        if index > 0 {
770            &self.tail[index - 1]
771        } else {
772            &self.head
773        }
774    }
775}
776
777impl<T> std::ops::IndexMut<usize> for NonEmpty<T> {
778    fn index_mut(&mut self, index: usize) -> &mut T {
779        if index > 0 {
780            &mut self.tail[index - 1]
781        } else {
782            &mut self.head
783        }
784    }
785}
786
787#[cfg(feature = "serialize")]
788pub mod serialize {
789    use std::{convert::TryFrom, fmt};
790
791    use super::NonEmpty;
792
793    #[derive(Debug)]
794    pub enum Error {
795        Empty,
796    }
797
798    impl fmt::Display for Error {
799        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800            match self {
801                Self::Empty => f.write_str(
802                    "the vector provided was empty, NonEmpty needs at least one element",
803                ),
804            }
805        }
806    }
807
808    impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
809        type Error = Error;
810
811        fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
812            NonEmpty::from_vec(vec).ok_or(Error::Empty)
813        }
814    }
815}
816
817#[cfg(test)]
818mod tests {
819    use crate::NonEmpty;
820
821    #[test]
822    fn test_from_conversion() {
823        let result = NonEmpty::from((1, vec![2, 3, 4, 5]));
824        let expected = NonEmpty {
825            head: 1,
826            tail: vec![2, 3, 4, 5],
827        };
828        assert_eq!(result, expected);
829    }
830
831    #[test]
832    fn test_into_iter() {
833        let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
834        for (i, n) in nonempty.into_iter().enumerate() {
835            assert_eq!(i as i32, n);
836        }
837    }
838
839    #[test]
840    fn test_iter_syntax() {
841        let nonempty = NonEmpty::from((0, vec![1, 2, 3]));
842        for n in &nonempty {
843            assert_eq!(*n, *n); // Prove that we're dealing with references.
844        }
845        for _ in nonempty {}
846    }
847
848    #[test]
849    fn test_mutate_head() {
850        let mut non_empty = NonEmpty::new(42);
851        non_empty.head += 1;
852        assert_eq!(non_empty.head, 43);
853
854        let mut non_empty = NonEmpty::from((1, vec![4, 2, 3]));
855        non_empty.head *= 42;
856        assert_eq!(non_empty.head, 42);
857    }
858
859    #[cfg(feature = "serialize")]
860    mod serialize {
861        use crate::NonEmpty;
862        use serde::{Deserialize, Serialize};
863
864        #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
865        pub struct SimpleSerializable(pub i32);
866
867        #[test]
868        fn test_simple_round_trip() -> Result<(), Box<dyn std::error::Error>> {
869            // Given
870            let mut non_empty = NonEmpty::new(SimpleSerializable(42));
871            non_empty.push(SimpleSerializable(777));
872            let expected_value = non_empty.clone();
873
874            // When
875            let res = serde_json::from_str::<'_, NonEmpty<SimpleSerializable>>(
876                &serde_json::to_string(&non_empty)?,
877            )?;
878
879            // Then
880            assert_eq!(res, expected_value);
881
882            Ok(())
883        }
884    }
885}