Skip to content

Commit

Permalink
Add Iterator::join to combine Iterator and Join
Browse files Browse the repository at this point in the history
Iterator::join will be added as extention trait IteratorExt inside
alloc crate as it requries allocation while joining which is the
reason why Join avaliable in alloc but not core. It is an easier
alternative to `.collect::<Vec<_>>().join(sep)`.

Tracking issue: rust-lang#75638
  • Loading branch information
pickfire committed Aug 22, 2020
1 parent 1a22a0f commit 3cc9052
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions library/alloc/src/iter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! Allocation extensions for [`Iterator`].
//!
//! *[See also the Iterator trait][Iterator].*
#![unstable(feature = "iterator_join", issue = "75638")]

use crate::slice::Join;
use crate::vec::Vec;

/// Iterator extension traits that requires allocation.
#[unstable(feature = "iterator_join", issue = "75638")]
pub trait IteratorExt: Iterator {
/// Flattens an iterator into a single value with the given separator in
/// between.
///
/// Combines `collect` with `join` to convert a sequence into a value
/// separated with the specified separator.
///
/// Allows `.join(sep)` instead of `.collect::<Vec<_>>().join(sep)`.
///
/// ```
/// #![feature(iterator_join)]
/// use alloc::iter::IteratorExt;
///
/// assert_eq!(["hello", "world"].iter().copied().join(" "), "hello world");
/// assert_eq!([[1, 2], [3, 4]].iter().copied().join(&0), [1, 2, 0, 3, 4]);
/// assert_eq!([[1, 2], [3, 4]].iter().copied().join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
/// ```
#[inline]
#[unstable(feature = "iterator_join", issue = "75638")]
#[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
fn join<Separator>(self, sep: Separator) -> <[Self::Item] as Join<Separator>>::Output
where
[Self::Item]: Join<Separator>,
Self: Sized,
{
Join::join(self.collect::<Vec<Self::Item>>().as_slice(), sep)
}
}

impl<T: Iterator + ?Sized> IteratorExt for T {}
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ mod boxed {
pub mod borrow;
pub mod collections;
pub mod fmt;
pub mod iter;
pub mod prelude;
pub mod raw_vec;
pub mod rc;
Expand Down

0 comments on commit 3cc9052

Please sign in to comment.