mod_regex/
lib.rs

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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use config::{any_err, get_or_create_sub_module};
use fancy_regex::{Matches, Regex};
use mlua::{Lua, UserData, UserDataMethods};

struct RegexWrap(Regex);

impl UserData for RegexWrap {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_method("captures", |lua, this, haystack: String| {
            match this.0.captures(&haystack).map_err(any_err)? {
                Some(c) => {
                    let result = lua.create_table()?;

                    let names = this.0.capture_names();
                    for ((idx, cap), name) in c.iter().enumerate().zip(names) {
                        if let Some(cap) = cap {
                            let s = cap.as_str();
                            result.set(idx, s.to_string())?;
                            if let Some(name) = name {
                                result.set(name, s.to_string())?;
                            }
                        }
                    }

                    Ok(Some(result))
                }
                None => Ok(None),
            }
        });

        methods.add_method("is_match", |_, this, haystack: String| {
            Ok(this.0.is_match(&haystack).map_err(any_err)?)
        });

        methods.add_method("find", |_, this, haystack: String| {
            Ok(this
                .0
                .find(&haystack)
                .map_err(any_err)?
                .map(|m| m.as_str().to_string()))
        });

        methods.add_method("find_all", |_, this, haystack: String| {
            let mut result = vec![];

            for m in this.0.find_iter(&haystack) {
                let s = m.map_err(any_err)?;
                result.push(s.as_str().to_string());
            }
            Ok(result)
        });

        methods.add_method("replace", |_, this, (haystack, rep): (String, String)| {
            Ok(this.0.replace(&haystack, &rep).to_string())
        });

        methods.add_method(
            "replace_all",
            |_, this, (haystack, rep): (String, String)| {
                Ok(this
                    .0
                    .try_replacen(&haystack, 0, &rep)
                    .map_err(any_err)?
                    .to_string())
            },
        );

        methods.add_method(
            "replacen",
            |_, this, (haystack, limit, rep): (String, usize, String)| {
                Ok(this
                    .0
                    .try_replacen(&haystack, limit, &rep)
                    .map_err(any_err)?
                    .to_string())
            },
        );

        methods.add_method("split", |_, this, haystack: String| {
            Ok(split_into_vec(&this.0, &haystack).map_err(any_err)?)
        });
    }
}

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

    regex_mod.set(
        "compile",
        lua.create_function(move |_, pattern: String| {
            let re = Regex::new(&pattern).map_err(any_err)?;
            Ok(RegexWrap(re))
        })?,
    )?;

    regex_mod.set(
        "escape",
        lua.create_function(move |_, pattern: String| Ok(regex::escape(&pattern)))?,
    )?;

    Ok(())
}

struct Split<'r, 'h> {
    finder: Matches<'r, 'h>,
    last: usize,
    haystack: &'h str,
}

impl<'r, 'h> Split<'r, 'h> {
    fn split(re: &'r Regex, haystack: &'h str) -> Self {
        Self {
            finder: re.find_iter(haystack),
            last: 0,
            haystack,
        }
    }
}

impl<'r, 'h> Iterator for Split<'r, 'h> {
    type Item = Result<&'h str, fancy_regex::Error>;

    fn next(&mut self) -> Option<Result<&'h str, fancy_regex::Error>> {
        match self.finder.next() {
            None => {
                let len = self.haystack.len();
                if self.last > len {
                    None
                } else {
                    let span = &self.haystack[self.last..len];
                    self.last = len + 1; // Next call will return None
                    Some(Ok(span))
                }
            }
            Some(Ok(m)) => {
                let span = &self.haystack[self.last..m.start()];
                self.last = m.end();
                Some(Ok(span))
            }
            Some(Err(e)) => Some(Err(e)),
        }
    }
}

fn split_into_vec(re: &Regex, haystack: &str) -> Result<Vec<String>, fancy_regex::Error> {
    let mut result = vec![];
    for m in Split::split(re, haystack) {
        let m = m?;
        result.push(m.to_string());
    }
    Ok(result)
}

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

    #[test]
    fn fancy_split() {
        let re = Regex::new("[ \t]+").unwrap();
        let hay = "a b \t  c\td    e";
        let fields = split_into_vec(&re, hay).unwrap();
        assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
    }
}