literator 0.1.0

Efficient conversion of iterators to human-readable strings
Documentation
//! Polyfill for unstable `fmt` functions.

use core::fmt::{Debug, Display, Formatter, Result};

/// Polyfill for the unstable
/// [`std::fmt::from_fn()`](https://doc.rust-lang.org/stable/std/fmt/fn.from_fn.html).
pub fn from_fn<F>(f: F) -> FromFn<F> {
    FromFn(f)
}

/// Helper for [`from_fn()`].
pub struct FromFn<F>(F);

impl<F> Display for FromFn<F>
where
    F: Fn(&mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        (self.0)(f)
    }
}

impl<F> Debug for FromFn<F>
where
    F: Fn(&mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        (self.0)(f)
    }
}

/// Adapter whose `Display` implementation displays `T` repeated `n` times.
///
/// This can be used to programmatically create indentation and spacing.
///
/// # Example
///
/// ```
/// # use literator::fmt::repeat;
/// assert_eq!(repeat('æ', 5).to_string(), "æææææ");
/// ```
pub fn repeat<T>(item: T, n: usize) -> Repeat<T> {
    Repeat { item, n }
}

/// Helper for [`repeat()`].
#[derive(Clone, Copy)]
pub struct Repeat<T> {
    /// The item to repeat.
    pub item: T,
    /// The number of times to display `item`.
    pub n: usize,
}

impl<T: Display> Display for Repeat<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        for _ in 0..self.n {
            self.item.fmt(f)?;
        }
        Ok(())
    }
}

/// Wrapper type whose `Display` and `Debug` implementations call `F`.
pub struct FormatWith<T, F> {
    /// The item to pass to `F`.
    pub item: T,
    /// The function to call.
    pub with: F,
}

impl<T, F> Display for FormatWith<T, F>
where
    F: Fn(&T, &mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        (self.with)(&self.item, f)
    }
}

impl<T, F> Debug for FormatWith<T, F>
where
    F: Fn(&T, &mut Formatter) -> Result,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        (self.with)(&self.item, f)
    }
}