use std::fmt::{Display, Error, Formatter};
pub struct LazyString<F>(F)
where
F: Fn(&mut Formatter<'_>) -> Result<(), Error>;
impl<F> LazyString<F>
where
F: Fn(&mut Formatter<'_>) -> Result<(), Error>,
{
pub fn new(f: F) -> Self {
Self(f)
}
}
impl<F> Display for LazyString<F>
where
F: Fn(&mut Formatter<'_>) -> Result<(), Error>,
{
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
(self.0)(f)
}
}
#[macro_export]
macro_rules! lazy_format {
($($arg:tt)*) => {
$crate::LazyString::new(|f: &mut std::fmt::Formatter<'_>| {
write!(f, $($arg)*)
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_lazy_string() {
let x: f32 = 10.5;
let y: usize = 20;
let lazy = LazyString::new(|f: &mut std::fmt::Formatter| {
write!(f, "Lazy Message: x = {x}, y = {y}")
});
assert_eq!(lazy.to_string(), "Lazy Message: x = 10.5, y = 20");
let lazy = lazy_format!("Lazy Message: x = {x}, y = {y}");
assert_eq!(lazy.to_string(), "Lazy Message: x = 10.5, y = 20");
}
}