scanner.rs 8.8 KB
Newer Older
P
Phodal Huang 已提交
1
use onig::Regex;
P
Phodal Huang 已提交
2
use unicode_segmentation::UnicodeSegmentation;
P
Phodal Huang 已提交
3

P
Phodal Huang 已提交
4
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
5
pub struct IOnigCaptureIndex {
P
Phodal Huang 已提交
6 7 8
    pub start: usize,
    pub end: usize,
    pub length: usize,
P
Phodal Huang 已提交
9 10
}

P
Phodal Huang 已提交
11
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
12
pub struct IOnigMatch {
P
Phodal Huang 已提交
13
    pub index: usize,
P
Phodal Huang 已提交
14 15 16
    pub capture_indices: Vec<IOnigCaptureIndex>,
}

P
Phodal Huang 已提交
17
#[derive(Debug, Clone, Serialize)]
P
Phodal Huang 已提交
18
pub struct Scanner {
P
Phodal Huang 已提交
19
    pub index: usize,
P
Phodal Huang 已提交
20 21 22 23 24
    pub patterns: Vec<String>,
}

impl Scanner {
    pub fn new(patterns: Vec<String>) -> Self {
P
Phodal Huang 已提交
25
        Scanner { index: 0, patterns }
P
Phodal Huang 已提交
26 27
    }

P
Phodal Huang 已提交
28 29 30 31
    pub fn dispose(&mut self) {
        self.index = 0
    }

P
Phodal Huang 已提交
32 33 34 35 36
    pub fn find_next_match_sync(
        &mut self,
        origin_str: String,
        start_position: i32,
    ) -> Option<IOnigMatch> {
P
Phodal Huang 已提交
37
        if self.index >= self.patterns.clone().len() {
P
Phodal Huang 已提交
38
            self.index = 0;
39 40 41
            return None;
        }

P
Phodal Huang 已提交
42
        let mut after_pos_str = String::from("");
43
        let mut start_pos = start_position;
P
Phodal Huang 已提交
44
        let string_vec = origin_str.graphemes(true).collect::<Vec<&str>>();
45

P
Phodal Huang 已提交
46
        if start_pos > string_vec.len() as i32 {
47 48
            return None;
        }
P
Phodal Huang 已提交
49

P
Phodal Huang 已提交
50
        if start_pos < 0 {
51
            start_pos = 0
P
Phodal Huang 已提交
52
        }
P
Phodal Huang 已提交
53

P
Phodal Huang 已提交
54 55 56 57 58
        let before_vec = string_vec[..start_pos as usize].to_owned();
        let after_vec = string_vec[start_pos as usize..].to_owned();

        for x in after_vec {
            after_pos_str = after_pos_str + x
P
Phodal Huang 已提交
59 60
        }

P
Phodal Huang 已提交
61 62 63 64
        let pattern = self.patterns[self.index].clone();

        let regex = Regex::new(pattern.as_str()).unwrap();
        let mut capture_indices = vec![];
P
Phodal Huang 已提交
65
        let _captures = regex.captures(after_pos_str.as_str());
P
Phodal Huang 已提交
66

P
Phodal Huang 已提交
67 68 69
        if let Some(captures) = _captures {
            for (_, pos) in captures.iter_pos().enumerate() {
                if let Some((start, end)) = pos {
P
Phodal Huang 已提交
70
                    let length = end - start;
71 72 73 74 75 76 77 78
                    let x1 = after_pos_str.split_at(end).0;
                    let utf8_end =
                        before_vec.len() + x1.graphemes(true).collect::<Vec<&str>>().len();
                    let utf8_start = utf8_end - length;

                    let capture = IOnigCaptureIndex {
                        start: utf8_start,
                        end: utf8_end,
P
Phodal Huang 已提交
79
                        length,
P
Phodal Huang 已提交
80
                    };
P
Phodal Huang 已提交
81

P
Phodal Huang 已提交
82
                    capture_indices.push(capture)
P
Phodal Huang 已提交
83
                }
P
Phodal Huang 已提交
84
            }
P
Phodal Huang 已提交
85
        }
P
Phodal Huang 已提交
86

P
Phodal Huang 已提交
87
        if capture_indices.len() <= 0 {
P
Phodal Huang 已提交
88
            self.index = self.index + 1;
89
            self.find_next_match_sync(origin_str.clone(), start_pos)
P
Phodal Huang 已提交
90 91
        } else {
            let index = self.index.clone();
P
Phodal Huang 已提交
92
            self.index = 0;
P
Phodal Huang 已提交
93 94 95 96
            Some(IOnigMatch {
                index,
                capture_indices,
            })
P
Phodal Huang 已提交
97
        }
P
Phodal Huang 已提交
98 99 100 101 102
    }
}

#[cfg(test)]
mod tests {
P
Phodal Huang 已提交
103
    use crate::scanner::scanner::Scanner;
P
Phodal Huang 已提交
104 105 106 107

    #[test]
    fn should_handle_simple_regex() {
        let regex = vec![String::from("ell"), String::from("wo")];
P
Phodal Huang 已提交
108 109
        let mut scanner = Scanner::new(regex);
        let s = String::from("Hello world!");
P
Phodal Huang 已提交
110
        let result = scanner.find_next_match_sync(s.clone(), 0).unwrap();
P
Phodal Huang 已提交
111 112 113 114
        assert_eq!(result.index, 0);
        assert_eq!(result.capture_indices[0].start, 1);
        assert_eq!(result.capture_indices[0].end, 4);

P
Phodal Huang 已提交
115
        let second_result = scanner.find_next_match_sync(s, 2).unwrap();
P
Phodal Huang 已提交
116 117 118
        assert_eq!(second_result.index, 1);
        assert_eq!(second_result.capture_indices[0].start, 6);
        assert_eq!(second_result.capture_indices[0].end, 8);
P
Phodal Huang 已提交
119
    }
P
Phodal Huang 已提交
120 121 122 123 124 125

    #[test]
    fn should_handle_simple2() {
        let regex = vec![String::from("a"), String::from("b"), String::from("c")];
        let mut scanner = Scanner::new(regex);

P
Phodal Huang 已提交
126 127 128 129 130
        if let None = scanner.find_next_match_sync(String::from("x"), 0) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
131

P
Phodal Huang 已提交
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
        let result = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 0)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
                "{\"index\":0,\"capture_indices\":[{\"start\":2,\"end\":3,\"length\":1}]}"
            )
        );

        let result2 = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 4)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
                "{\"index\":1,\"capture_indices\":[{\"start\":5,\"end\":6,\"length\":1}]}"
            )
        );

        let result3 = scanner
            .find_next_match_sync(String::from("xxaxxbxxc"), 7)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result3).unwrap(),
            String::from(
                "{\"index\":2,\"capture_indices\":[{\"start\":8,\"end\":9,\"length\":1}]}"
            )
        );
P
Phodal Huang 已提交
161 162 163 164 165 166

        if let None = scanner.find_next_match_sync(String::from("xxaxxbxxc"), 9) {
            assert_eq!(true, true);
        } else {
            assert_eq!(true, false);
        }
P
Phodal Huang 已提交
167
    }
P
Phodal Huang 已提交
168 169 170 171 172 173

    #[test]
    fn should_handle_unicode1() {
        let regex = vec![String::from("1"), String::from("2")];
        let mut scanner = Scanner::new(regex);

P
Phodal Huang 已提交
174 175 176 177 178 179
        let result = scanner
            .find_next_match_sync(String::from("ab…cde21"), 5)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
180
                "{\"index\":0,\"capture_indices\":[{\"start\":7,\"end\":8,\"length\":1}]}"
P
Phodal Huang 已提交
181 182
            )
        );
P
Phodal Huang 已提交
183 184 185 186 187
    }

    #[test]
    fn should_handle_unicode2() {
        let mut scanner2 = Scanner::new(vec![String::from("\"")]);
P
Phodal Huang 已提交
188 189 190 191 192 193
        let result2 = scanner2
            .find_next_match_sync(String::from("{\"\": 1}"), 1)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
194
                "{\"index\":0,\"capture_indices\":[{\"start\":1,\"end\":2,\"length\":1}]}"
P
Phodal Huang 已提交
195 196
            )
        );
P
Phodal Huang 已提交
197
    }
P
Phodal Huang 已提交
198

199 200 201 202
    #[test]
    fn should_handle_unicode3() {
        let regex = vec![String::from("Y"), String::from("X")];
        let mut scanner = Scanner::new(regex);
P
Phodal Huang 已提交
203 204 205 206 207 208
        let result = scanner
            .find_next_match_sync(String::from("a💻bYX"), 0)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
209
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
210 211 212 213 214 215 216 217 218
            )
        );

        let result1 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 1)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result1).unwrap(),
            String::from(
219
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
220 221 222 223 224 225 226 227 228
            )
        );

        let result2 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 2)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
229
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
230 231 232 233 234 235 236 237 238
            )
        );

        let result3 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 3)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result3).unwrap(),
            String::from(
239
                "{\"index\":0,\"capture_indices\":[{\"start\":3,\"end\":4,\"length\":1}]}"
P
Phodal Huang 已提交
240 241 242 243 244 245 246 247 248
            )
        );

        let result4 = scanner
            .find_next_match_sync(String::from("a💻bYX"), 4)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result4).unwrap(),
            String::from(
249
                "{\"index\":1,\"capture_indices\":[{\"start\":4,\"end\":5,\"length\":1}]}"
P
Phodal Huang 已提交
250 251
            )
        );
252 253
    }

254 255 256
    #[test]
    fn should_out_of_bounds() {
        let mut scanner = Scanner::new(vec![String::from("X")]);
P
Phodal Huang 已提交
257 258 259 260 261 262
        let result = scanner
            .find_next_match_sync(String::from("X💻X"), -10000)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            String::from(
263
                "{\"index\":0,\"capture_indices\":[{\"start\":0,\"end\":1,\"length\":1}]}"
P
Phodal Huang 已提交
264 265
            )
        );
266

267 268 269 270 271 272 273 274
        let result2 = scanner.find_next_match_sync(String::from("X💻X"), 10000);
        assert_eq!(format!("{:?}", result2), "None");
    }

    #[test]
    fn should_handle_regex_g() {
        let mut scanner = Scanner::new(vec![String::from("\\G-and")]);
        let result = scanner.find_next_match_sync(String::from("first-and-second"), 0);
275
        assert_eq!(format!("{:?}", result), "None");
276

P
Phodal Huang 已提交
277 278 279 280 281 282 283 284 285
        let result2 = scanner
            .find_next_match_sync(String::from("first-and-second"), 5)
            .unwrap();
        assert_eq!(
            serde_json::to_string(&result2).unwrap(),
            String::from(
                "{\"index\":0,\"capture_indices\":[{\"start\":5,\"end\":9,\"length\":4}]}"
            )
        );
286
    }
P
Phodal Huang 已提交
287
}