Abstract out "debug-print hex fields" using WrapDebug

This commit introduces `WrapDebug` in `internals` and updates `Witness`
debug implementation to use it. The previous `DebugElements` struct has
been removed in favor of an ad-hoc closure inside `WrapDebug`, which
formats witness elements as a debug list of hex-encoded values.

By abstracting out the "debug-print hex fields" pattern, we reduce
code duplication and improve maintainability.
This commit is contained in:
Erick Cestari 2025-02-20 10:46:09 -03:00
parent e487618503
commit 4eb3177fab
3 changed files with 17 additions and 10 deletions

View File

@ -42,6 +42,7 @@ pub mod error;
pub mod macros; pub mod macros;
mod parse; mod parse;
pub mod script; pub mod script;
pub mod wrap_debug;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
#[macro_use] #[macro_use]
pub mod serde; pub mod serde;

View File

@ -0,0 +1,9 @@
//! Contains a wrapper for a function that implements `Debug`.
use core::fmt;
/// A wrapper for a function that implements `Debug`.
pub struct WrapDebug<F: Fn(&mut fmt::Formatter) -> fmt::Result>(pub F);
impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> fmt::Debug for WrapDebug<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.0)(f) }
}

View File

@ -11,6 +11,7 @@ use core::ops::Index;
use arbitrary::{Arbitrary, Unstructured}; use arbitrary::{Arbitrary, Unstructured};
use hex::DisplayHex; use hex::DisplayHex;
use internals::compact_size; use internals::compact_size;
use internals::wrap_debug::WrapDebug;
use crate::prelude::Vec; use crate::prelude::Vec;
@ -232,15 +233,6 @@ fn decode_cursor(bytes: &[u8], start_of_indices: usize, index: usize) -> Option<
} }
} }
/// Debug implementation that displays the witness as a structured output containing hex-encoded witness elements.
struct DebugElements<'a>(&'a Witness);
impl fmt::Debug for DebugElements<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.iter().map(|elem| elem.as_hex())).finish()
}
}
/// Debug implementation that displays the witness as a structured output containing: /// Debug implementation that displays the witness as a structured output containing:
/// - Number of witness elements /// - Number of witness elements
/// - Total bytes across all elements /// - Total bytes across all elements
@ -252,7 +244,12 @@ impl fmt::Debug for Witness {
f.debug_struct("Witness") f.debug_struct("Witness")
.field("num_elements", &self.witness_elements) .field("num_elements", &self.witness_elements)
.field("total_bytes", &total_bytes) .field("total_bytes", &total_bytes)
.field("elements", &DebugElements(self)) .field(
"elements",
&WrapDebug(|f| {
f.debug_list().entries(self.iter().map(|elem| elem.as_hex())).finish()
}),
)
.finish() .finish()
} }
} }