frame_decode/utils/
decode_with_error_tracing.rsuse alloc::format;
use alloc::string::String;
pub fn decode_with_error_tracing<'scale, 'resolver, Resolver, Id, V>(
cursor: &mut &'scale [u8],
type_id: Id,
types: &'resolver Resolver,
visitor: V,
) -> Result<V::Value<'scale, 'resolver>, DecodeErrorTrace>
where
Resolver: scale_type_resolver::TypeResolver<TypeId = Id>,
Id: core::fmt::Debug + Clone,
V: scale_decode::Visitor<TypeResolver = Resolver>,
V::Error: core::fmt::Debug,
{
let initial = *cursor;
match scale_decode::visitor::decode_with_visitor(cursor, type_id.clone(), types, visitor) {
Ok(value) => Ok(value),
#[cfg(not(feature = "error-tracing"))]
Err(e) => {
*cursor = initial;
Err(DecodeErrorTrace {
original_error: format!("{e:?}"),
tracing_error: String::new(),
})
}
#[cfg(feature = "error-tracing")]
Err(e) => {
*cursor = initial;
let res = scale_value::scale::tracing::decode_as_type(cursor, type_id.clone(), types)
.map(|v| v.map_context(|id| format!("{id:?}")))
.map_err(|te| DecodeErrorTrace {
original_error: format!("{e:?}"),
tracing_error: te.to_string(),
})?;
use core::fmt::Write;
let mut res_string = String::new();
write!(
&mut res_string,
"Failed to decode value with custom visitor (but tracing decoded it):\n\n"
)
.unwrap();
scale_value::stringify::to_writer_custom()
.pretty()
.format_context(|type_id, w: &mut &mut String| write!(w, "{type_id}"))
.add_custom_formatter(|v, w| {
scale_value::stringify::custom_formatters::format_hex(v, w)
})
.add_custom_formatter(|v, w| {
if let scale_value::ValueDef::Composite(scale_value::Composite::Unnamed(vals)) =
&v.value
{
let are_primitive = vals
.iter()
.all(|val| matches!(val.value, scale_value::ValueDef::Primitive(_)));
if are_primitive {
return Some(write!(w, "{v}"));
}
}
None
})
.write(&res, &mut res_string)
.expect("writing to string should always succeed");
Err(DecodeErrorTrace {
original_error: format!("{e:?}"),
tracing_error: res_string,
})
}
}
}
#[derive(Clone, Debug)]
pub struct DecodeErrorTrace {
original_error: String,
tracing_error: String,
}
impl core::error::Error for DecodeErrorTrace {}
impl core::fmt::Display for DecodeErrorTrace {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let DecodeErrorTrace {
original_error,
tracing_error,
} = self;
write!(f, "{original_error}")?;
if !tracing_error.is_empty() {
write!(f, ":\n\n{tracing_error}")?;
}
Ok(())
}
}