kaspa-utils 0.15.0

Kaspa utilities
Documentation
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)
    }
}