Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Display variant to Value. #85

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
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.
chanks marked this conversation as resolved.
Show resolved Hide resolved
///
/// # 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,
chanks marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}
}
Expand Down