1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use peg::parser;

use serde::de::{Deserialize, Deserializer, Visitor};
use std::path::PathBuf;
use std::str;

#[derive(Debug, PartialEq)]
pub enum Action {
    Delete,
    Move { to: PathBuf },
}

parser! {
  grammar actions() for str {
    rule path() -> PathBuf
        = x:$(['a'..='z'|'A'..='Z'|'_'|'-'|'/'|'\\'|' ']+) { PathBuf::from(x) }

    rule delete() -> Action
        = "delete" { Action::Delete }

    rule move_to() -> Action
        = "move" " " p:path() { Action::Move { to: p } }

    pub rule action() -> Action
      = move_to() / delete()
  }
}

impl str::FromStr for Action {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(actions::action(s).unwrap())
    }
}

struct ActionVisitor;
impl<'de> Visitor<'de> for ActionVisitor {
    type Value = Action;

    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "a string containing at least 10 bytes")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(s.parse().unwrap())
    }
}

impl<'de> Deserialize<'de> for Action {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_str(ActionVisitor)
    }
}

#[test]
fn can_parse_delete() {
    assert_eq!("delete".parse::<Action>().unwrap(), Action::Delete,);
}

#[test]
fn can_parse_move_to() {
    assert_eq!(
        "move documents".parse::<Action>().unwrap(),
        Action::Move {
            to: PathBuf::from("documents")
        },
    );
}