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