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.len() == 0 {
6        None
7    } else {
8        if &s[0..1] == "-" {
9            match i128::from_str_radix(s, 10) {
10                Ok(num) => {
11                    let positive = num * -1;
12                    let true_positive = positive as u128;
13                    let not = !true_positive;
14                    let cc2 = not + 1;
15                    Some((cc2, true))
16                },
17                Err(_) => None,
18            }
19        } else {
20            if s.len() >= 3 {
21                if &s[0..2] == "0x" {
22                    match u128::from_str_radix(&s[2..s.len()], 0x10) {
23                        Ok(num) => Some((num, false)),
24                        Err(_) => None,
25                    }
26                } else {
27                    match u128::from_str_radix(s, 10) {
28                        Ok(num) => Some((num, false)),
29                        Err(_) => None,
30                    }
31                }
32            } else {
33                match u128::from_str_radix(s, 10) {
34                    Ok(num) => Some((num, false)),
35                    Err(_) => None,
36                }
37            }
38        }
39    }
40}
41
42#[test]
43fn test_format_string_into_number() {
44    assert_eq!(format_string_into_number("123"),       Some((123, false)));
45    assert_eq!(format_string_into_number("0x123"),     Some((0x123, false)));
46    assert_eq!(format_string_into_number("-123"),      Some((!123 + 1, true)));
47    assert_eq!(format_string_into_number("-0x123"),    None);
48    assert_eq!(format_string_into_number("abcd"),      None);
49    assert_eq!(format_string_into_number("0xabcd"),    Some((0xabcd, false)));
50    assert_eq!(format_string_into_number("0xabcdefg"), None);
51    assert_eq!(format_string_into_number(""),          None);
52    assert_eq!(format_string_into_number("12"),        Some((12, false)));
53    assert_eq!(format_string_into_number("xy"),        None);
54}