saferx-parser 0.1.0

Parse drug specifications.
Documentation
use std::fmt;

use nom::{
    branch::alt,
    bytes::complete::{tag, tag_no_case},
    character::complete::space0,
    number::complete::double,
    sequence::preceded,
    IResult, Parser,
};
use serde::{Deserialize, Serialize};

use crate::specification::common::format_value;

use super::common::multiply_with_space;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PatchUnitValue {
    pub value: f64,
    pub unit: String,
}

impl fmt::Display for PatchUnitValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}", format_value(self.value), self.unit)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Patch {
    pub length: PatchUnitValue,
    pub width: PatchUnitValue,
}

impl fmt::Display for Patch {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}*{}", self.length, self.width)
    }
}

pub fn patch_unit_value(input: &str) -> IResult<&str, PatchUnitValue> {
    let (input, (value, _, unit)) =
        (double, space0, alt((tag_no_case("mm"), tag_no_case("cm")))).parse(input)?;

    Ok((
        input,
        PatchUnitValue {
            value,
            unit: unit.to_string(),
        },
    ))
}

pub fn patch_without_parentheses(input: &str) -> IResult<&str, Patch> {
    let (input, (length, width)) = (
        patch_unit_value,
        preceded(multiply_with_space, patch_unit_value),
    )
        .parse(input)?;

    Ok((input, Patch { length, width }))
}

pub fn area_with_parentheses(input: &str) -> IResult<&str, Patch> {
    let (input, (_, _, patch, _, _)) = (
        alt((tag("("), tag("("))),
        space0,
        patch_without_parentheses,
        space0,
        alt((tag(")"), tag(")"))),
    )
        .parse(input)?;

    Ok((input, patch))
}

pub fn patch(input: &str) -> IResult<&str, Patch> {
    let (input, patch) = alt((area_with_parentheses, patch_without_parentheses)).parse(input)?;

    Ok((input, patch))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_patch_unit_value() {
        let test_cases = vec![
            (
                "10.5cm",
                PatchUnitValue {
                    value: 10.5,
                    unit: "cm".to_string(),
                },
            ),
            (
                "5.5 mm",
                PatchUnitValue {
                    value: 5.5,
                    unit: "mm".to_string(),
                },
            ),
        ];

        for (input, expected) in test_cases {
            assert_eq!(patch_unit_value(input).unwrap().1, expected);
        }

        let invalid_inputs = ["invalid", "10.5 km"];
        for input in invalid_inputs {
            assert!(patch_unit_value(input).is_err());
        }
    }

    #[test]
    fn test_patch_without_parentheses() {
        let test_cases = vec![
            (
                "10mm*5mm",
                Patch {
                    length: PatchUnitValue {
                        value: 10.0,
                        unit: "mm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
            (
                "1cm x 5cm",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "cm".to_string(),
                    },
                },
            ),
            (
                "1cm × 5mm",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
        ];

        for (input, expected) in test_cases {
            assert_eq!(patch_without_parentheses(input).unwrap().1, expected);
        }

        let invalid_inputs = ["invalid", "10.5cm", "10.5mm:", "*5mm"];
        for input in invalid_inputs {
            assert!(patch_without_parentheses(input).is_err());
        }
    }

    #[test]
    fn test_patch_with_parentheses() {
        let test_cases = vec![
            (
                "(10mm*5mm)",
                Patch {
                    length: PatchUnitValue {
                        value: 10.0,
                        unit: "mm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
            (
                "( 1cm x 5cm )",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "cm".to_string(),
                    },
                },
            ),
            (
                "(1cm × 5mm  )",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
        ];

        for (input, expected) in test_cases {
            assert_eq!(area_with_parentheses(input).unwrap().1, expected);
        }

        let invalid_inputs = ["(invalid)", "(10.5mm)", "(10.5mm:)", "(:5cm)", "10.5mmx5mm"];
        for input in invalid_inputs {
            assert!(area_with_parentheses(input).is_err());
        }
    }

    #[test]
    fn test_patch() {
        let test_cases = vec![
            (
                "10mm*5mm",
                Patch {
                    length: PatchUnitValue {
                        value: 10.0,
                        unit: "mm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
            (
                "1cm x 5cm",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "cm".to_string(),
                    },
                },
            ),
            (
                "1cm × 5mm",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
            (
                "(10mm*5mm)",
                Patch {
                    length: PatchUnitValue {
                        value: 10.0,
                        unit: "mm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
            (
                "( 1cm x 5cm )",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "cm".to_string(),
                    },
                },
            ),
            (
                "(1cm × 5mm  )",
                Patch {
                    length: PatchUnitValue {
                        value: 1.0,
                        unit: "cm".to_string(),
                    },
                    width: PatchUnitValue {
                        value: 5.0,
                        unit: "mm".to_string(),
                    },
                },
            ),
        ];

        for (input, expected) in test_cases {
            assert_eq!(patch(input).unwrap().1, expected);
        }

        let invalid_inputs = ["invalid", "10.5mm", "(10.5mmx1)"];
        for input in invalid_inputs {
            assert!(patch(input).is_err());
        }
    }
}