Skip to main content

secure_gate/traits/decoding/
hex.rs

1//! # FromHexStr Trait
2//!
3//! Extension trait for decoding hex strings to byte data.
4//!
5//! This trait provides secure, explicit decoding of hex strings to byte vectors.
6//! Input should be treated as untrusted; use fallible methods.
7//!
8//! ## Security Warning
9//!
10//! Decoding input from untrusted sources should use fallible `try_` methods.
11//! Invalid input may indicate tampering or errors.
12//!
13
14#[cfg(feature = "encoding-hex")]
15use ::hex as hex_crate;
16
17#[cfg(feature = "encoding-hex")]
18use crate::error::HexError;
19
20/// Extension trait for decoding hex strings to byte data.
21///
22/// Input should be treated as untrusted; use fallible methods.
23///
24/// # Security Warning
25///
26/// Decoding input from untrusted sources should use fallible `try_` methods.
27/// Invalid input may indicate tampering or errors.
28///
29/// ## Example
30///
31/// ```rust
32/// # #[cfg(feature = "encoding-hex")]
33/// use secure_gate::FromHexStr;
34/// # #[cfg(feature = "encoding-hex")]
35/// let hex_string = "424344";
36/// # #[cfg(feature = "encoding-hex")]
37/// let bytes = hex_string.try_from_hex().unwrap();
38/// // bytes is now Vec<u8>: [66, 66, 66]
39/// ```
40#[cfg(feature = "encoding-hex")]
41pub trait FromHexStr {
42    /// Fallibly decode a hex string to bytes.
43    fn try_from_hex(&self) -> Result<Vec<u8>, HexError>;
44}
45
46// Blanket impl to cover any AsRef<str> (e.g., &str, String, etc.)
47#[cfg(feature = "encoding-hex")]
48impl<T: AsRef<str> + ?Sized> FromHexStr for T {
49    fn try_from_hex(&self) -> Result<Vec<u8>, HexError> {
50        hex_crate::decode(self.as_ref()).map_err(|_| HexError::InvalidHex)
51    }
52}