From d33625f6e2d4986c4e8116016a8b4530d374f2c9 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 2 Apr 2024 09:51:40 +1100 Subject: [PATCH] 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`. --- units/src/parse.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) 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); + } }