nonempty_collections/iter.rs
1//! Non-empty iterators.
2
3use crate::nev;
4use crate::NEVec;
5use crate::Singleton;
6use std::borrow::Cow;
7use std::cell::RefCell;
8use std::cmp::Ordering;
9use std::collections::BTreeMap;
10use std::collections::BTreeSet;
11use std::collections::HashMap;
12use std::collections::HashSet;
13use std::hash::BuildHasher;
14use std::hash::Hash;
15use std::iter::Product;
16use std::iter::Sum;
17use std::num::NonZeroUsize;
18use std::path::Path;
19use std::path::PathBuf;
20use std::rc::Rc;
21use std::result::Result;
22
23// Iterator structs which _always_ have something if the source iterator is
24// non-empty:
25//
26// - [x] Chain (if one, the other, or both are nonempty)
27// - [x] Cloned
28// - [x] Copied
29// - [ ] Cycle
30// - [x] Enumerate
31// - [x] Map
32// - [x] Once
33// - [ ] Scan
34// - [x] Take
35// - [x] Zip (if both are nonempty)
36
37/// Creates an iterator that yields an element exactly once.
38///
39/// See also [`std::iter::once`].
40pub fn once<T>(value: T) -> Once<T> {
41 Once::new(value)
42}
43
44/// An [`Iterator`] that is guaranteed to have at least one item.
45///
46/// By implementing `NonEmptyIterator` for a type the implementor is responsible
47/// for ensuring that non-emptiness holds. Violating this invariant may lead to
48/// panics and/or undefined behavior.
49pub trait NonEmptyIterator: IntoIterator {
50 /// Advances this non-empty iterator, consuming its ownership. Yields the
51 /// first item and a possibly empty iterator containing the rest of the
52 /// elements.
53 #[must_use]
54 fn next(self) -> (Self::Item, Self::IntoIter)
55 where
56 Self: Sized,
57 {
58 let mut iter = self.into_iter();
59 (iter.next().unwrap(), iter)
60 }
61
62 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
63 /// to look at the next element of the iterator without consuming it. See
64 /// their documentation for more information.
65 ///
66 /// Note that the underlying iterator is still advanced when this method is
67 /// called. In order to retrieve the next element, [`next`] is called on the
68 /// underlying iterator, hence any side effects (i.e. anything other than
69 /// fetching the next value) of the [`next`] method will occur.
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// use nonempty_collections::*;
75 ///
76 /// let v = nev![0, 1, 2, 3];
77 /// let iter = v.into_nonempty_iter().peekable();
78 /// assert_eq!(&0, iter.peek());
79 /// ```
80 ///
81 /// [`peek`]: Peekable::peek
82 /// [`peek_mut`]: Peekable::peek_mut
83 /// [`next`]: Iterator::next
84 fn peekable(self) -> Peekable<Self::IntoIter>
85 where
86 Self: Sized,
87 {
88 let mut iter = self.into_iter();
89 Peekable {
90 first: iter.next().unwrap(),
91 rest: iter,
92 }
93 }
94
95 /// Tests if every element of the iterator matches a predicate.
96 ///
97 /// Because this function always advances the iterator at least once, the
98 /// non-empty guarantee is invalidated. Therefore, this function consumes
99 /// this `NonEmptyIterator`.
100 ///
101 /// See also [`Iterator::all`].
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use nonempty_collections::*;
107 ///
108 /// let n = nev![2, 2, 2];
109 /// assert!(n.nonempty_iter().all(|n| n % 2 == 0));
110 /// assert!(n.iter().all(|n| n % 2 == 0));
111 /// ```
112 #[must_use]
113 fn all<F>(self, f: F) -> bool
114 where
115 Self: Sized,
116 F: FnMut(Self::Item) -> bool,
117 {
118 self.into_iter().all(f)
119 }
120
121 /// Tests if any element of the iterator matches a predicate.
122 ///
123 /// Because this function always advances the iterator at least once, the
124 /// non-empty guarantee is invalidated. Therefore, this function consumes
125 /// this `NonEmptyIterator`.
126 ///
127 /// See also [`Iterator::any`].
128 ///
129 /// # Examples
130 ///
131 /// ```
132 /// use nonempty_collections::*;
133 ///
134 /// let n = nev![1, 1, 1, 2, 1, 1];
135 /// assert!(n.nonempty_iter().any(|n| n % 2 == 0));
136 /// assert!(!n.nonempty_iter().any(|n| n % 3 == 0));
137 /// ```
138 #[must_use]
139 fn any<F>(self, f: F) -> bool
140 where
141 Self: Sized,
142 F: FnMut(Self::Item) -> bool,
143 {
144 self.into_iter().any(f)
145 }
146
147 /// Takes two iterators and creates a new non-empty iterator over both in
148 /// sequence.
149 ///
150 /// Note that the second iterator need not be empty.
151 ///
152 /// See also [`Iterator::chain`].
153 ///
154 /// ```
155 /// use nonempty_collections::*;
156 ///
157 /// let v = nev![1, 2, 3];
158 /// let s = nes![4, 5, 6];
159 /// let mut r: Vec<_> = v.into_nonempty_iter().chain(s).collect();
160 /// r.sort();
161 ///
162 /// assert_eq!(vec![1, 2, 3, 4, 5, 6], r);
163 /// ```
164 fn chain<U>(self, other: U) -> Chain<Self::IntoIter, U::IntoIter>
165 where
166 Self: Sized,
167 U: IntoIterator<Item = Self::Item>,
168 {
169 Chain {
170 inner: self.into_iter().chain(other),
171 }
172 }
173
174 /// Creates a non-empty iterator which clones all of its elements.
175 ///
176 /// This is useful when you have an iterator over `&T`, but you need an
177 /// iterator over `T`.
178 ///
179 /// See also [`Iterator::cloned`].
180 ///
181 /// ```
182 /// use nonempty_collections::NEVec;
183 /// use nonempty_collections::*;
184 ///
185 /// #[derive(Debug, Clone, PartialEq, Eq)]
186 /// enum Foo {
187 /// A,
188 /// B,
189 /// C,
190 /// }
191 ///
192 /// let v0 = nev![Foo::A, Foo::B, Foo::C];
193 /// let v1: NEVec<_> = v0.nonempty_iter().collect();
194 /// let v2: NEVec<_> = v0.nonempty_iter().cloned().collect();
195 ///
196 /// assert_eq!(nev![&Foo::A, &Foo::B, &Foo::C], v1);
197 /// assert_eq!(nev![Foo::A, Foo::B, Foo::C], v2);
198 /// ```
199 fn cloned<'a, T>(self) -> Cloned<Self>
200 where
201 Self: Sized + NonEmptyIterator<Item = &'a T>,
202 T: Clone + 'a,
203 {
204 Cloned { iter: self }
205 }
206
207 /// Transforms an iterator into a collection, or some other concrete value.
208 ///
209 /// See also [`Iterator::collect`].
210 ///
211 /// ```
212 /// use nonempty_collections::*;
213 ///
214 /// let n0 = nev![1, 2, 3, 4];
215 /// let n1 = n0.into_nonempty_iter().collect();
216 /// assert_eq!(nev![1, 2, 3, 4], n1);
217 /// ```
218 #[must_use]
219 fn collect<B>(self) -> B
220 where
221 Self: Sized,
222 B: FromNonEmptyIterator<Self::Item>,
223 {
224 FromNonEmptyIterator::from_nonempty_iter(self)
225 }
226
227 /// Creates a non-empty iterator which copies all of its elements.
228 ///
229 /// See also [`Iterator::copied`].
230 ///
231 /// ```
232 /// use nonempty_collections::*;
233 ///
234 /// let n0 = nev![1, 2, 3, 4];
235 /// let n1 = n0.nonempty_iter().copied().collect();
236 /// assert_eq!(n0, n1);
237 /// ```
238 fn copied<'a, T>(self) -> Copied<Self::IntoIter>
239 where
240 Self: Sized + NonEmptyIterator<Item = &'a T>,
241 T: Copy + 'a,
242 {
243 Copied {
244 iter: self.into_iter().copied(),
245 }
246 }
247
248 /// Consumes the non-empty iterator, counting the number of iterations and
249 /// returning it.
250 ///
251 /// See also [`Iterator::count`].
252 ///
253 /// ```
254 /// use nonempty_collections::*;
255 ///
256 /// let n = nev![1];
257 /// assert_eq!(1, n.nonempty_iter().count().get());
258 ///
259 /// let n = nev![1, 2, 3, 4, 5, 6];
260 /// assert_eq!(6, n.nonempty_iter().count().get());
261 /// ````
262 #[must_use]
263 fn count(self) -> NonZeroUsize
264 where
265 Self: Sized,
266 {
267 unsafe { NonZeroUsize::new_unchecked(self.into_iter().count()) }
268 }
269
270 /// Creates a non-empty iterator which gives the current iteration count as
271 /// well as the next value.
272 ///
273 /// See also [`Iterator::enumerate`].
274 ///
275 /// ```
276 /// use nonempty_collections::*;
277 ///
278 /// let s = nes!["Doriath", "Gondolin", "Nargothrond"];
279 /// let total: usize = s.nonempty_iter().enumerate().map(|(c, _)| c).sum();
280 /// assert_eq!(3, total);
281 /// ```
282 fn enumerate(self) -> Enumerate<Self>
283 where
284 Self: Sized,
285 {
286 Enumerate { iter: self }
287 }
288
289 /// Creates an iterator which uses a closure to determine if an element
290 /// should be yielded.
291 ///
292 /// **Note:** The iterator returned by this method is **not** a
293 /// `NonEmptyIterator`, since there is never a guarantee that any element
294 /// will pass the predicate.
295 ///
296 /// See also [`Iterator::filter`].
297 ///
298 /// ```
299 /// use nonempty_collections::*;
300 ///
301 /// let n = nev![1, 2, 3, 4, 5, 6];
302 /// let v: Vec<_> = n
303 /// .nonempty_iter()
304 /// .map(|x| x * 2)
305 /// .filter(|&x| x % 3 == 0)
306 /// .collect();
307 /// assert_eq!(vec![6, 12], v);
308 /// ```
309 fn filter<P>(self, predicate: P) -> std::iter::Filter<<Self as IntoIterator>::IntoIter, P>
310 where
311 Self: Sized,
312 P: FnMut(&<Self as IntoIterator>::Item) -> bool,
313 {
314 self.into_iter().filter(predicate)
315 }
316
317 /// Creates an iterator that both filters and maps.
318 ///
319 /// **Note:** The iterator returned by this method is **not** a
320 /// `NonEmptyIterator`, since there is never a guarantee that any element
321 /// will yield `Some` from the given function.
322 ///
323 /// See also [`Iterator::filter_map`].
324 ///
325 /// ```
326 /// use nonempty_collections::*;
327 ///
328 /// let v = nev!["Frodo", "Sam", "", "Peregrin", "Meriadoc"];
329 /// let firsts: Vec<char> = v
330 /// .into_nonempty_iter()
331 /// .filter_map(|s| s.chars().next())
332 /// .collect();
333 /// assert_eq!(vec!['F', 'S', 'P', 'M'], firsts);
334 /// ```
335 fn filter_map<B, F>(self, f: F) -> std::iter::FilterMap<<Self as IntoIterator>::IntoIter, F>
336 where
337 Self: Sized,
338 F: FnMut(<Self as IntoIterator>::Item) -> Option<B>,
339 {
340 self.into_iter().filter_map(f)
341 }
342
343 /// Searches for an element of an iterator that satisfies a predicate.
344 ///
345 /// Because this function always advances the iterator at least once, the
346 /// non-empty guarantee is invalidated. Therefore, this function consumes
347 /// this `NonEmptyIterator`.
348 ///
349 /// See also [`Iterator::find`].
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// use nonempty_collections::*;
355 ///
356 /// let n = nev![1, 3, 5, 7, 9, 10];
357 /// assert_eq!(Some(&10), n.iter().find(|n| *n % 2 == 0));
358 /// assert_eq!(None, n.iter().find(|n| **n > 10));
359 /// ```
360 #[must_use]
361 fn find<P>(self, predicate: P) -> Option<Self::Item>
362 where
363 Self: Sized,
364 P: FnMut(&Self::Item) -> bool,
365 {
366 self.into_iter().find(predicate)
367 }
368
369 /// Creates an iterator that works like `map`, but flattens nested,
370 /// non-empty structure.
371 ///
372 /// See also [`Iterator::flat_map`].
373 ///
374 /// ```
375 /// use nonempty_collections::*;
376 ///
377 /// let v = nev![1, 2, 3];
378 /// let r = v.into_nonempty_iter().flat_map(|n| nev![n]).collect();
379 /// assert_eq!(nev![1, 2, 3], r);
380 /// ```
381 #[inline]
382 fn flat_map<U, F>(self, f: F) -> FlatMap<Self::IntoIter, U, F>
383 where
384 Self: Sized,
385 F: FnMut(Self::Item) -> U,
386 U: IntoNonEmptyIterator,
387 {
388 FlatMap {
389 inner: self.into_iter().flat_map(f),
390 }
391 }
392
393 // fn flatten<F, V>(self) -> FlatMap<Self, V, F>
394 // where
395 // Self: Sized,
396 // Self::Item: IntoNonEmptyIterator<IntoIter = V, Item = V::Item>,
397 // V: NonEmptyIterator,
398 // {
399 // self.flat_map(|ne| ne)
400 // }
401
402 /// Folds every element into an accumulator by applying an operation,
403 /// returning the final result.
404 ///
405 /// See also [`Iterator::fold`].
406 ///
407 /// ```
408 /// use nonempty_collections::*;
409 ///
410 /// let n = nev![1, 2, 3, 4];
411 /// let r = n.into_nonempty_iter().fold(0, |acc, x| acc + x);
412 /// assert_eq!(10, r);
413 /// ```
414 #[must_use]
415 fn fold<B, F>(self, init: B, f: F) -> B
416 where
417 Self: Sized,
418 F: FnMut(B, Self::Item) -> B,
419 {
420 self.into_iter().fold(init, f)
421 }
422
423 /// Group the non-empty input stream into concrete, non-empty subsections
424 /// via a given function. The cutoff criterion is whether the return value
425 /// of `f` changes between two consecutive elements.
426 ///
427 /// ```
428 /// use nonempty_collections::*;
429 ///
430 /// let n = nev![1, 1, 2, 3, 3];
431 /// let r: NEVec<_> = n.into_nonempty_iter().group_by(|n| *n).collect();
432 /// assert_eq!(r, nev![nev![1, 1], nev![2], nev![3, 3]]);
433 ///
434 /// let n = nev![2, 4, 6, 7, 9, 1, 2, 4, 6, 3];
435 /// let r: NEVec<_> = n.into_nonempty_iter().group_by(|n| n % 2 == 0).collect();
436 /// assert_eq!(
437 /// r,
438 /// nev![nev![2, 4, 6], nev![7, 9, 1], nev![2, 4, 6], nev![3]]
439 /// );
440 /// ```
441 fn group_by<K, F>(self, f: F) -> NEGroupBy<Self, F>
442 where
443 Self: Sized,
444 F: FnMut(&Self::Item) -> K,
445 K: PartialEq,
446 {
447 NEGroupBy { iter: self, f }
448 }
449
450 /// Inject a given value between each item of the [`NonEmptyIterator`].
451 ///
452 /// ```
453 /// use nonempty_collections::*;
454 ///
455 /// let n = nev![1, 2, 3];
456 /// let m: NEVec<_> = n.into_nonempty_iter().intersperse(0).collect();
457 /// assert_eq!(nev![1, 0, 2, 0, 3], m);
458 /// ```
459 fn intersperse(self, item: Self::Item) -> Intersperse<Self>
460 where
461 Self: Sized,
462 Self::Item: Clone,
463 {
464 Intersperse { iter: self, item }
465 }
466
467 /// Takes a closure and creates a non-empty iterator which calls that
468 /// closure on each element.
469 ///
470 /// If `self` is a `NonEmptyIterator`, then so is [`Map`].
471 ///
472 /// See also [`Iterator::map`].
473 ///
474 /// ```
475 /// use nonempty_collections::NEVec;
476 /// use nonempty_collections::*;
477 ///
478 /// let s = nes![1, 2, 3];
479 /// let mut v: NEVec<_> = s.nonempty_iter().map(|n| n * 2).collect();
480 /// v.sort();
481 /// assert_eq!(nev![2, 4, 6], v);
482 /// ```
483 #[inline]
484 fn map<U, F>(self, f: F) -> Map<Self, F>
485 where
486 Self: Sized,
487 F: FnMut(Self::Item) -> U,
488 {
489 Map {
490 iter: self.into_iter().map(f),
491 }
492 }
493
494 /// Returns the maximum element of a non-empty iterator.
495 ///
496 /// Unlike [`Iterator::max`], this always yields a value.
497 ///
498 /// ```
499 /// use nonempty_collections::*;
500 ///
501 /// let v = nev![1, 1000, 2, 3];
502 /// assert_eq!(1000, v.into_nonempty_iter().max());
503 /// ```
504 #[must_use]
505 fn max(self) -> Self::Item
506 where
507 Self: Sized,
508 Self::Item: Ord,
509 {
510 self.max_by(Ord::cmp)
511 }
512
513 /// Returns the element that gives the maximum value with respect to the
514 /// given comparison function.
515 ///
516 /// Unlike [`Iterator::max_by`], this always yields a value.
517 #[must_use]
518 fn max_by<F>(self, compare: F) -> Self::Item
519 where
520 Self: Sized,
521 F: Fn(&Self::Item, &Self::Item) -> Ordering,
522 {
523 let (first, iter) = self.next();
524
525 iter.into_iter()
526 .fold(first, |acc, item| match compare(&acc, &item) {
527 Ordering::Less => item,
528 _ => acc,
529 })
530 }
531
532 /// Returns the element that gives the maximum value from the
533 /// specified function.
534 ///
535 /// There are two differences with [`Iterator::max_by_key`]:
536 /// - this function always yields a value while [`Iterator::max_by_key`]
537 /// yields an `Option`.
538 /// - if several elements are equally maximum, the *first* element is
539 /// returned (unlike [`Iterator::max_by_key`] which returns the last
540 /// element).
541 ///
542 /// # Examples
543 ///
544 /// ```
545 /// use nonempty_collections::*;
546 /// let max = nev!["hi", "hey", "rust", "yolo"]
547 /// .into_nonempty_iter()
548 /// .max_by_key(|item| item.len());
549 /// assert_eq!("rust", max);
550 /// ```
551 #[must_use]
552 fn max_by_key<B, F>(self, mut key: F) -> Self::Item
553 where
554 Self: Sized,
555 B: Ord,
556 F: FnMut(&Self::Item) -> B,
557 {
558 self.map(|item| (key(&item), item))
559 .max_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key))
560 .1
561 }
562
563 /// Returns the minimum element of a non-empty iterator.
564 ///
565 /// Unlike [`Iterator::min`], this always yields a value.
566 ///
567 /// ```
568 /// use nonempty_collections::*;
569 ///
570 /// let v = nev![1000, 1, 2000, 3000];
571 /// assert_eq!(1, v.into_nonempty_iter().min());
572 /// ```
573 #[must_use]
574 fn min(self) -> Self::Item
575 where
576 Self: Sized,
577 Self::Item: Ord,
578 {
579 self.min_by(Ord::cmp)
580 }
581
582 /// Returns the element that gives the minimum value with respect to the
583 /// given comparison function.
584 ///
585 /// Unlike [`Iterator::min_by`], this always yields a value.
586 #[must_use]
587 fn min_by<F>(self, compare: F) -> Self::Item
588 where
589 Self: Sized,
590 F: Fn(&Self::Item, &Self::Item) -> Ordering,
591 {
592 let (first, iter) = self.next();
593
594 iter.into_iter()
595 .fold(first, |acc, item| match compare(&acc, &item) {
596 Ordering::Greater => item,
597 _ => acc,
598 })
599 }
600
601 /// Returns the element that gives the minimum value from the
602 /// specified function.
603 ///
604 /// There are two differences with [`Iterator::min_by_key`]:
605 /// - this function always yields a value while [`Iterator::min_by_key`]
606 /// yields an `Option`.
607 /// - if several elements are equally minimum, the *first* element is
608 /// returned (unlike [`Iterator::min_by_key`] which returns the last
609 /// element).
610 ///
611 /// # Examples
612 ///
613 /// ```
614 /// use nonempty_collections::*;
615 /// let min = nev!["hi", "hello", "greetings", "hy"]
616 /// .into_nonempty_iter()
617 /// .min_by_key(|item| item.len());
618 /// assert_eq!("hi", min);
619 /// ```
620 #[must_use]
621 fn min_by_key<B, F>(self, mut key: F) -> Self::Item
622 where
623 Self: Sized,
624 B: Ord,
625 F: FnMut(&Self::Item) -> B,
626 {
627 self.map(|item| (key(&item), item))
628 .min_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key))
629 .1
630 }
631
632 /// Sort all iterator elements into a new non-empty iterator in ascending
633 /// order.
634 ///
635 /// **Note:** This consumes the entire iterator, uses the
636 /// [`NEVec::sort_by_key`] method and returns the result as a new iterator
637 /// that owns its elements.
638 ///
639 /// This sort is stable (i.e., does not reorder equal elements).
640 ///
641 /// The sorted iterator, if directly collected to a `NEVec`, is converted
642 /// without any extra copying or allocation cost.
643 ///
644 /// ```
645 /// use nonempty_collections::*;
646 ///
647 /// // sort people in descending order by age
648 /// let people = nev![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 30)];
649 ///
650 /// let oldest_people_first = people
651 /// .into_nonempty_iter()
652 /// .sorted_by_key(|x| -x.1)
653 /// .map(|(person, _age)| person)
654 /// .collect::<NEVec<_>>();
655 ///
656 /// assert_eq!(nev!["Jill", "Jack", "Jane", "John"], oldest_people_first);
657 /// ```
658 fn sorted_by_key<K, F>(self, f: F) -> crate::vector::IntoIter<Self::Item>
659 where
660 Self: Sized,
661 K: Ord,
662 F: FnMut(&Self::Item) -> K,
663 {
664 let mut v = NEVec::from_nonempty_iter(self);
665 v.sort_by_key(f);
666 v.into_nonempty_iter()
667 }
668
669 /// Returns the `n`th element of the iterator.
670 ///
671 /// This function consumes this `NonEmptyIterator`. [`Self::next()`] can be
672 /// used for getting the first element and a reference to an iterator
673 /// over the remaining elements.
674 ///
675 /// See also [`Iterator::nth`].
676 ///
677 /// ```
678 /// use nonempty_collections::*;
679 ///
680 /// let n = nev![0, 1, 2, 3, 4, 5, 6];
681 /// assert_eq!(Some(&0), n.nonempty_iter().nth(0));
682 ///
683 /// let n = nev![0, 1, 2, 3, 4, 5, 6];
684 /// assert_eq!(Some(&6), n.nonempty_iter().nth(6));
685 ///
686 /// let n = nev![0, 1, 2, 3, 4, 5, 6];
687 /// assert_eq!(None, n.nonempty_iter().nth(100));
688 /// ```
689 fn nth(self, n: usize) -> Option<Self::Item>
690 where
691 Self: Sized,
692 {
693 self.into_iter().nth(n)
694 }
695
696 /// Skip the first `n` elements.
697 ///
698 /// Note that the result will not be non-empty.
699 ///
700 /// See also [`Iterator::skip`].
701 ///
702 /// ```
703 /// use nonempty_collections::*;
704 ///
705 /// let v = nev![1, 2, 3];
706 /// assert_eq!(Some(&3), v.nonempty_iter().skip(2).next());
707 /// ```
708 fn skip(self, n: usize) -> std::iter::Skip<<Self as IntoIterator>::IntoIter>
709 where
710 Self: Sized,
711 {
712 self.into_iter().skip(n)
713 }
714
715 /// Skips over all initial elements that pass a given predicate.
716 ///
717 /// **Note**: This does not yield a non-empty iterator, since there is no
718 /// guarantee that anything will fail the predicate.
719 ///
720 /// See also [`Iterator::skip_while`].
721 ///
722 /// ```
723 /// use nonempty_collections::*;
724 ///
725 /// let v = nev![2, 4, 6, 7, 8];
726 /// let r: Vec<_> = v.into_nonempty_iter().skip_while(|n| n % 2 == 0).collect();
727 /// assert_eq!(vec![7, 8], r);
728 /// ```
729 fn skip_while<P>(self, pred: P) -> std::iter::SkipWhile<<Self as IntoIterator>::IntoIter, P>
730 where
731 Self: Sized,
732 P: FnMut(&<Self as IntoIterator>::Item) -> bool,
733 {
734 self.into_iter().skip_while(pred)
735 }
736
737 /// Sums the elements of a non-empty iterator.
738 ///
739 /// See also [`Iterator::sum`].
740 ///
741 /// ```
742 /// use nonempty_collections::*;
743 ///
744 /// let sum: u32 = nev![1, 2, 3, 4].nonempty_iter().sum();
745 /// assert_eq!(10, sum);
746 /// ```
747 #[must_use]
748 fn sum<S>(self) -> S
749 where
750 Self: Sized + IntoIterator,
751 S: Sum<<Self as IntoIterator>::Item>,
752 {
753 Sum::sum(self.into_iter())
754 }
755
756 /// Iterates over the first `n` elements, or fewer if the underlying
757 /// iterator ends sooner.
758 ///
759 /// See also [`Iterator::take`].
760 ///
761 /// # Panics
762 ///
763 /// Panics if `n == 0`.
764 ///
765 /// # Examples
766 ///
767 /// ```
768 /// use core::num::NonZeroUsize;
769 ///
770 /// use nonempty_collections::*;
771 ///
772 /// let n: NEVec<_> = nev![1, 2, 3]
773 /// .nonempty_iter()
774 /// .map(|n| n * 2)
775 /// .take(NonZeroUsize::new(2).unwrap())
776 /// .collect();
777 /// assert_eq!(nev![2, 4], n);
778 /// ```
779 fn take(self, n: NonZeroUsize) -> Take<Self>
780 where
781 Self: Sized,
782 {
783 Take {
784 iter: self.into_iter().take(n.get()),
785 }
786 }
787
788 /// Iterates over all initial elements that pass a given predicate.
789 ///
790 /// **Note**: This does not yield a non-empty iterator, since there is no
791 /// guarantee that anything will pass the predicate.
792 ///
793 /// See also [`Iterator::take_while`].
794 ///
795 /// ```
796 /// use nonempty_collections::*;
797 ///
798 /// let v = nev![2, 4, 6, 7, 8];
799 /// let r: Vec<_> = v.into_nonempty_iter().take_while(|n| n % 2 == 0).collect();
800 /// assert_eq!(vec![2, 4, 6], r);
801 /// ```
802 fn take_while<P>(self, pred: P) -> std::iter::TakeWhile<<Self as IntoIterator>::IntoIter, P>
803 where
804 Self: Sized,
805 P: FnMut(&<Self as IntoIterator>::Item) -> bool,
806 {
807 self.into_iter().take_while(pred)
808 }
809
810 /// Iterates over the entire non-empty iterator, multiplying all the
811 /// elements.
812 ///
813 /// See also [`Iterator::product`].
814 ///
815 /// ```
816 /// use nonempty_collections::*;
817 ///
818 /// let prod: u32 = nev![1, 2, 3, 4].nonempty_iter().product();
819 /// assert_eq!(24, prod);
820 /// ```
821 #[must_use]
822 fn product<P>(self) -> P
823 where
824 Self: Sized + IntoIterator,
825 P: Product<<Self as IntoIterator>::Item>,
826 {
827 Product::product(self.into_iter())
828 }
829
830 /// "Zips up" two non-empty iterators into a single one, while preserving
831 /// non-emptiness.
832 ///
833 /// See also [`Iterator::zip`].
834 ///
835 /// ```
836 /// use nonempty_collections::*;
837 ///
838 /// let a = nev![1, 2, 3];
839 /// let b = nev![4, 5, 6, 7];
840 /// let r = a
841 /// .into_nonempty_iter()
842 /// .zip(b)
843 /// .map(|(av, bv)| av + bv)
844 /// .collect();
845 /// assert_eq!(nev![5, 7, 9], r);
846 /// ```
847 fn zip<U>(self, other: U) -> Zip<Self::IntoIter, U::IntoIter>
848 where
849 Self: Sized,
850 U: IntoNonEmptyIterator,
851 {
852 Zip {
853 inner: self.into_iter().zip(other),
854 }
855 }
856
857 /// Reduce a non-empty iterator of pairs into a pair of concrete containers.
858 ///
859 /// See also [`Iterator::unzip`].
860 ///
861 /// ```
862 /// use nonempty_collections::*;
863 ///
864 /// let v = nev![('a', 1), ('b', 2), ('c', 3)];
865 /// let (a, b): (NEVec<char>, NEVec<usize>) = v.into_nonempty_iter().unzip();
866 ///
867 /// assert_eq!(a, nev!['a', 'b', 'c']);
868 /// assert_eq!(b, nev![1, 2, 3]);
869 /// ```
870 ///
871 /// Fortunately, the [`Extend`] impl of [`crate::NEMap`] naturally fits
872 /// this, thus you can split keys and values cleanly:
873 ///
874 /// ```
875 /// use nonempty_collections::*;
876 ///
877 /// let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
878 /// let (a, b): (NESet<char>, NESet<usize>) = m.into_nonempty_iter().unzip();
879 ///
880 /// assert_eq!(a, nes!['a', 'b', 'c']);
881 /// assert_eq!(b, nes![1, 2, 3]);
882 /// ```
883 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
884 where
885 FromA: Singleton<Item = A> + Extend<A>,
886 FromB: Singleton<Item = B> + Extend<B>,
887 Self: Sized + NonEmptyIterator<Item = (A, B)>,
888 {
889 let ((a, b), iter) = self.next();
890 let from_a = Singleton::singleton(a);
891 let from_b = Singleton::singleton(b);
892
893 let mut fused = (from_a, from_b);
894 fused.extend(iter);
895 fused
896 }
897
898 /// Reduces the elements to a single one, by repeatedly applying a reducing
899 /// operation.
900 ///
901 /// See also [`Iterator::reduce`].
902 ///
903 /// ```
904 /// use nonempty_collections::*;
905 ///
906 /// let a = nev![1, 2, 3, 4];
907 /// let b = a.clone();
908 ///
909 /// let x = a.into_nonempty_iter().reduce(|acc, v| acc + v);
910 /// assert_eq!(x, 10);
911 ///
912 /// let y = b.into_nonempty_iter().reduce(|acc, v| acc * v);
913 /// assert_eq!(y, 24);
914 /// ```
915 #[must_use]
916 fn reduce<F>(self, f: F) -> Self::Item
917 where
918 Self: Sized,
919 F: FnMut(Self::Item, Self::Item) -> Self::Item,
920 {
921 self.into_iter().reduce(f).unwrap()
922 }
923}
924
925/// Conversion from a [`NonEmptyIterator`].
926pub trait FromNonEmptyIterator<T>: Sized {
927 /// Creates a value from a [`NonEmptyIterator`].
928 fn from_nonempty_iter<I>(iter: I) -> Self
929 where
930 I: IntoNonEmptyIterator<Item = T>;
931}
932
933impl FromNonEmptyIterator<()> for () {
934 fn from_nonempty_iter<I>(iter: I) -> Self
935 where
936 I: IntoNonEmptyIterator<Item = ()>,
937 {
938 // NOTE: 2025-11-11 Can't just be a short-circuited `()` due to the
939 // potential for side-effects to be occuring within the original
940 // iterator.
941 iter.into_nonempty_iter().into_iter().collect()
942 }
943}
944
945impl FromNonEmptyIterator<String> for String {
946 fn from_nonempty_iter<I>(iter: I) -> Self
947 where
948 I: IntoNonEmptyIterator<Item = String>,
949 {
950 iter.into_nonempty_iter().into_iter().collect()
951 }
952}
953
954impl<'a> FromNonEmptyIterator<&'a str> for String {
955 fn from_nonempty_iter<I>(iter: I) -> Self
956 where
957 I: IntoNonEmptyIterator<Item = &'a str>,
958 {
959 iter.into_nonempty_iter().into_iter().collect()
960 }
961}
962
963impl<'a> FromNonEmptyIterator<Cow<'a, str>> for String {
964 fn from_nonempty_iter<I>(iter: I) -> Self
965 where
966 I: IntoNonEmptyIterator<Item = Cow<'a, str>>,
967 {
968 iter.into_nonempty_iter().into_iter().collect()
969 }
970}
971
972impl FromNonEmptyIterator<char> for String {
973 fn from_nonempty_iter<I>(iter: I) -> Self
974 where
975 I: IntoNonEmptyIterator<Item = char>,
976 {
977 iter.into_nonempty_iter().into_iter().collect()
978 }
979}
980
981impl<'a> FromNonEmptyIterator<&'a char> for String {
982 fn from_nonempty_iter<I>(iter: I) -> Self
983 where
984 I: IntoNonEmptyIterator<Item = &'a char>,
985 {
986 iter.into_nonempty_iter().into_iter().collect()
987 }
988}
989
990impl<T> FromNonEmptyIterator<T> for Vec<T> {
991 fn from_nonempty_iter<I>(iter: I) -> Self
992 where
993 I: IntoNonEmptyIterator<Item = T>,
994 {
995 iter.into_nonempty_iter().into_iter().collect()
996 }
997}
998
999impl<K, V, S> FromNonEmptyIterator<(K, V)> for HashMap<K, V, S>
1000where
1001 K: Eq + Hash,
1002 S: BuildHasher + Default,
1003{
1004 fn from_nonempty_iter<I>(iter: I) -> Self
1005 where
1006 I: IntoNonEmptyIterator<Item = (K, V)>,
1007 {
1008 iter.into_nonempty_iter().into_iter().collect()
1009 }
1010}
1011
1012impl<T, S> FromNonEmptyIterator<T> for HashSet<T, S>
1013where
1014 T: Eq + Hash,
1015 S: BuildHasher + Default,
1016{
1017 fn from_nonempty_iter<I>(iter: I) -> Self
1018 where
1019 I: IntoNonEmptyIterator<Item = T>,
1020 {
1021 iter.into_nonempty_iter().into_iter().collect()
1022 }
1023}
1024
1025impl<K, V> FromNonEmptyIterator<(K, V)> for BTreeMap<K, V>
1026where
1027 K: Ord,
1028{
1029 fn from_nonempty_iter<I>(iter: I) -> Self
1030 where
1031 I: IntoNonEmptyIterator<Item = (K, V)>,
1032 {
1033 iter.into_nonempty_iter().into_iter().collect()
1034 }
1035}
1036
1037impl<T> FromNonEmptyIterator<T> for BTreeSet<T>
1038where
1039 T: Ord,
1040{
1041 fn from_nonempty_iter<I>(iter: I) -> Self
1042 where
1043 I: IntoNonEmptyIterator<Item = T>,
1044 {
1045 iter.into_nonempty_iter().into_iter().collect()
1046 }
1047}
1048
1049impl<P> FromNonEmptyIterator<P> for PathBuf
1050where
1051 P: AsRef<Path>,
1052{
1053 fn from_nonempty_iter<I>(iter: I) -> Self
1054 where
1055 I: IntoNonEmptyIterator<Item = P>,
1056 {
1057 iter.into_nonempty_iter().into_iter().collect()
1058 }
1059}
1060
1061impl<A, E, V> FromNonEmptyIterator<Result<A, E>> for Result<V, E>
1062where
1063 V: FromNonEmptyIterator<A>,
1064{
1065 fn from_nonempty_iter<I>(iter: I) -> Result<V, E>
1066 where
1067 I: IntoNonEmptyIterator<Item = Result<A, E>>,
1068 {
1069 let (head, rest) = iter.into_nonempty_iter().next();
1070 let head: A = head?;
1071
1072 let mut buf = NEVec::new(head);
1073
1074 for item in rest {
1075 let item: A = item?;
1076 buf.push(item);
1077 }
1078 let new_iter = buf.into_nonempty_iter();
1079 let output: V = FromNonEmptyIterator::from_nonempty_iter(new_iter);
1080 Ok(output)
1081 }
1082}
1083
1084/// Conversion into a [`NonEmptyIterator`].
1085pub trait IntoNonEmptyIterator: IntoIterator {
1086 /// Which kind of [`NonEmptyIterator`] are we turning this into?
1087 type IntoNEIter: NonEmptyIterator<Item = Self::Item>;
1088
1089 /// Creates a [`NonEmptyIterator`] from a value.
1090 fn into_nonempty_iter(self) -> Self::IntoNEIter;
1091}
1092
1093impl<I: NonEmptyIterator> IntoNonEmptyIterator for I {
1094 type IntoNEIter = I;
1095
1096 fn into_nonempty_iter(self) -> Self::IntoNEIter {
1097 self
1098 }
1099}
1100
1101/// Similar to [`std::iter::Map`], but with additional non-emptiness guarantees.
1102#[derive(Clone)]
1103#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1104pub struct Map<I: NonEmptyIterator, F> {
1105 iter: std::iter::Map<I::IntoIter, F>,
1106}
1107
1108impl<U, I, F> NonEmptyIterator for Map<I, F>
1109where
1110 I: NonEmptyIterator,
1111 F: FnMut(I::Item) -> U,
1112{
1113}
1114
1115/// ```
1116/// use nonempty_collections::*;
1117///
1118/// let v: Vec<_> = nev![1, 2, 3].nonempty_iter().map(|n| n * 2).collect();
1119/// ```
1120impl<U, I, F> IntoIterator for Map<I, F>
1121where
1122 I: NonEmptyIterator,
1123 F: FnMut(I::Item) -> U,
1124{
1125 type Item = U;
1126
1127 type IntoIter = std::iter::Map<I::IntoIter, F>;
1128
1129 fn into_iter(self) -> Self::IntoIter {
1130 self.iter
1131 }
1132}
1133
1134impl<I, F> std::fmt::Debug for Map<I, F>
1135where
1136 I: NonEmptyIterator,
1137 I::IntoIter: std::fmt::Debug,
1138{
1139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1140 self.iter.fmt(f)
1141 }
1142}
1143
1144/// An iterator that clones the elements of an underlying iterator.
1145///
1146/// See also [`std::iter::Cloned`].
1147#[derive(Clone)]
1148#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1149pub struct Cloned<I> {
1150 iter: I,
1151}
1152
1153impl<'a, I, T: 'a> NonEmptyIterator for Cloned<I>
1154where
1155 I: NonEmptyIterator<Item = &'a T>,
1156 T: Clone,
1157{
1158}
1159
1160impl<'a, I, T: 'a> IntoIterator for Cloned<I>
1161where
1162 I: IntoIterator<Item = &'a T>,
1163 T: Clone,
1164{
1165 type Item = T;
1166
1167 type IntoIter = std::iter::Cloned<I::IntoIter>;
1168
1169 fn into_iter(self) -> Self::IntoIter {
1170 self.iter.into_iter().cloned()
1171 }
1172}
1173
1174impl<I: std::fmt::Debug> std::fmt::Debug for Cloned<I> {
1175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1176 self.iter.fmt(f)
1177 }
1178}
1179
1180/// An iterator that yields the current count and the element during iteration.
1181///
1182/// See also [`std::iter::Enumerate`].
1183#[derive(Clone)]
1184#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1185pub struct Enumerate<I> {
1186 iter: I,
1187}
1188
1189impl<I> NonEmptyIterator for Enumerate<I> where I: NonEmptyIterator {}
1190
1191impl<I> IntoIterator for Enumerate<I>
1192where
1193 I: IntoIterator,
1194{
1195 type Item = (usize, I::Item);
1196
1197 type IntoIter = std::iter::Enumerate<I::IntoIter>;
1198
1199 fn into_iter(self) -> Self::IntoIter {
1200 self.iter.into_iter().enumerate()
1201 }
1202}
1203
1204impl<I: std::fmt::Debug> std::fmt::Debug for Enumerate<I> {
1205 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1206 self.iter.fmt(f)
1207 }
1208}
1209
1210/// A non-empty iterator that only iterates over the first `n` iterations.
1211///
1212/// See also [`Iterator::take`].
1213#[derive(Clone)]
1214#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1215pub struct Take<I: NonEmptyIterator> {
1216 iter: std::iter::Take<I::IntoIter>,
1217}
1218
1219impl<I> NonEmptyIterator for Take<I> where I: NonEmptyIterator {}
1220
1221/// ```
1222/// use core::num::NonZeroUsize;
1223///
1224/// use nonempty_collections::*;
1225///
1226/// let v = nev![1, 2, 3];
1227/// let r = v
1228/// .nonempty_iter()
1229/// .take(NonZeroUsize::new(1).unwrap())
1230/// .into_iter()
1231/// .count();
1232/// assert_eq!(1, r);
1233/// ```
1234impl<I> IntoIterator for Take<I>
1235where
1236 I: NonEmptyIterator,
1237{
1238 type Item = I::Item;
1239
1240 type IntoIter = std::iter::Take<I::IntoIter>;
1241
1242 fn into_iter(self) -> Self::IntoIter {
1243 self.iter
1244 }
1245}
1246
1247impl<I> std::fmt::Debug for Take<I>
1248where
1249 I: NonEmptyIterator,
1250 I::IntoIter: std::fmt::Debug,
1251{
1252 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1253 self.iter.fmt(f)
1254 }
1255}
1256
1257/// A non-empty iterator that links two iterators together, in a chain.
1258#[derive(Clone)]
1259#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1260pub struct Chain<A, B> {
1261 inner: std::iter::Chain<A, B>,
1262}
1263
1264impl<A, B> NonEmptyIterator for Chain<A, B>
1265where
1266 A: Iterator,
1267 B: Iterator<Item = A::Item>,
1268{
1269}
1270
1271impl<A, B> IntoIterator for Chain<A, B>
1272where
1273 A: Iterator,
1274 B: Iterator<Item = A::Item>,
1275{
1276 type Item = A::Item;
1277
1278 type IntoIter = std::iter::Chain<A, B>;
1279
1280 fn into_iter(self) -> Self::IntoIter {
1281 self.inner
1282 }
1283}
1284
1285impl<A, B> std::fmt::Debug for Chain<A, B>
1286where
1287 A: std::fmt::Debug,
1288 B: std::fmt::Debug,
1289{
1290 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1291 self.inner.fmt(f)
1292 }
1293}
1294
1295/// A non-empty iterator that yields an element exactly once.
1296#[derive(Clone)]
1297#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1298pub struct Once<T> {
1299 inner: std::iter::Once<T>,
1300}
1301
1302impl<T> Once<T> {
1303 pub(crate) fn new(value: T) -> Once<T> {
1304 Once {
1305 inner: std::iter::once(value),
1306 }
1307 }
1308}
1309
1310impl<T> NonEmptyIterator for Once<T> {}
1311
1312impl<T> IntoIterator for Once<T> {
1313 type Item = T;
1314
1315 type IntoIter = std::iter::Once<T>;
1316
1317 fn into_iter(self) -> Self::IntoIter {
1318 self.inner
1319 }
1320}
1321
1322impl<T: std::fmt::Debug> std::fmt::Debug for Once<T> {
1323 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1324 self.inner.fmt(f)
1325 }
1326}
1327
1328/// A non-empty iterator that copies the elements of an underlying non-empty
1329/// iterator.
1330///
1331/// See also [`std::iter::Copied`].
1332#[derive(Clone)]
1333#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1334pub struct Copied<I> {
1335 iter: std::iter::Copied<I>,
1336}
1337
1338impl<'a, I, T: 'a> NonEmptyIterator for Copied<I>
1339where
1340 I: Iterator<Item = &'a T>,
1341 T: Copy,
1342{
1343}
1344
1345impl<'a, I, T: 'a> IntoIterator for Copied<I>
1346where
1347 I: Iterator<Item = &'a T>,
1348 T: Copy,
1349{
1350 type Item = T;
1351
1352 type IntoIter = std::iter::Copied<I>;
1353
1354 fn into_iter(self) -> Self::IntoIter {
1355 self.iter
1356 }
1357}
1358
1359impl<'a, I, T: 'a> std::fmt::Debug for Copied<I>
1360where
1361 I: Iterator<Item = &'a T> + std::fmt::Debug,
1362{
1363 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1364 self.iter.fmt(f)
1365 }
1366}
1367
1368/// A non-empty iterator that "zips up" its sources.
1369///
1370/// See also [`std::iter::Zip`].
1371#[derive(Clone)]
1372#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1373pub struct Zip<A, B> {
1374 inner: std::iter::Zip<A, B>,
1375}
1376
1377impl<A, B> NonEmptyIterator for Zip<A, B>
1378where
1379 A: Iterator,
1380 B: Iterator,
1381{
1382}
1383
1384impl<A, B> IntoIterator for Zip<A, B>
1385where
1386 A: Iterator,
1387 B: Iterator,
1388{
1389 type Item = (A::Item, B::Item);
1390
1391 type IntoIter = std::iter::Zip<A, B>;
1392
1393 fn into_iter(self) -> Self::IntoIter {
1394 self.inner
1395 }
1396}
1397
1398impl<A, B> std::fmt::Debug for Zip<A, B>
1399where
1400 A: std::fmt::Debug,
1401 B: std::fmt::Debug,
1402{
1403 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1404 self.inner.fmt(f)
1405 }
1406}
1407
1408/// Wrapper struct for powering [`NonEmptyIterator::group_by`].
1409#[derive(Debug)]
1410pub struct NEGroupBy<I, F> {
1411 iter: I,
1412 f: F,
1413}
1414
1415impl<I, K, F> NonEmptyIterator for NEGroupBy<I, F>
1416where
1417 I: NonEmptyIterator,
1418 F: FnMut(&I::Item) -> K,
1419 K: PartialEq,
1420{
1421}
1422
1423impl<I, K, F> IntoIterator for NEGroupBy<I, F>
1424where
1425 I: IntoIterator,
1426 F: FnMut(&I::Item) -> K,
1427 K: PartialEq,
1428{
1429 type Item = NEVec<I::Item>;
1430
1431 type IntoIter = GroupBy<<I as IntoIterator>::IntoIter, K, I::Item, F>;
1432
1433 fn into_iter(self) -> Self::IntoIter {
1434 GroupBy {
1435 iter: self.iter.into_iter(),
1436 f: Rc::new(RefCell::new(self.f)),
1437 prev: None,
1438 curr: None,
1439 }
1440 }
1441}
1442
1443/// A (possibly empty) definition of the group-by operation that enables
1444/// [`NEGroupBy`] to be written. You aren't expected to use this directly, thus
1445/// there is no way to construct one.
1446#[derive(Debug)]
1447pub struct GroupBy<I, K, V, F> {
1448 iter: I,
1449 f: Rc<RefCell<F>>,
1450 prev: Option<K>,
1451 curr: Option<NEVec<V>>,
1452}
1453
1454impl<I, K, V, F> Iterator for GroupBy<I, K, V, F>
1455where
1456 I: Iterator<Item = V>,
1457 F: FnMut(&I::Item) -> K,
1458 K: PartialEq,
1459{
1460 type Item = NEVec<I::Item>;
1461
1462 fn next(&mut self) -> Option<Self::Item> {
1463 loop {
1464 match self.iter.next() {
1465 None => return self.curr.take(),
1466 Some(v) => {
1467 let k = {
1468 let mut f = self.f.borrow_mut();
1469 f(&v)
1470 };
1471
1472 match (self.prev.as_ref(), &mut self.curr) {
1473 // Continue some run of similar values.
1474 (Some(p), Some(c)) if p == &k => {
1475 c.push(v);
1476 }
1477 // We found a break; finally yield an NEVec.
1478 (Some(_), Some(_)) => {
1479 let curr = self.curr.take();
1480 self.curr = Some(nev![v]);
1481 self.prev = Some(k);
1482 return curr;
1483 }
1484 // Very first iteration.
1485 (_, _) => {
1486 self.prev = Some(k);
1487 self.curr = Some(nev![v]);
1488 }
1489 }
1490 }
1491 }
1492 }
1493 }
1494}
1495
1496/// Flatten nested, non-empty structures.
1497///
1498/// See also [`std::iter::FlatMap`].
1499#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1500pub struct FlatMap<I, U: IntoIterator, F> {
1501 inner: std::iter::FlatMap<I, U, F>,
1502}
1503
1504impl<I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U> NonEmptyIterator for FlatMap<I, U, F> {}
1505
1506/// ```
1507/// use nonempty_collections::*;
1508///
1509/// let v = nev![1, 2, 3];
1510/// let r: Vec<_> = v
1511/// .into_nonempty_iter()
1512/// .flat_map(|n| nev![n])
1513/// .into_iter()
1514/// .collect();
1515/// assert_eq!(vec![1, 2, 3], r);
1516/// ```
1517impl<I: Iterator, U: IntoIterator, F: FnMut(I::Item) -> U> IntoIterator for FlatMap<I, U, F> {
1518 type Item = U::Item;
1519
1520 type IntoIter = std::iter::FlatMap<I, U, F>;
1521
1522 fn into_iter(self) -> Self::IntoIter {
1523 self.inner
1524 }
1525}
1526
1527impl<I: std::fmt::Debug, U, F> std::fmt::Debug for FlatMap<I, U, F>
1528where
1529 U: IntoIterator,
1530 U::IntoIter: std::fmt::Debug,
1531{
1532 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1533 self.inner.fmt(f)
1534 }
1535}
1536
1537impl<I: Clone, U, F: Clone> Clone for FlatMap<I, U, F>
1538where
1539 U: Clone + IntoIterator,
1540 U::IntoIter: Clone,
1541{
1542 fn clone(&self) -> Self {
1543 FlatMap {
1544 inner: self.inner.clone(),
1545 }
1546 }
1547}
1548
1549/// An adapter for regular iterators that are known to be non-empty.
1550#[derive(Clone)]
1551#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1552pub struct NonEmptyIterAdapter<I> {
1553 inner: I,
1554}
1555
1556impl<I: Iterator> NonEmptyIterator for NonEmptyIterAdapter<I> {}
1557
1558impl<I> IntoIterator for NonEmptyIterAdapter<I>
1559where
1560 I: Iterator,
1561{
1562 type Item = I::Item;
1563
1564 type IntoIter = I;
1565
1566 fn into_iter(self) -> Self::IntoIter {
1567 self.inner
1568 }
1569}
1570
1571impl<I: std::fmt::Debug> std::fmt::Debug for NonEmptyIterAdapter<I> {
1572 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1573 self.inner.fmt(f)
1574 }
1575}
1576
1577/// Convenience trait extending [`IntoIterator`].
1578pub trait IntoIteratorExt {
1579 /// The type of the elements being iterated over.
1580 type Item;
1581 /// Which kind of [`NonEmptyIterator`] are we turning this into?
1582 type IntoIter: NonEmptyIterator<Item = Self::Item>;
1583
1584 /// Tries to convert `self` into a [`NonEmptyIterator`].
1585 ///
1586 /// ```
1587 /// use nonempty_collections::*;
1588 ///
1589 /// let a = vec![1];
1590 /// let x = a.try_into_nonempty_iter();
1591 /// assert!(x.is_some());
1592 ///
1593 /// let y = x.unwrap().collect::<NEVec<_>>();
1594 /// assert_eq!(y.len().get(), 1);
1595 /// ```
1596 ///
1597 /// ```
1598 /// use nonempty_collections::*;
1599 ///
1600 /// let b: Vec<u8> = vec![];
1601 /// let x = b.try_into_nonempty_iter();
1602 ///
1603 /// assert!(x.is_none());
1604 /// ```
1605 ///
1606 /// To construct non-empty collections directly, consider macros like
1607 /// [`crate::nev!`].
1608 fn try_into_nonempty_iter(self) -> Option<Self::IntoIter>;
1609}
1610
1611impl<T> IntoIteratorExt for T
1612where
1613 T: IntoIterator,
1614{
1615 type Item = T::Item;
1616
1617 type IntoIter = NonEmptyIterAdapter<std::iter::Peekable<T::IntoIter>>;
1618
1619 /// Converts `self` into a non-empty iterator or returns `None` if
1620 /// the iterator is empty.
1621 fn try_into_nonempty_iter(self) -> Option<Self::IntoIter> {
1622 let mut iter = self.into_iter().peekable();
1623 iter.peek()
1624 .is_some()
1625 .then_some(NonEmptyIterAdapter { inner: iter })
1626 }
1627}
1628
1629/// A non-empty iterator with a `peek()` that returns a reference to the first
1630/// element.
1631///
1632/// This `struct` is created by the [`peekable`] method on [`NonEmptyIterator`].
1633/// See its documentation for more.
1634///
1635/// [`peekable`]: NonEmptyIterator::peekable
1636#[derive(Debug, Clone)]
1637#[must_use = "non-empty iterators are lazy and do nothing unless consumed"]
1638pub struct Peekable<I: Iterator> {
1639 first: I::Item,
1640 rest: I,
1641}
1642
1643impl<I: Iterator> Peekable<I> {
1644 /// Returns a reference to the first value without advancing or consuming
1645 /// the iterator.
1646 pub const fn peek(&self) -> &I::Item {
1647 &self.first
1648 }
1649
1650 /// Returns a mutable reference to the first value without advancing or
1651 /// consuming the iterator.
1652 pub fn peek_mut(&mut self) -> &mut I::Item {
1653 &mut self.first
1654 }
1655}
1656
1657impl<I: Iterator> NonEmptyIterator for Peekable<I> {}
1658
1659impl<I: Iterator> IntoIterator for Peekable<I> {
1660 type Item = I::Item;
1661
1662 type IntoIter = std::iter::Chain<std::iter::Once<I::Item>, I>;
1663
1664 fn into_iter(self) -> Self::IntoIter {
1665 std::iter::once(self.first).chain(self.rest)
1666 }
1667}
1668
1669pub struct Intersperse<I>
1670where
1671 I: NonEmptyIterator,
1672{
1673 iter: I,
1674 item: I::Item,
1675}
1676
1677impl<I> NonEmptyIterator for Intersperse<I>
1678where
1679 I: NonEmptyIterator,
1680 I::Item: Clone,
1681{
1682}
1683
1684impl<I> IntoIterator for Intersperse<I>
1685where
1686 I: NonEmptyIterator,
1687 I::Item: Clone,
1688{
1689 type Item = I::Item;
1690
1691 type IntoIter = RawIntersperse<<I as IntoIterator>::IntoIter>;
1692
1693 fn into_iter(self) -> Self::IntoIter {
1694 let mut iter = self.iter.into_iter();
1695
1696 let raw = RawIntersperse {
1697 item: self.item.clone(),
1698 next: iter.next(),
1699 iter,
1700 };
1701
1702 raw.into_iter()
1703 }
1704}
1705
1706pub struct RawIntersperse<I>
1707where
1708 I: Iterator,
1709{
1710 iter: I,
1711 item: I::Item,
1712 next: Option<I::Item>,
1713}
1714
1715impl<I> Iterator for RawIntersperse<I>
1716where
1717 I: Iterator,
1718 I::Item: Clone,
1719{
1720 type Item = I::Item;
1721
1722 fn next(&mut self) -> Option<Self::Item> {
1723 if self.next.is_none() {
1724 match self.iter.next() {
1725 Some(next) => {
1726 self.next = Some(next);
1727 Some(self.item.clone())
1728 }
1729 // Completely done the iteration.
1730 None => None,
1731 }
1732 } else {
1733 self.next.take()
1734 }
1735 }
1736}
1737
1738#[cfg(test)]
1739mod tests {
1740 use super::*;
1741 use crate::nem;
1742 use crate::NEMap;
1743
1744 #[test]
1745 fn into_hashset() {
1746 let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
1747 let _: HashSet<_> = m.values().collect();
1748 }
1749
1750 #[test]
1751 fn into_hashmap() {
1752 let m = nem!['a' => 1, 'b' => 2, 'c' => 3];
1753 let h: HashMap<_, _> = m.iter().map(|(k, v)| (*k, *v)).collect();
1754 let n = NEMap::try_from(h).unwrap();
1755 assert_eq!(m, n);
1756 }
1757
1758 #[test]
1759 fn peekable() {
1760 let v = nev![0, 1, 2, 3];
1761
1762 let iter = v.into_nonempty_iter().peekable();
1763 assert_eq!(&0, iter.peek());
1764
1765 let all = iter.collect::<NEVec<_>>();
1766 assert_eq!(nev![0, 1, 2, 3], all);
1767
1768 let mut iter = all.into_nonempty_iter().peekable();
1769
1770 *iter.peek_mut() = 7;
1771
1772 let (first, rest) = iter.next();
1773 assert_eq!(7, first);
1774 assert_eq!(vec![1, 2, 3], rest.collect::<Vec<_>>());
1775
1776 let u = nev![0, 1, 2];
1777 let p: NEVec<_> = u
1778 .into_nonempty_iter()
1779 .map(|n| n + 1)
1780 .peekable()
1781 .map(|n| n * 2)
1782 .collect();
1783 assert_eq!(nev![2, 4, 6], p);
1784 }
1785}