Skip to content

Commit

Permalink
Update FromHex trait
Browse files Browse the repository at this point in the history
Hex strings may or may not include a prefix. We want to default to
explicitly disallowing a prefix in `FromHex` because that is the
behaviour we expect in `rust-bitcoin`.

Add functions to the `FromHex` trait for various prefix states.
  • Loading branch information
tcharding committed Feb 12, 2024
1 parent bbb2db2 commit c5a4cdf
Showing 1 changed file with 118 additions and 3 deletions.
121 changes: 118 additions & 3 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
use core::{fmt, str};

#[cfg(all(feature = "alloc", not(feature = "std")))]
use crate::alloc::vec::Vec;
use crate::alloc::{string::String, vec::Vec};
use crate::error::InvalidLengthError;
use crate::iter::HexToBytesIter;
use crate::write_err;

#[rustfmt::skip] // Keep public re-exports separate.
pub use crate::error::{HexToBytesError, HexToArrayError};
Expand All @@ -22,9 +23,64 @@ pub trait FromHex: Sized {
where
I: Iterator<Item = Result<u8, HexToBytesError>> + ExactSizeIterator + DoubleEndedIterator;

/// Parses provided string as hex explicitly requiring there to not be a `0x` prefix.
///
/// This is not recommended for user-supplied inputs because of possible confusion with decimals.
/// It should be only used for existing protocols which always encode values as hex without 0x prefix.
#[rustfmt::skip]
fn from_hex<
#[cfg(feature = "alloc")] S: AsRef<str> + Into<String>,
#[cfg(not(feature = "alloc"))] S: AsRef<str>,
>(s: S) -> Result<Self, Self::Error> {
Self::from_no_prefix_hex(s)
}

/// Produces an object from a hex string.
fn from_hex(s: &str) -> Result<Self, Self::Error> {
Self::from_byte_iter(HexToBytesIter::new(s)?)
///
/// Accepts an input string either with `0x` prefix or without, if you require specific handling
/// of the prefix see [`Self::from_prefixed_hex`] and [`Self::from_no_prefix_hex`].
#[rustfmt::skip]
fn from_maybe_prefixed_hex<
#[cfg(feature = "alloc")] S: AsRef<str> + Into<String>,
#[cfg(not(feature = "alloc"))] S: AsRef<str>,
>(s: S) -> Result<Self, Self::Error> {
if s.as_ref().starts_with("0x") {
Self::from_no_prefix_hex(s.as_ref().trim_start_matches("0x"))
} else {
Self::from_no_prefix_hex(s)
}
}

/// Parses provided string as hex explicitly requiring there to not be a `0x` prefix.
///
/// This is not recommended for user-supplied inputs because of possible confusion with decimals.
/// It should be only used for existing protocols which always encode values as hex without 0x prefix.
#[rustfmt::skip]
fn from_no_prefix_hex<
#[cfg(feature = "alloc")] S: AsRef<str> + Into<String>,
#[cfg(not(feature = "alloc"))] S: AsRef<str>,
>(s: S) -> Result<Self, Self::Error> {
Self::from_byte_iter(HexToBytesIter::new(s.as_ref())?)
}

/// Parses provided string as hex requiring 0x prefix.
///
/// This is intended for user-supplied inputs or already-existing protocols in which 0x prefix is used.
#[rustfmt::skip]
fn from_prefixed_hex<
#[cfg(feature = "alloc")] S: AsRef<str> + Into<String>,
#[cfg(not(feature = "alloc"))] S: AsRef<str>,
>(s: S) -> Result<Self, PrefixedError<Self::Error>> {
use PrefixedError::*;

if !s.as_ref().starts_with("0x") {
#[cfg(feature = "alloc")]
return Err(MissingPrefix(MissingPrefixError(s.into())));
#[cfg(not(feature = "alloc"))]
return Err(MissingPrefix(MissingPrefixError()));
} else {
Ok(Self::from_no_prefix_hex(s.as_ref().trim_start_matches("0x"))?)
}
}
}

Expand Down Expand Up @@ -86,6 +142,65 @@ impl_fromhex_array!(256);
impl_fromhex_array!(384);
impl_fromhex_array!(512);

/// Hex parsing error
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrefixedError<E> {
/// The input was not a valid hex string, contains the error that occurred while parsing.
ParseHex(E),
/// The input is missing `0x` prefix, contains the invalid input.
MissingPrefix(MissingPrefixError),
}

impl<E> From<E> for PrefixedError<E> {
fn from(e: E) -> Self { PrefixedError::ParseHex(e) }
}

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

match *self {
ParseHex(ref e) => write_err!(f, "failed to parse hex string"; e),
MissingPrefix(ref e) => write_err!(f, "missing prefix"; e),
}
}
}

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

match *self {
ParseHex(ref e) => Some(e),
MissingPrefix(ref e) => Some(e),
}
}
}

/// Hex string was missing the `0x` prefix.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MissingPrefixError(#[cfg(feature = "alloc")] String);

impl fmt::Display for MissingPrefixError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
#[cfg(feature = "alloc")]
let res = write!(f, "the input value `{}` is missing the `0x` prefix", self.0);
#[cfg(not(feature = "alloc"))]
let res = write!(f, "input string is missing the `0x` prefix");

res
}
}

#[cfg(feature = "std")]
impl std::error::Error for MissingPrefixError {}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit c5a4cdf

Please sign in to comment.