units: Introduce public hex_u128 function

Introduce a function for parsing a `u128` from hex. Support strings with
and without a `0x` prefix as we do for `hex_u32`.
This commit is contained in:
Tobin C. Harding 2024-04-02 09:51:40 +11:00
parent 9705d51782
commit d33625f6e2
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 27 additions and 0 deletions

View File

@ -101,6 +101,19 @@ pub fn hex_u32<S: AsRef<str> + Into<String>>(s: S) -> Result<u32, ParseIntError>
}) })
} }
/// Parses a `u128` from a hex string.
///
/// Input string may or may not contain a `0x` prefix.
pub fn hex_u128<S: AsRef<str> + Into<String>>(s: S) -> Result<u128, ParseIntError> {
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. /// Strips the hex prefix off `s` if one is present.
pub(crate) fn strip_hex_prefix(s: &str) -> &str { pub(crate) fn strip_hex_prefix(s: &str) -> &str {
if let Some(stripped) = s.strip_prefix("0x") { 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"); let got = hex_u32("ab").expect("failed to parse non-prefixed hex");
assert_eq!(got, want); 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);
}
} }