use std::fmt::{Display, Formatter, Result};
use serde::Serialize;
pub struct OptDisplay<'a, T> {
inner: Option<T>,
empty_display: &'a str,
}
impl<T> Serialize for OptDisplay<'_, T>
where
T: Serialize,
{
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.inner.serialize(serializer)
}
}
impl<'a, T: Display> OptDisplay<'a, T> {
#[inline]
pub fn new(maybe_display: Option<T>, empty_display: &'a str) -> Self {
Self {
inner: maybe_display,
empty_display,
}
}
}
impl<T: Display> Display for OptDisplay<'_, T> {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self.inner {
None => f.write_str(self.empty_display),
Some(ref val) => val.fmt(f),
}
}
}
#[cfg(test)]
mod tests {
use super::OptDisplay;
#[test]
fn opt_display_works() {
let some_value: Option<u32> = Some(12345);
assert_eq!(
OptDisplay::new(some_value.as_ref(), "does not matter").to_string(),
"12345"
);
let none_value: Option<u32> = None;
assert_eq!(
OptDisplay::new(none_value.as_ref(), "should be none").to_string(),
"should be none"
);
}
}