@@ -77,19 +77,18 @@ impl<const BYTES: usize> TryFrom<Vec<u8>> for Hash<BYTES> {
7777 type Error = Vec < u8 > ;
7878
7979 fn try_from ( value : Vec < u8 > ) -> Result < Self , Self :: Error > {
80- let hash: [ u8 ; BYTES ] = value. try_into ( ) ?;
81- Ok ( Self :: new ( hash) )
80+ Self :: try_from ( value. as_slice ( ) ) . map_err ( |_| value)
8281 }
8382}
8483
85- impl < const BYTES : usize > From < Hash < BYTES > > for Vec < u8 > {
86- fn from ( hash : Hash < BYTES > ) -> Self {
84+ impl < const BYTES : usize > From < & Hash < BYTES > > for Vec < u8 > {
85+ fn from ( hash : & Hash < BYTES > ) -> Self {
8786 hash. 0 . to_vec ( )
8887 }
8988}
9089
91- impl < const BYTES : usize > From < Hash < BYTES > > for [ u8 ; BYTES ] {
92- fn from ( hash : Hash < BYTES > ) -> Self {
90+ impl < const BYTES : usize > From < & Hash < BYTES > > for [ u8 ; BYTES ] {
91+ fn from ( hash : & Hash < BYTES > ) -> Self {
9392 hash. 0
9493 }
9594}
@@ -278,7 +277,7 @@ macro_rules! declare_hash_type_with_bech32 {
278277 impl std:: str :: FromStr for $name {
279278 type Err = hex:: FromHexError ;
280279 fn from_str( s: & str ) -> Result <Self , Self :: Err > {
281- Ok ( Self ( s. parse( ) ?) )
280+ Ok ( Self ( s. parse:: < Hash <$size>> ( ) ?) )
282281 }
283282 }
284283
@@ -310,14 +309,30 @@ macro_rules! declare_hash_type_with_bech32 {
310309 impl crate :: serialization:: Bech32Conversion for $name {
311310 fn to_bech32( & self ) -> Result <String , anyhow:: Error > {
312311 use crate :: serialization:: Bech32WithHrp ;
313- self . 0 . to_vec( ) . to_bech32_with_hrp( $hrp)
312+ use anyhow:: Context ;
313+
314+ self . to_vec( ) . to_bech32_with_hrp( $hrp) . with_context( || {
315+ format!(
316+ "Failed to encode {} to bech32 with HRP '{}'" ,
317+ stringify!( $name) ,
318+ $hrp
319+ )
320+ } )
314321 }
315322
316323 fn from_bech32( s: & str ) -> Result <Self , anyhow:: Error > {
317324 use crate :: serialization:: Bech32WithHrp ;
318- let v = Vec :: <u8 >:: from_bech32_with_hrp( s, $hrp) ?;
325+ use anyhow:: Context ;
326+
327+ let v = Vec :: <u8 >:: from_bech32_with_hrp( s, $hrp) . with_context( || {
328+ format!( "Failed to decode {} from bech32" , stringify!( $name) )
329+ } ) ?;
330+
319331 Self :: try_from( v) . map_err( |_| {
320- anyhow:: Error :: msg( format!( "Bad vector input to {}" , stringify!( $name) ) )
332+ anyhow:: anyhow!(
333+ "Failed to create {} from decoded bech32 data" ,
334+ stringify!( $name)
335+ )
321336 } )
322337 }
323338 }
@@ -367,7 +382,7 @@ mod tests {
367382 fn into_vec ( ) {
368383 let bytes = [ 0u8 ; 28 ] ;
369384 let hash = Hash :: new ( bytes) ;
370- let vec: Vec < u8 > = hash. into ( ) ;
385+ let vec: Vec < u8 > = hash. as_ref ( ) . into ( ) ;
371386 assert_eq ! ( vec, bytes. to_vec( ) ) ;
372387 }
373388
0 commit comments