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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use itertools::Itertools;

/// Format all iterator elements, separated by `sep`.
///
/// Unlike the underlying `itertools::format`, **does not panic** if `fmt` is called more than once.
/// Should be used for logging purposes since `itertools::format` will panic when used by multiple loggers.
pub trait IterExtensions: Iterator {
    fn reusable_format(self, sep: &str) -> ReusableIterFormat<Self>
    where
        Self: Sized,
    {
        ReusableIterFormat::new(self.format(sep))
    }
}

impl<T: ?Sized> IterExtensions for T where T: Iterator {}

pub struct ReusableIterFormat<'a, I> {
    inner: itertools::Format<'a, I>,
}

impl<'a, I> ReusableIterFormat<'a, I> {
    pub fn new(inner: itertools::Format<'a, I>) -> Self {
        Self { inner }
    }
}

impl<'a, I> std::fmt::Display for ReusableIterFormat<'a, I>
where
    I: std::clone::Clone,
    I: Iterator,
    I::Item: std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Clone the inner format to workaround the `Format: was already formatted once` internal error
        self.inner.clone().fmt(f)
    }
}

impl<'a, I> std::fmt::Debug for ReusableIterFormat<'a, I>
where
    I: std::clone::Clone,
    I: Iterator,
    I::Item: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Clone the inner format to workaround the `Format: was already formatted once` internal error
        self.inner.clone().fmt(f)
    }
}