From 1ee887a2fcd7f7df0f2a04f915031841db6c1499 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 21 Feb 2024 14:43:04 +1100 Subject: [PATCH] Make from_hex inherent for byte-like types Byte like types naturally display in hex, therefore they should have an inherent method `from_hex` and not implement `FromHex`. --- bitcoin/src/internal_macros.rs | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/bitcoin/src/internal_macros.rs b/bitcoin/src/internal_macros.rs index 875a2a6f..49c8cf5e 100644 --- a/bitcoin/src/internal_macros.rs +++ b/bitcoin/src/internal_macros.rs @@ -50,7 +50,6 @@ pub(crate) use impl_consensus_encoding; /// - core::fmt::UpperHex /// - core::fmt::Display /// - core::str::FromStr -/// - hex::FromHex macro_rules! impl_bytes_newtype { ($t:ident, $len:literal) => { impl $t { @@ -68,6 +67,11 @@ macro_rules! impl_bytes_newtype { self.0 } + + /// Creates `Self` from a hex string. + pub fn from_hex(s: &str) -> Result { + Ok($t($crate::hex::FromHex::from_hex(s)?)) + } } impl core::fmt::LowerHex for $t { @@ -96,22 +100,9 @@ macro_rules! impl_bytes_newtype { } } - impl $crate::hex::FromHex for $t { - type Err = $crate::hex::HexToArrayError; - - fn from_byte_iter(iter: I) -> core::result::Result - where - I: core::iter::Iterator> - + core::iter::ExactSizeIterator - + core::iter::DoubleEndedIterator, - { - Ok($t($crate::hex::FromHex::from_byte_iter(iter)?)) - } - } - impl core::str::FromStr for $t { type Err = $crate::hex::HexToArrayError; - fn from_str(s: &str) -> core::result::Result { $crate::hex::FromHex::from_hex(s) } + fn from_str(s: &str) -> core::result::Result { Self::from_hex(s) } } #[cfg(feature = "serde")] @@ -145,17 +136,17 @@ macro_rules! impl_bytes_newtype { use $crate::serde::de::Unexpected; if let Ok(hex) = core::str::from_utf8(v) { - $crate::hex::FromHex::from_hex(hex).map_err(E::custom) + core::str::FromStr::from_str(hex).map_err(E::custom) } else { return Err(E::invalid_value(Unexpected::Bytes(v), &self)); } } - fn visit_str(self, v: &str) -> core::result::Result + fn visit_str(self, hex: &str) -> core::result::Result where E: $crate::serde::de::Error, { - $crate::hex::FromHex::from_hex(v).map_err(E::custom) + core::str::FromStr::from_str(hex).map_err(E::custom) } }