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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#[macro_use]
extern crate lazy_static;

use regex::{Regex, RegexBuilder};
use voca_rs::case;

fn restore_case(origin: &str, to_restore: &str) -> String {
    if origin == to_restore {
        to_restore.to_string()
    } else if origin == case::lower_case(origin) {
        case::lower_case(to_restore)
    } else if origin == case::upper_case(origin) {
        case::upper_case(to_restore)
    } else if origin == case::upper_first(origin) {
        case::upper_first(to_restore)
    } else if origin == case::camel_case(origin) {
        case::camel_case(to_restore)
    } else {
        case::lower_case(to_restore)
    }
}

macro_rules! load_config_map {
    ($filename:expr) => {
        include_str!($filename)
            .split('\n')
            .filter(|it| it.trim() != "")
            .map(|it| {
                let mut splitted = it
                    .split('=')
                    .map(|it| it.trim().trim_matches(|ch| ch == '\"'));
                (splitted.next().unwrap(), splitted.next().unwrap())
            })
            .map(|(k, v)| {
                (
                    RegexBuilder::new(k).case_insensitive(true).build().unwrap(),
                    v.to_string(),
                )
            })
            .rev()
            .collect()
    };
}

lazy_static! {
    static ref IRREGULAR: Vec<(&'static str, &'static str)> =
        include_str!("../rules/irregular.txt")
            .split('\n')
            .filter(|it| it.trim() != "")
            .map(|it| {
                let mut splitted = it
                    .split('=')
                    .map(|it| it.trim().trim_matches(|ch| ch == '\"'));
                (splitted.next().unwrap(), splitted.next().unwrap())
            })
            .collect();
    static ref PLURAL_RULES: Vec<(Regex, String)> = load_config_map!("../rules/plural.txt");
    static ref SINGLAR_RULES: Vec<(Regex, String)> = load_config_map!("../rules/singular.txt");
    static ref UNCOUNTABLE: Vec<Regex> = include_str!("../rules/uncountable.txt")
        .split('\n')
        .filter(|it| it.trim() != "")
        .map(|it| RegexBuilder::new(it)
            .case_insensitive(true)
            .build()
            .unwrap())
        .collect();
}

/// Returns whether a noun is uncountable
///
/// # Arguments
///
/// * `word` - The noun
///
/// # Examples
///
/// ```
/// use pluralize_rs::is_uncountable;
/// assert!(is_uncountable("water"));
/// ```
pub fn is_uncountable(word: &str) -> bool {
    let lower_case = case::lower_case(word);
    for (singular, plural) in IRREGULAR.iter() {
        if lower_case == *singular || lower_case == *plural {
            return false;
        }
    }
    for r in UNCOUNTABLE.iter() {
        if r.find(&lower_case).is_some() {
            return true;
        }
    }
    false
}

fn replace_with_rules(
    word: &str,
    mut rules: impl Iterator<Item=&'static (Regex, String)>,
) -> String {
    if let Some((m, mut r)) = rules
        .find_map(|(re, replace_to)| re.captures(&word).map(move |it| (it, replace_to.clone())))
    {
        if r == "$0" {
            return word.to_string();
        }
        let mut result = word[0..m.get(0).unwrap().start()].to_string();
        for (i, content) in ["$1", "$2"].iter().enumerate() {
            r = if let Some(replace_to) = m.get(i + 1).map(|it| &word[it.start()..it.end()]) {
                r.replace(content, replace_to)
            } else {
                r.replace(content, "")
            }
        }
        result.push_str(&r);
        result
    } else {
        word.to_string()
    }
}

/// Returns a noun's plural form, if it is uncountable, the origin value will be returned
///
/// # Arguments
///
/// * `word` - The noun
///
/// # Examples
///
/// ```
/// use pluralize_rs::to_plural;
/// assert_eq!(to_plural("word"), "words");
/// ```
pub fn to_plural(word: &str) -> String {
    if is_uncountable(word) {
        word.to_string()
    } else {
        let lower_case = case::lower_case(word);
        for (singular, plural) in IRREGULAR.iter() {
            if lower_case == *singular {
                return restore_case(word, plural);
            }
        }
        restore_case(word, &replace_with_rules(&word, PLURAL_RULES.iter()))
    }
}

/// Returns wheter the noun is plural, if it is uncountable, will return true
///
/// # Arguments
///
/// * `word` - The noun
///
/// # Examples
///
/// ```
/// use pluralize_rs::is_plural;
/// assert!(is_plural("words"));
/// assert!(!is_plural("word"));
/// ```
pub fn is_plural(word: &str) -> bool {
    if is_uncountable(word) {
        false
    } else {
        let lower_case = case::lower_case(word);
        for (singular, plural) in IRREGULAR.iter() {
            if lower_case == *singular {
                return false;
            } else if lower_case == *plural {
                return true;
            }
        }
        lower_case == replace_with_rules(&lower_case, PLURAL_RULES.iter())
    }
}

/// Returns a noun's singular form, if it is uncountable, the origin value will be returned
///
/// # Arguments
///
/// * `word` - The noun
///
/// # Examples
///
/// ```
/// use pluralize_rs::to_singular;
/// assert_eq!(to_singular("words"), "word");
/// ```
pub fn to_singular(word: &str) -> String {
    if is_uncountable(word) {
        word.to_string()
    } else {
        let lower_case = case::lower_case(word);
        for (singular, plural) in IRREGULAR.iter() {
            if lower_case == *plural {
                return restore_case(word, singular);
            }
        }
        restore_case(word, &replace_with_rules(&word, SINGLAR_RULES.iter()))
    }
}

/// Returns wheter the noun is singular, if it is uncountable, will return true
///
/// # Arguments
///
/// * `word` - The noun
///
/// # Examples
///
/// ```
/// use pluralize_rs::is_singular;
/// assert!(!is_singular("words"));
/// assert!(is_singular("word"));
/// ```
pub fn is_singular(word: &str) -> bool {
    if is_uncountable(word) {
        false
    } else {
        let lower_case = case::lower_case(word);
        for (singular, plural) in IRREGULAR.iter() {
            if lower_case == *plural {
                return false;
            } else if lower_case == *singular {
                return true;
            }
        }
        lower_case == replace_with_rules(&lower_case, SINGLAR_RULES.iter())
    }
}

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

    #[test]
    fn it_works() {
        let cases: Vec<_> = include_str!("../test-cases.txt")
            .split('\n')
            .filter(|it| !it.trim().is_empty())
            .map(|it| {
                let mut splitted = it.split(',');
                (
                    splitted.next().unwrap().trim(),
                    splitted.next().unwrap().trim(),
                )
            })
            .collect();
        for (singular, plural) in cases {
            println!("{} <=> {}", singular, plural);
            assert_eq!(to_plural(singular), plural);
            assert_eq!(to_singular(plural), singular);
            if !is_uncountable(singular) {
                assert!(is_singular(singular));
                assert!(is_plural(plural));
            }
        }
    }
}