lib_rv32_common/
util.rs

1/// Parse an integer from a string slice. If it leads with `0x` or `0X`, it
2/// will be parsed as base 16, otherwise it will be parsed as base 10.
3#[macro_export]
4macro_rules! parse_int {
5    ($t:ty,$s:expr) => {{
6        if !$s.to_ascii_lowercase().starts_with("0x") {
7            $s.parse()
8        } else {
9            <$t>::from_str_radix(&$s[2..], 16)
10        }
11    }};
12}
13
14#[cfg(test)]
15mod tests {
16    use crate::parse_int;
17
18    #[test]
19    fn test_parse_int() {
20        assert_eq!(17, parse_int!(u32, "17").unwrap());
21        assert_eq!(17, parse_int!(u32, "017").unwrap());
22        assert_eq!(17, parse_int!(i32, "17").unwrap());
23
24        assert_eq!(-21, parse_int!(i32, "-21").unwrap());
25
26        assert_eq!(0x16, parse_int!(u32, "0x16").unwrap());
27        assert_eq!(0x16, parse_int!(u32, "0x0016").unwrap());
28    }
29}