Skip to main content

castep_model_core/parser/
mod.rs

1use nom::{
2    branch::alt,
3    character::complete::{char, one_of},
4    combinator::{opt, recognize},
5    multi::many1,
6    sequence::{preceded, tuple},
7    IResult,
8};
9
10pub mod msi_parser;
11
12pub fn decimal(input: &str) -> IResult<&str, &str> {
13    recognize(many1(one_of("0123456789")))(input)
14}
15pub fn float(input: &str) -> IResult<&str, &str> {
16    alt((
17        // Case one: .42
18        recognize(tuple((
19            char('.'),
20            decimal,
21            opt(tuple((one_of("eE"), opt(one_of("+-")), decimal))),
22        ))), // Case two: 42e42 and 42.42e42
23        recognize(tuple((
24            decimal,
25            opt(preceded(char('.'), decimal)),
26            one_of("eE"),
27            opt(one_of("+-")),
28            decimal,
29        ))), // Case three: 42. and 42.42
30        // Case four: 42., +42., 42.42, and -42.e-05
31        recognize(tuple((
32            opt(one_of("+-")),
33            decimal,
34            char('.'),
35            opt(decimal),
36            opt(one_of("eE")),
37            opt(one_of("+-")),
38            opt(decimal),
39        ))),
40    ))(input)
41}
42
43#[test]
44fn test_float() {
45    let number = "-2.865153883599e-05";
46    let number_2 = "-2.";
47    let parse_float = float(number);
48    match parse_float {
49        Ok((_, num)) => println!("{num}"),
50        Err(e) => println!("{e}"),
51    }
52    let parse_float_2 = float(number_2);
53    match parse_float_2 {
54        Ok((_, num)) => println!("{num}"),
55        Err(e) => println!("{e}"),
56    }
57}