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
This commit is contained in:
Tobin C. Harding 2022-12-07 12:40:57 +11:00
parent 52fbb043b6
commit b7a84d0c68
2 changed files with 14 additions and 13 deletions

View File

@ -17,6 +17,7 @@ panic-halt = "0.2.0"
alloc-cortex-m = "0.4.1" alloc-cortex-m = "0.4.1"
bitcoin = { path="../", default-features = false, features = ["no-std", "secp-lowmemory"] } bitcoin = { path="../", default-features = false, features = ["no-std", "secp-lowmemory"] }
[[bin]] [[bin]]
name = "embedded" name = "embedded"
test = false test = false

View File

@ -28,9 +28,9 @@ macro_rules! hex_fmt_impl(
write!(f, "0x")?; write!(f, "0x")?;
} }
if $ty::<$($gen),*>::DISPLAY_BACKWARD { if $ty::<$($gen),*>::DISPLAY_BACKWARD {
hex::format_hex_reverse(&self.0, f) hex::format_hex_reverse(self.as_ref(), f)
} else { } else {
hex::format_hex(&self.0, f) hex::format_hex(self.as_ref(), f)
} }
} }
} }
@ -67,14 +67,6 @@ macro_rules! borrow_slice_impl(
&self[..] &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}; use crate::{Hash, sha256};
#[test] #[test]
fn borrow_slice_impl_to_vec() { fn hash_as_ref() {
// Test that the borrow_slice_impl macro gives to_vec.
let hash = sha256::Hash::hash(&[3, 50]); 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."); hash_newtype!(TestHash, crate::sha256d::Hash, 32, doc="Test hash.");