tamer: xir::fmt (DisplayFn): New fn wrapper

See the docblock for a description.  This is used in an upcoming commit for
=ele_parse!=.

DEV-7145
main
Mike Gerwitz 2022-08-17 10:01:47 -04:00
parent 4177b8ed71
commit 6b29479fd6
1 changed files with 24 additions and 0 deletions

View File

@ -389,6 +389,22 @@ impl<'a, W: ListDisplayWrapper + ?Sized, T: Display> Display
}
}
/// Wrap a `fmt`-like function to be used as [`Display::fmt`] for this
/// object.
///
/// This works around the problem of having a function expecting a
/// [`Formatter`],
/// but not having a [`Formatter`] to call it with.
/// It also allows for arbitrary (compatible) functions to be used as
/// [`Display`].
pub struct DisplayFn<F: Fn(&mut Formatter) -> Result>(pub F);
impl<F: Fn(&mut Formatter) -> Result> Display for DisplayFn<F> {
fn fmt(&self, f: &mut Formatter) -> Result {
(self.0)(f)
}
}
#[cfg(test)]
mod test {
use super::*;
@ -523,4 +539,12 @@ mod test {
"things (a), (b), or (c)",
);
}
#[test]
fn display_fn() {
assert_eq!(
DisplayFn(|f| write!(f, "test fmt")).to_string(),
"test fmt",
);
}
}