macro_asm_builder/
utils.rs

1
2/// Tries to convert the string representation of a u128. If the input is
3/// negative, use two complement and tells is on the boolean return.
4pub fn format_string_into_number(s: &str) -> Option<(u128, bool)> {
5    if s.is_empty() {
6        None
7    } else if &s[0..1] == "-" {
8        match s.parse::<i128>() {
9            Ok(num) => {
10                let positive = -num;
11                let true_positive = positive as u128;
12                let not = !true_positive;
13                let cc2 = not + 1;
14                Some((cc2, true))
15            },
16            Err(_) => None,
17        }
18    } else if s.len() >= 3 {
19        if &s[0..2] == "0x" {
20            match u128::from_str_radix(&s[2..s.len()], 0x10) {
21                Ok(num) => Some((num, false)),
22                Err(_) => None,
23            }
24        } else {
25            match s.parse::<u128>() {
26                Ok(num) => Some((num, false)),
27                Err(_) => None,
28            }
29        }
30    } else {
31        match s.parse::<u128>() {
32            Ok(num) => Some((num, false)),
33            Err(_) => None,
34        }
35    }
36}
37
38#[test]
39fn test_format_string_into_number() {
40    assert_eq!(format_string_into_number("123"),       Some((123, false)));
41    assert_eq!(format_string_into_number("0x123"),     Some((0x123, false)));
42    assert_eq!(format_string_into_number("-123"),      Some((!123 + 1, true)));
43    assert_eq!(format_string_into_number("-0x123"),    None);
44    assert_eq!(format_string_into_number("abcd"),      None);
45    assert_eq!(format_string_into_number("0xabcd"),    Some((0xabcd, false)));
46    assert_eq!(format_string_into_number("0xabcdefg"), None);
47    assert_eq!(format_string_into_number(""),          None);
48    assert_eq!(format_string_into_number("12"),        Some((12, false)));
49    assert_eq!(format_string_into_number("xy"),        None);
50}