futilehdl/src/literals.rs

47 lines
1.1 KiB
Rust

use nom::{
bytes::complete::tag,
character::complete::{char, one_of},
combinator::{map_res, recognize},
multi::{many0, many1},
sequence::{preceded, terminated},
};
use crate::IResult;
pub fn decimal(input: &str) -> IResult<&str, u64> {
map_res(
recognize(many1(terminated(one_of("0123456789"), many0(char('_'))))),
|out: &str| out.parse::<u64>(),
)(input)
}
pub fn hexadecimal(input: &str) -> IResult<&str, u64> {
map_res(
preceded(
tag("h"),
recognize(many1(terminated(
one_of("0123456789abcdefABCDEF"),
many0(char('_')),
))),
),
|out: &str| u64::from_str_radix(&str::replace(&out, "_", ""), 16),
)(input)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dec() {
assert_eq!(decimal("123").unwrap().1, 123);
assert_eq!(decimal("0123").unwrap().1, 123);
}
#[test]
fn test_hex() {
assert_eq!(hexadecimal("hfF").unwrap().1, 0xff);
assert_eq!(hexadecimal("hF").unwrap().1, 0xf);
}
}