Skip to content

Commit

Permalink
Add consensus::deserialize_hex function
Browse files Browse the repository at this point in the history
We have `serialize_hex` and `deserialize` but no `deserialize_hex`, add
it.
  • Loading branch information
tcharding committed Aug 29, 2023
1 parent 7fd9b89 commit 1d7e3b6
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions bitcoin/src/consensus/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ pub mod params;
#[cfg(feature = "bitcoinconsensus")]
pub mod validation;

use core::fmt;

use hex::{FromHex, HexToBytesError};
use internals::write_err;

pub use self::encode::{
deserialize, deserialize_partial, serialize, Decodable, Encodable, ReadExt, WriteExt,
};
Expand All @@ -20,5 +25,50 @@ pub use self::validation::{
verify_script, verify_script_with_flags, verify_transaction, verify_transaction_with_flags,
};

/// Deserialize any decodable type from a hex string.
pub fn deserialize_hex<T: Decodable>(hex: &str) -> Result<T, FromHexError> {
let v = Vec::from_hex(hex)?;
Ok(deserialize(&v)?)
}

/// Hex decoding error.
#[derive(Debug)]
pub enum FromHexError {
/// Hex decoding error.
Decode(HexToBytesError),
/// Consensus deserialization error.
Deser(encode::Error),
}

impl fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use FromHexError::*;

match *self {
Decode(ref e) => write_err!(f, "hex decoding erorr"; e),
Deser(ref e) => write_err!(f, "consensus deserialization error"; e),
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for FromHexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use FromHexError::*;

match *self {
Decode(_) | Deser(_) => None,
}
}
}

impl From<HexToBytesError> for FromHexError {
fn from(e: HexToBytesError) -> Self { Self::Decode(e) }
}

impl From<encode::Error> for FromHexError {
fn from(e: encode::Error) -> Self { Self::Deser(e) }
}

#[cfg(feature = "serde")]
pub mod serde;

0 comments on commit 1d7e3b6

Please sign in to comment.