Skip to content
50 changes: 50 additions & 0 deletions valuable/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,27 @@ macro_rules! value {
$variant($ty),
)*

/// An arbitrary value that implements Display.
///
/// # Examples
///
/// ```
/// use std::fmt;
/// use valuable::{Value, Valuable};
///
/// struct Meters(u32);
///
/// impl fmt::Display for Meters {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "{}m", self.0)
/// }
/// }
///
/// let meters = Meters(5);
/// let v = Value::Display(&meters);
/// ```
Display(&'a dyn fmt::Display),

/// A Rust `()` or `None` value.
///
/// # Examples
Expand Down Expand Up @@ -104,6 +125,7 @@ macro_rules! value {
$(#[$attrs])*
$variant(v) => fmt::Debug::fmt(v, fmt),
)*
Display(d) => d.fmt(fmt),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i wonder if we want to quote this while debug printing it? it's essentially a different way of recording a string, and strings are quoted in fmt::Debug. @carllerche WDYT?

Unit => ().fmt(fmt),
}
}
Expand Down Expand Up @@ -690,6 +712,34 @@ macro_rules! convert {
_ => None,
}
}

/// Return a `&dyn Display` representation of `self`, if possible.
///
/// # Examples
///
/// ```
/// use std::fmt;
/// use valuable::{Value, Valuable};
///
/// struct Meters(u32);
///
/// impl fmt::Display for Meters {
/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
/// write!(f, "{}m", self.0)
/// }
/// }
///
/// let meters = Meters(5);
///
/// assert!(Value::Display(&meters).as_display().is_some());
/// assert!(Value::Bool(true).as_display().is_none());
/// ```
pub fn as_display(&self) -> Option<&dyn fmt::Display> {
match *self {
Value::Display(v) => Some(v),
_ => None,
}
}
}
}
}
Expand Down