From b7a84d0c6841a86238a5884c9aa35404373928c4 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 7 Dec 2022 12:40:57 +1100 Subject: [PATCH] hashes: Do not implement Deref Currently we implement `Deref` for hashes. From the docs [0] > Deref should only be implemented for smart pointers to avoid confusion Furthermore because we implement `Deref` as well as implement `internals::hex::display::DisplayHex` for slices hashes get coerced into slices and `to_lower_hex_string` can be called on them, this is incorrect because `DisplayHex` does not account for hashes that display backwards so we end up with the wrong string. [0] https://doc.rust-lang.org/std/ops/trait.Deref.html --- bitcoin/embedded/Cargo.toml | 1 + hashes/src/util.rs | 26 +++++++++++++------------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/bitcoin/embedded/Cargo.toml b/bitcoin/embedded/Cargo.toml index 3971abf3..63742c10 100644 --- a/bitcoin/embedded/Cargo.toml +++ b/bitcoin/embedded/Cargo.toml @@ -17,6 +17,7 @@ panic-halt = "0.2.0" alloc-cortex-m = "0.4.1" bitcoin = { path="../", default-features = false, features = ["no-std", "secp-lowmemory"] } + [[bin]] name = "embedded" test = false diff --git a/hashes/src/util.rs b/hashes/src/util.rs index 77f4ce22..95353474 100644 --- a/hashes/src/util.rs +++ b/hashes/src/util.rs @@ -28,9 +28,9 @@ macro_rules! hex_fmt_impl( write!(f, "0x")?; } if $ty::<$($gen),*>::DISPLAY_BACKWARD { - hex::format_hex_reverse(&self.0, f) + hex::format_hex_reverse(self.as_ref(), f) } else { - hex::format_hex(&self.0, f) + hex::format_hex(self.as_ref(), f) } } } @@ -67,14 +67,6 @@ macro_rules! borrow_slice_impl( &self[..] } } - - impl<$($gen: $gent),*> $crate::_export::_core::ops::Deref for $ty<$($gen),*> { - type Target = [u8]; - - fn deref(&self) -> &Self::Target { - &self.0 - } - } ) ); @@ -240,10 +232,18 @@ mod test { use crate::{Hash, sha256}; #[test] - fn borrow_slice_impl_to_vec() { - // Test that the borrow_slice_impl macro gives to_vec. + fn hash_as_ref() { let hash = sha256::Hash::hash(&[3, 50]); - assert_eq!(hash.to_vec().len(), sha256::Hash::LEN); + assert_eq!(hash.as_ref(), hash.as_inner()); + } + + #[test] + fn hash_borrow() { + use core::borrow::Borrow; + + let hash = sha256::Hash::hash(&[3, 50]); + let borrowed: &[u8] = hash.borrow(); + assert_eq!(borrowed, hash.as_inner()); } hash_newtype!(TestHash, crate::sha256d::Hash, 32, doc="Test hash.");