Skip to content

Commit

Permalink
fix: make from_str parse 0x-prefixed strings (#487)
Browse files Browse the repository at this point in the history
* fix: make from_str parse 0x-prefixed strings

* fix(uint): make from_str parse 0x-prefixed strings

* chore: address review styling comments

* fix: tabs instead of spaces

* chore: cargo fmt

* fix: use strip_prefix instead of starts_with
  • Loading branch information
gakonst committed Dec 30, 2020
1 parent e64bf1a commit 0264ebf
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 0 deletions.
5 changes: 5 additions & 0 deletions ethereum-types/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ mod tests {
}
}

#[test]
fn test_parse_0x() {
assert!("0x0000000000000000000000000000000000000000000000000000000000000000".parse::<H256>().is_ok())
}

#[test]
fn test_serialize_invalid() {
assert!(ser::from_str::<H256>("\"0x000000000000000000000000000000000000000000000000000000000000000\"")
Expand Down
1 change: 1 addition & 0 deletions fixed-hash/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ macro_rules! impl_rustc_hex_for_fixed_hash {
/// - When encountering invalid non hex-digits
/// - Upon empty string input or invalid input length in general
fn from_str(input: &str) -> $crate::core_::result::Result<$name, $crate::rustc_hex::FromHexError> {
let input = input.strip_prefix("0x").unwrap_or(input);
let mut iter = $crate::rustc_hex::FromHexIter::new(input);
let mut result = Self::zero();
for byte in result.as_mut() {
Expand Down
1 change: 1 addition & 0 deletions uint/src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1688,6 +1688,7 @@ macro_rules! construct_uint {
type Err = $crate::FromHexError;

fn from_str(value: &str) -> $crate::core_::result::Result<$name, Self::Err> {
let value = value.strip_prefix("0x").unwrap_or(value);
const BYTES_LEN: usize = $n_words * 8;
const MAX_ENCODED_LEN: usize = BYTES_LEN * 2;

Expand Down
2 changes: 2 additions & 0 deletions uint/tests/uint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ fn uint256_from() {

// test initializtion from string
let sa = U256::from_str("0a").unwrap();
let sa2 = U256::from_str("0x0a").unwrap();
assert_eq!(sa2, sa);
assert_eq!(e, sa);
assert_eq!(U256([0, 0, 0, 0]), U256::from_str("").unwrap());
assert_eq!(U256([0x1, 0, 0, 0]), U256::from_str("1").unwrap());
Expand Down

0 comments on commit 0264ebf

Please sign in to comment.