From 9c76d5789fecfdb3b1bb5e0852897acf7707d3d5 Mon Sep 17 00:00:00 2001 From: Jack Grigg Date: Mon, 15 May 2023 20:45:38 +0000 Subject: [PATCH] Render byte slices as hex more often in `Debug` impls This is more generally useful for debugging purposes than the default `Debug` impl for `&[u8]`. We also provide an alternate `Debug` impl for `legacy::Script` that parses and renders known opcodes. Note that we only parse a subset of the full opcode set. Extracted from: https://github.com/zcash/librustzcash/commit/c8e2d81f58d4ba0193017633b983e251639b625d --- src/lib.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index fb8049d..16c089b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,8 @@ #![deny(unsafe_code)] // TODO: #![deny(missing_docs)] +use core::fmt::{self, Write}; + #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "alloc")] @@ -72,9 +74,28 @@ impl AsRef<[u8]> for OutgoingCipherKey { /// Newtype representing the byte encoding of an [`EphemeralPublicKey`]. /// /// [`EphemeralPublicKey`]: Domain::EphemeralPublicKey -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct EphemeralKeyBytes(pub [u8; 32]); +impl fmt::Debug for EphemeralKeyBytes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + struct HexFmt<'b>(&'b [u8]); + impl<'b> fmt::Debug for HexFmt<'b> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_char('"')?; + for b in self.0 { + f.write_fmt(format_args!("{:02x}", b))?; + } + f.write_char('"') + } + } + + f.debug_tuple("EphemeralKeyBytes") + .field(&HexFmt(&self.0)) + .finish() + } +} + impl AsRef<[u8]> for EphemeralKeyBytes { fn as_ref(&self) -> &[u8] { &self.0