Skip to content

Commit

Permalink
core: add Value impl for Box<T> where T: Value (#2071)
Browse files Browse the repository at this point in the history
This commit adds a `Value` implementation for `Box<T> where T: Value`.
This is *primarily* intended to make `Box<dyn Error + ...>` implement
`Value`, building on the `Value` impls for `dyn Error + ...` added in
#2066, but it may be useful for other boxed values as well.

Refs: #1308
  • Loading branch information
hawkw committed Apr 14, 2022
1 parent 8c67359 commit 96347c7
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions tracing-core/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,18 @@ impl<'a> Value for fmt::Arguments<'a> {
}
}

impl<T: ?Sized> crate::sealed::Sealed for crate::stdlib::boxed::Box<T> where T: Value {}

impl<T: ?Sized> Value for crate::stdlib::boxed::Box<T>
where
T: Value,
{
#[inline]
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
self.as_ref().record(key, visitor)
}
}

impl fmt::Debug for dyn Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// We are only going to be recording the field value, so we don't
Expand Down Expand Up @@ -1155,4 +1167,24 @@ mod test {
});
assert_eq!(result, "123".to_owned());
}

#[test]
#[cfg(feature = "std")]
fn record_error() {
let fields = TEST_META_1.fields();
let err: Box<dyn std::error::Error + Send + Sync + 'static> =
std::io::Error::new(std::io::ErrorKind::Other, "lol").into();
let values = &[
(&fields.field("foo").unwrap(), Some(&err as &dyn Value)),
(&fields.field("bar").unwrap(), Some(&Empty as &dyn Value)),
(&fields.field("baz").unwrap(), Some(&Empty as &dyn Value)),
];
let valueset = fields.value_set(values);
let mut result = String::new();
valueset.record(&mut |_: &Field, value: &dyn fmt::Debug| {
use core::fmt::Write;
write!(&mut result, "{:?}", value).unwrap();
});
assert_eq!(result, format!("{}", err));
}
}

0 comments on commit 96347c7

Please sign in to comment.