Skip to content

Commit 55fdc75

Browse files
authored
core: add Value impl for Box<T> where T: Value (#2071)
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
1 parent a421763 commit 55fdc75

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

tracing-core/src/field.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,21 @@ impl<'a> Value for fmt::Arguments<'a> {
488488
}
489489
}
490490

491+
#[cfg(feature = "alloc")]
492+
impl<T: ?Sized> crate::sealed::Sealed for alloc::boxed::Box<T> where T: Value {}
493+
494+
#[cfg(feature = "alloc")]
495+
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
496+
impl<T: ?Sized> Value for alloc::boxed::Box<T>
497+
where
498+
T: Value,
499+
{
500+
#[inline]
501+
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
502+
self.as_ref().record(key, visitor)
503+
}
504+
}
505+
491506
impl fmt::Debug for dyn Value {
492507
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493508
// We are only going to be recording the field value, so we don't
@@ -1021,4 +1036,24 @@ mod test {
10211036
});
10221037
assert_eq!(result, String::from("123"));
10231038
}
1039+
1040+
#[test]
1041+
#[cfg(feature = "std")]
1042+
fn record_error() {
1043+
let fields = TEST_META_1.fields();
1044+
let err: Box<dyn std::error::Error + Send + Sync + 'static> =
1045+
std::io::Error::new(std::io::ErrorKind::Other, "lol").into();
1046+
let values = &[
1047+
(&fields.field("foo").unwrap(), Some(&err as &dyn Value)),
1048+
(&fields.field("bar").unwrap(), Some(&Empty as &dyn Value)),
1049+
(&fields.field("baz").unwrap(), Some(&Empty as &dyn Value)),
1050+
];
1051+
let valueset = fields.value_set(values);
1052+
let mut result = String::new();
1053+
valueset.record(&mut |_: &Field, value: &dyn fmt::Debug| {
1054+
use core::fmt::Write;
1055+
write!(&mut result, "{:?}", value).unwrap();
1056+
});
1057+
assert_eq!(result, format!("{}", err));
1058+
}
10241059
}

0 commit comments

Comments
 (0)