stdx/
iter.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#[cfg(feature = "alloc")]
use core::fmt;

#[cfg(feature = "alloc")]
use alloc::string::String;

pub trait IteratorExt: Iterator {
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    #[cfg(feature = "alloc")]
    fn join_(&mut self, sep: &str) -> String
    where
        Self::Item: fmt::Display,
    {
        use core::fmt::Write as _;

        match self.next() {
            None => String::new(),
            Some(first) => {
                let (lower, _) = self.size_hint();
                let mut buf = String::with_capacity(sep.len() * lower);
                write!(&mut buf, "{first}").unwrap();
                self.for_each(|item| {
                    buf.push_str(sep);
                    write!(&mut buf, "{item}").unwrap();
                });
                buf
            }
        }
    }
}

impl<I: Iterator> IteratorExt for I {}