Skip to content

Commit 3cc9052

Browse files
committed
Add Iterator::join to combine Iterator and Join
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
1 parent 1a22a0f commit 3cc9052

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

library/alloc/src/iter.rs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 {}

library/alloc/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ mod boxed {
167167
pub mod borrow;
168168
pub mod collections;
169169
pub mod fmt;
170+
pub mod iter;
170171
pub mod prelude;
171172
pub mod raw_vec;
172173
pub mod rc;

0 commit comments

Comments
 (0)