diff options
| author | phayes <[email protected]> | 2020-01-15 09:59:36 -0800 |
|---|---|---|
| committer | phayes <[email protected]> | 2020-01-15 09:59:36 -0800 |
| commit | 3353f0e5a182e5d854fa7249fb711689fad29e68 (patch) | |
| tree | 982f164f7cc9ba7af875162bd2f0249be68f1938 | |
| parent | cfa310a49798ec41ae1d00edc8c842b35e13bd7c (diff) | |
Updating from_hex to accept a &str instead of an ArrayString
| -rw-r--r-- | src/lib.rs | 18 | ||||
| -rw-r--r-- | src/test.rs | 6 |
2 files changed, 13 insertions, 11 deletions
@@ -177,12 +177,18 @@ impl Hash { s } - /// Parse a fixed-length hexidecimal string and return the resulting Hash. + /// Parse a hexidecimal string and return the resulting Hash. /// - /// [`ArrayString`]: https://docs.rs/arrayvec/0.5.1/arrayvec/struct.ArrayString.html - pub fn from_hex(hex: ArrayString<[u8; 2 * OUT_LEN]>) -> Result<Self, ParseError> { + /// The string must be 64 characters long, producting a 32 byte digest. + /// All other string length will return a `ParseError::InvalidLen`. + pub fn from_hex(hex: &str) -> Result<Self, ParseError> { + let str_bytes = hex.as_bytes(); + if str_bytes.len() != OUT_LEN * 2 { + return Err(ParseError::InvalidLen); + } + let mut bytes: [u8; OUT_LEN] = [0; OUT_LEN]; - for (i, pair) in hex.as_str().as_bytes().chunks(2).enumerate() { + for (i, pair) in str_bytes.chunks(2).enumerate() { bytes[i] = hex_val(pair[0])? << 4 | hex_val(pair[1])?; } @@ -217,9 +223,7 @@ impl core::str::FromStr for Hash { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { - let string = - ArrayString::<[u8; OUT_LEN * 2]>::from(s).map_err(|_| ParseError::InvalidLen)?; - Hash::from_hex(string) + Hash::from_hex(s) } } diff --git a/src/test.rs b/src/test.rs index d1f73a9..6883c91 100644 --- a/src/test.rs +++ b/src/test.rs @@ -459,12 +459,10 @@ fn test_hex_encoding_decoding() { assert_eq!(digest.to_hex().as_str(), digest_str); // Test round trip - let input = arrayvec::ArrayString::from(digest_str).unwrap(); - assert_eq!(digest.to_hex().as_str(), digest_str); - let digest = crate::Hash::from_hex(input).unwrap(); + let digest = crate::Hash::from_hex(digest_str).unwrap(); assert_eq!(digest.to_hex().as_str(), digest_str); - // Test string parsing + // Test string parsing via FromStr let digest: crate::Hash = digest_str.parse().unwrap(); assert_eq!(digest.to_hex().as_str(), digest_str); } |
