diff --git a/units/src/parse.rs b/units/src/parse.rs index 52418f6b..967113f9 100644 --- a/units/src/parse.rs +++ b/units/src/parse.rs @@ -101,6 +101,19 @@ pub fn hex_u32 + Into>(s: S) -> Result }) } +/// Parses a `u128` from a hex string. +/// +/// Input string may or may not contain a `0x` prefix. +pub fn hex_u128 + Into>(s: S) -> Result { + let stripped = strip_hex_prefix(s.as_ref()); + u128::from_str_radix(stripped, 16).map_err(|error| ParseIntError { + input: s.into(), + bits: 128, + is_signed: false, + source: error, + }) +} + /// Strips the hex prefix off `s` if one is present. pub(crate) fn strip_hex_prefix(s: &str) -> &str { if let Some(stripped) = s.strip_prefix("0x") { @@ -201,4 +214,18 @@ mod tests { let got = hex_u32("ab").expect("failed to parse non-prefixed hex"); assert_eq!(got, want); } + + #[test] + fn parse_u128_from_hex_prefixed() { + let want = 3735928559; + let got = hex_u128("0xdeadbeef").expect("failed to parse prefixed hex"); + assert_eq!(got, want); + } + + #[test] + fn parse_u128_from_hex_no_prefix() { + let want = 3735928559; + let got = hex_u128("deadbeef").expect("failed to parse non-prefixed hex"); + assert_eq!(got, want); + } }