Skip to main content

korrektor_utils/
lib.rs

1/// Crate that holds utility functions needed
2/// for korrektor.
3use pcre::MatchIterator;
4
5/// Replaces constants represented as a tuple array. Each first
6/// element of the tuple replaces each second element
7/// with the help of the regex crate.
8pub fn replace_pairs(input: &str, constant: &[(&str, &str)]) -> String {
9    let mut input = input.to_string();
10
11    for (pattern, replacement) in constant {
12        let re = regex::Regex::new(pattern).unwrap();
13        input = re.replace_all(&input, *replacement).as_ref().to_string();
14    }
15
16    input
17}
18
19/// Wrap all matches in the given text with
20/// provided pattern that must be a valid regex.
21///
22/// # Panics
23/// Supplied an invalid regex that can not be compiled by pcre crate
24pub fn wrap_regex(text: &str, pattern: &str) -> String {
25    let mut re = pcre::Pcre::compile(pattern).unwrap();
26    let matches = re.matches(text);
27
28    wrap_matches(text, matches)
29}
30
31/// Wraps all regex matches of pcre crate
32/// in 〈〉 brackets in order to preserve some
33/// text from some operations in korrektor.
34pub fn wrap_matches(text: &str, matches: MatchIterator) -> String{
35    let mut result = text.to_string();
36
37    for m in matches {
38        let captured = String::from(m.group(0));
39        let replacement = String::from("〈") + &*captured + "〉";
40        result = result.replace(&captured, &replacement);
41    }
42
43    result
44}
45
46/// Removes all brackets that wrap special text
47/// protected from korrektor operations.
48pub fn unwrap_text(text: &str) -> String {
49    let re = regex::Regex::new("[〈〉]").unwrap();
50
51    re.replace_all(text, "").to_string()
52}
53
54#[cfg(test)]
55mod as_tests {
56    use super::*;
57
58    #[test]
59    fn unwrap_text_test() {
60        let input = "@ki-d @ki- 〈@hello〉 〈〈nyan@mail.uz〉〉 〈〈nya@mail.uz〉〉 〈https://nyan.com〉 go'zal 〈@crystalny〉";
61        let expected = "@ki-d @ki- @hello nyan@mail.uz nya@mail.uz https://nyan.com go'zal @crystalny";
62
63        assert_eq!(unwrap_text(input), expected.to_string());
64    }
65
66    #[test]
67    fn wrap_regex_test() {
68        let input = "@ki-d @ki- @hello nyan@mail.uz nya@mail.uz https://nyan.com go'zal @crystalny";
69        let pattern = r"([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)|@(?!.*\-|.*\-$)[a-zA-Z0-9][\w-]+[a-zA-Z0-9]{0,39}";
70        let expected = "@ki-d @ki- 〈@hello〉 〈nyan@mail.uz〉 〈nya@mail.uz〉 https://nyan.com go'zal 〈@crystalny〉";
71
72        assert_eq!(wrap_regex(input, pattern), expected.to_string());
73
74        let input = "@ki-d https://nyan.com go'zal @crystalny";
75        let pattern = "(?i)\\b(?:(?:https?|ftp|file|ssh):\\/\\/|www\\.|ftp\\.)[-A-Z0-9+&@#\\/%=~_|$?!:,.]*[A-Z0-9+&@#\\/%=~_|$]";
76        let expected = "@ki-d 〈https://nyan.com〉 go'zal @crystalny";
77
78        assert_eq!(wrap_regex(input, pattern), expected.to_string());
79    }
80}