diff --git a/src/util.rs b/src/util.rs index 0d2c8de..70160e7 100644 --- a/src/util.rs +++ b/src/util.rs @@ -7,7 +7,7 @@ mod duration; pub use duration::FemtoDuration; // Imports -use std::io; +use std::{cell::RefCell, fmt, io}; /// Extension trait for `R: io::Read` types to read a byte array #[extend::ext(name = ReadByteArray)] @@ -21,3 +21,22 @@ pub impl R { Ok(array) } } + +/// [`fmt::Display`] helper to display using a `FnMut(&mut fmt::Formatter)` +pub struct DisplayWrapper fmt::Result>(RefCell); + +impl fmt::Result> DisplayWrapper { + /// Creates a new display wrapper + #[must_use] + pub const fn new(func: F) -> Self { + Self(RefCell::new(func)) + } +} + + +impl fmt::Result> fmt::Display for DisplayWrapper { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Note: `f` cannot be re-entrant, so this cannot fail + self.0.borrow_mut()(f) + } +}