|
| 1 | +use regex::Regex; |
| 2 | +use std::error::Error; |
| 3 | + |
| 4 | +#[derive(Debug, PartialEq)] |
| 5 | +pub struct Order { |
| 6 | + pub qty: u32, |
| 7 | + pub product: String, |
| 8 | + pub source: String, |
| 9 | +} |
| 10 | + |
| 11 | +impl Order { |
| 12 | + pub fn new<S: Into<String>>(qty: u32, product: S, source: S) -> Self { |
| 13 | + Self { |
| 14 | + qty, |
| 15 | + product: product.into(), |
| 16 | + source: source.into(), |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + pub fn parse<S: Into<String>>(command: S) -> Result<Self, Box<dyn Error>> { |
| 21 | + // Grammar Representationconst |
| 22 | + let optional_space = " ?"; |
| 23 | + let qty = String::from("x(?P<qty>\\d+)") + optional_space; |
| 24 | + let product = String::from("'(?P<product>[\\w ]+)'") + optional_space; |
| 25 | + let source = "from (?P<source>\\w+)"; |
| 26 | + let order_command = |
| 27 | + String::from("order") + optional_space + qty.as_str() + product.as_str() + source; |
| 28 | + |
| 29 | + let re = Regex::new(&order_command)?; |
| 30 | + let command = command.into(); |
| 31 | + let x = re.captures(command.as_ref()).ok_or("Bad command")?; |
| 32 | + |
| 33 | + Ok(Self { |
| 34 | + product: x |
| 35 | + .name("product") |
| 36 | + .ok_or("Product not defined")? |
| 37 | + .as_str() |
| 38 | + .to_string(), |
| 39 | + qty: x.name("qty").ok_or("Qty not defined")?.as_str().parse()?, |
| 40 | + source: x |
| 41 | + .name("source") |
| 42 | + .ok_or("Source not defined")? |
| 43 | + .as_str() |
| 44 | + .to_string(), |
| 45 | + }) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Default for Order { |
| 50 | + fn default() -> Self { |
| 51 | + Self::new(1, "Ice cream", "Five") |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +mod tests { |
| 57 | + use super::Order; |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_1() { |
| 61 | + let order = Order::new(12, "1L milk packs", "Macro"); |
| 62 | + let command = "order x12 '1L milk packs' from Macro"; |
| 63 | + assert_eq!(order, Order::parse(command).unwrap()); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_2() { |
| 68 | + let order = Order::new(1, "a bag of potatoes", "Tesco"); |
| 69 | + let command = "order x1 'a bag of potatoes' from Tesco"; |
| 70 | + assert_eq!(order, Order::parse(command).unwrap()); |
| 71 | + } |
| 72 | +} |
0 commit comments