Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions tracing-core/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,13 @@ pub trait Value: crate::sealed::Sealed {
#[derive(Clone)]
pub struct DisplayValue<T: fmt::Display>(T);

/// A `Value` which serializes using alternate `fmt::Display`.
///
/// Uses `record_debug` in the `Value` implementation to
/// avoid an unnecessary evaluation.
#[derive(Clone)]
pub struct DisplayAltValue<T: fmt::Display>(T);

/// A `Value` which serializes as a string using `fmt::Debug`.
#[derive(Clone)]
pub struct DebugValue<T: fmt::Debug>(T);
Expand All @@ -279,6 +286,15 @@ where
DisplayValue(t)
}

/// Wraps a type implementing `fmt::Display` as a `Value` that can be
/// recorded using its alternate `Display` implementation.
pub fn display_alt<T>(t: T) -> DisplayAltValue<T>
where
T: fmt::Display,
{
DisplayAltValue(t)
}

/// Wraps a type implementing `fmt::Debug` as a `Value` that can be
/// recorded using its `Debug` implementation.
pub fn debug<T>(t: T) -> DebugValue<T>
Expand Down Expand Up @@ -639,6 +655,31 @@ impl<T: fmt::Display> fmt::Display for DisplayValue<T> {
}
}

// ===== impl DisplayAltValue =====

impl<T: fmt::Display> crate::sealed::Sealed for DisplayAltValue<T> {}

impl<T> Value for DisplayAltValue<T>
where
T: fmt::Display,
{
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
visitor.record_debug(key, self)
}
}

impl<T: fmt::Display> fmt::Debug for DisplayAltValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&format_args!("{:#}", self), f)
}
}

impl<T: fmt::Display> fmt::Display for DisplayAltValue<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
format_args!("{:#}", self.0).fmt(f)
}
}

// ===== impl DebugValue =====

impl<T: fmt::Debug> crate::sealed::Sealed for DebugValue<T> {}
Expand Down Expand Up @@ -1197,4 +1238,32 @@ mod test {
});
assert_eq!(result, format!("{}", r#"[61 62 63]" "[c0 ff ee]"#));
}

#[test]
fn display_alt_value() {
struct AlternateString<'a>(&'a str);

impl std::fmt::Display for AlternateString<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
write!(f, "{} with alternate", self.0)
} else {
self.0.fmt(f)
}
}
}

let alt_str = AlternateString("hello world");

let display = "hello world";
assert_eq!(display, format!("{}", &alt_str));

let alt_display = "hello world with alternate";
assert_eq!(alt_display, format!("{:#}", &alt_str));

assert_eq!(alt_display, format!("{}", display_alt(&alt_str)));
assert_eq!(alt_display, format!("{:#}", display_alt(&alt_str)));
assert_eq!(alt_display, format!("{:?}", display_alt(&alt_str)));
assert_eq!(alt_display, format!("{:#?}", display_alt(&alt_str)));
}
}
Loading