Added util::DisplayWrapper helper.

This commit is contained in:
2023-05-17 19:15:52 +01:00
parent c809e9b197
commit cf52bf745d

View File

@@ -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: io::Read> R {
Ok(array)
}
}
/// [`fmt::Display`] helper to display using a `FnMut(&mut fmt::Formatter)`
pub struct DisplayWrapper<F: FnMut(&mut fmt::Formatter) -> fmt::Result>(RefCell<F>);
impl<F: FnMut(&mut fmt::Formatter) -> fmt::Result> DisplayWrapper<F> {
/// Creates a new display wrapper
#[must_use]
pub const fn new(func: F) -> Self {
Self(RefCell::new(func))
}
}
impl<F: FnMut(&mut fmt::Formatter) -> fmt::Result> fmt::Display for DisplayWrapper<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Note: `f` cannot be re-entrant, so this cannot fail
self.0.borrow_mut()(f)
}
}