|
| 1 | +//! Allocation extensions for [`Iterator`]. |
| 2 | +//! |
| 3 | +//! *[See also the Iterator trait][Iterator].* |
| 4 | +#![unstable(feature = "iterator_join", issue = "75638")] |
| 5 | + |
| 6 | +use crate::slice::Join; |
| 7 | +use crate::vec::Vec; |
| 8 | + |
| 9 | +/// Iterator extension traits that requires allocation. |
| 10 | +#[unstable(feature = "iterator_join", issue = "75638")] |
| 11 | +pub trait IteratorExt: Iterator { |
| 12 | + /// Flattens an iterator into a single value with the given separator in |
| 13 | + /// between. |
| 14 | + /// |
| 15 | + /// Combines `collect` with `join` to convert a sequence into a value |
| 16 | + /// separated with the specified separator. |
| 17 | + /// |
| 18 | + /// Allows `.join(sep)` instead of `.collect::<Vec<_>>().join(sep)`. |
| 19 | + /// |
| 20 | + /// ``` |
| 21 | + /// #![feature(iterator_join)] |
| 22 | + /// use alloc::iter::IteratorExt; |
| 23 | + /// |
| 24 | + /// assert_eq!(["hello", "world"].iter().copied().join(" "), "hello world"); |
| 25 | + /// assert_eq!([[1, 2], [3, 4]].iter().copied().join(&0), [1, 2, 0, 3, 4]); |
| 26 | + /// assert_eq!([[1, 2], [3, 4]].iter().copied().join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); |
| 27 | + /// ``` |
| 28 | + #[inline] |
| 29 | + #[unstable(feature = "iterator_join", issue = "75638")] |
| 30 | + #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] |
| 31 | + fn join<Separator>(self, sep: Separator) -> <[Self::Item] as Join<Separator>>::Output |
| 32 | + where |
| 33 | + [Self::Item]: Join<Separator>, |
| 34 | + Self: Sized, |
| 35 | + { |
| 36 | + Join::join(self.collect::<Vec<Self::Item>>().as_slice(), sep) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<T: Iterator + ?Sized> IteratorExt for T {} |
0 commit comments