|
38 | 38 | use crate::callsite;
|
39 | 39 | use core::{
|
40 | 40 | borrow::Borrow,
|
41 |
| - fmt, |
| 41 | + fmt::{self, Write}, |
42 | 42 | hash::{Hash, Hasher},
|
43 | 43 | num,
|
44 | 44 | ops::Range,
|
@@ -224,6 +224,11 @@ pub trait Visit {
|
224 | 224 | self.record_debug(field, &value)
|
225 | 225 | }
|
226 | 226 |
|
| 227 | + /// Visit a byte slice. |
| 228 | + fn record_bytes(&mut self, field: &Field, value: &[u8]) { |
| 229 | + self.record_debug(field, &HexBytes(value)) |
| 230 | + } |
| 231 | + |
227 | 232 | /// Records a type implementing `Error`.
|
228 | 233 | ///
|
229 | 234 | /// <div class="example-wrap" style="display:inline-block">
|
@@ -283,6 +288,26 @@ where
|
283 | 288 | DebugValue(t)
|
284 | 289 | }
|
285 | 290 |
|
| 291 | +struct HexBytes<'a>(&'a [u8]); |
| 292 | + |
| 293 | +impl<'a> fmt::Debug for HexBytes<'a> { |
| 294 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 295 | + f.write_char('[')?; |
| 296 | + |
| 297 | + let mut bytes = self.0.iter(); |
| 298 | + |
| 299 | + if let Some(byte) = bytes.next() { |
| 300 | + f.write_fmt(format_args!("{byte:02x}"))?; |
| 301 | + } |
| 302 | + |
| 303 | + for byte in bytes { |
| 304 | + f.write_fmt(format_args!(" {byte:02x}"))?; |
| 305 | + } |
| 306 | + |
| 307 | + f.write_char(']') |
| 308 | + } |
| 309 | +} |
| 310 | + |
286 | 311 | // ===== impl Visit =====
|
287 | 312 |
|
288 | 313 | impl<'a, 'b> Visit for fmt::DebugStruct<'a, 'b> {
|
@@ -443,6 +468,14 @@ impl Value for str {
|
443 | 468 | }
|
444 | 469 | }
|
445 | 470 |
|
| 471 | +impl crate::sealed::Sealed for [u8] {} |
| 472 | + |
| 473 | +impl Value for [u8] { |
| 474 | + fn record(&self, key: &Field, visitor: &mut dyn Visit) { |
| 475 | + visitor.record_bytes(key, self) |
| 476 | + } |
| 477 | +} |
| 478 | + |
446 | 479 | #[cfg(feature = "std")]
|
447 | 480 | impl crate::sealed::Sealed for dyn std::error::Error + 'static {}
|
448 | 481 |
|
@@ -1131,4 +1164,23 @@ mod test {
|
1131 | 1164 | });
|
1132 | 1165 | assert_eq!(result, format!("{}", err));
|
1133 | 1166 | }
|
| 1167 | + |
| 1168 | + #[test] |
| 1169 | + fn record_bytes() { |
| 1170 | + let fields = TEST_META_1.fields(); |
| 1171 | + let first = &b"abc"[..]; |
| 1172 | + let second: &[u8] = &[192, 255, 238]; |
| 1173 | + let values = &[ |
| 1174 | + (&fields.field("foo").unwrap(), Some(&first as &dyn Value)), |
| 1175 | + (&fields.field("bar").unwrap(), Some(&" " as &dyn Value)), |
| 1176 | + (&fields.field("baz").unwrap(), Some(&second as &dyn Value)), |
| 1177 | + ]; |
| 1178 | + let valueset = fields.value_set(values); |
| 1179 | + let mut result = String::new(); |
| 1180 | + valueset.record(&mut |_: &Field, value: &dyn fmt::Debug| { |
| 1181 | + use core::fmt::Write; |
| 1182 | + write!(&mut result, "{:?}", value).unwrap(); |
| 1183 | + }); |
| 1184 | + assert_eq!(result, format!("{}", r#"[61 62 63]" "[c0 ff ee]"#)); |
| 1185 | + } |
1134 | 1186 | }
|
0 commit comments