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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use config::{any_err, get_or_create_sub_module};
use mlua::prelude::LuaUserData;
use mlua::{FromLua, Lua, MetaMethod, UserDataMethods};
use mod_memoize::CacheValue;
use regex::{RegexSet, RegexSetBuilder};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Clone, Serialize, Deserialize)]
#[serde(try_from = "RegexSetMapBuilder<V>", into = "RegexSetMapBuilder<V>")]
pub struct RegexSetMap<V: Clone> {
    set: RegexSet,
    pattern_to_value: Vec<V>,
}

impl<V: Clone> RegexSetMap<V> {
    pub fn lookup(&self, subject: &str) -> Option<&V> {
        self.set
            .matches(subject)
            .into_iter()
            .next()
            .and_then(|idx| self.pattern_to_value.get(idx))
    }
}

impl<V: Clone> From<RegexSetMap<V>> for RegexSetMapBuilder<V> {
    fn from(map: RegexSetMap<V>) -> Self {
        let patterns = map.set.patterns().to_vec();
        RegexSetMapBuilder {
            patterns,
            pattern_to_value: map.pattern_to_value,
        }
    }
}

impl<V: Clone> TryFrom<RegexSetMapBuilder<V>> for RegexSetMap<V> {
    type Error = String;

    fn try_from(builder: RegexSetMapBuilder<V>) -> Result<RegexSetMap<V>, String> {
        builder.build()
    }
}

#[derive(Serialize, Deserialize)]
pub struct RegexSetMapBuilder<V: Clone> {
    patterns: Vec<String>,
    pattern_to_value: Vec<V>,
}

impl<V: Clone> RegexSetMapBuilder<V> {
    pub fn new() -> Self {
        Self {
            patterns: vec![],
            pattern_to_value: vec![],
        }
    }

    pub fn add_rule<S: Into<String>>(&mut self, rule: S, value: V) {
        self.patterns.push(rule.into());
        self.pattern_to_value.push(value);
    }

    pub fn build(mut self) -> Result<RegexSetMap<V>, String> {
        self.patterns.shrink_to_fit();
        self.pattern_to_value.shrink_to_fit();

        let set = RegexSetBuilder::new(self.patterns)
            .build()
            .map_err(|err| format!("compiling rules: {err:#}"))?;
        Ok(RegexSetMap {
            set,
            pattern_to_value: self.pattern_to_value,
        })
    }
}

impl LuaUserData for RegexSetMap<CacheValue> {
    fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
        mod_memoize::Memoized::impl_memoize(methods);
        methods.add_meta_method(MetaMethod::Index, |lua, this, key: String| {
            if let Some(value) = this.lookup(&key) {
                let value = value.as_lua(lua)?;
                Ok(Some(value))
            } else {
                Ok(None)
            }
        });
    }
}

pub fn register(lua: &Lua) -> anyhow::Result<()> {
    let module = get_or_create_sub_module(lua, "regex_set_map")?;

    module.set(
        "new",
        lua.create_function(|lua, value: Option<HashMap<String, mlua::Value>>| {
            let mut builder: RegexSetMapBuilder<CacheValue> = RegexSetMapBuilder::new();

            if let Some(value) = value {
                for (k, v) in value {
                    let v = CacheValue::from_lua(v, lua)?;
                    builder.add_rule(&k, v);
                }
            }

            builder.build().map_err(any_err)
        })?,
    )?;

    Ok(())
}

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

    #[test]
    fn test_basic_mapping() {
        let mut builder = RegexSetMapBuilder::new();
        builder.add_rule(
            "4\\.2\\.2 The email account that you tried to reach is over quota\\.",
            500,
        );
        builder.add_rule("4\\.2\\.1 <.+>: Recipient address rejected: this mailbox is inactive and has been disabled", 501);
        builder.add_rule("4\\.1\\.1 <.*> 4.2.2 mailbox full\\.", 502);
        let mapper = builder.build().unwrap();

        let corpus = &[
            ("400 4.2.2 The email account that you tried to reach is over quota", None),
            ("400 4.2.2 The email account that you tried to reach is over quota.", Some(500)),
            ("400 4.2.1 <foo>: Recipient address rejected: this mailbox is inactive and has been disabled", Some(501)),
            ("400 4.1.1 <bar> 4.2.2 mailbox full.", Some(502)),
        ];

        for &(input, output) in corpus {
            assert_eq!(
                mapper.lookup(input),
                output.as_ref(),
                "expected {input} -> {output:?}"
            );
        }
    }
}