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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#![no_std]

extern crate alloc;

use alloc::{boxed::Box, format, string::String, vec, vec::Vec};
use unicase::UniCase;

// FIXME: Use generators once those work on stable Rust.

fn ends_with_roman_numeral(name: &str) -> bool {
    name.split_whitespace().rev().next().map_or(false, |n| {
        n.chars().all(|c| c == 'I' || c == 'V' || c == 'X')
    })
}

fn ends_with_numeric(name: &str) -> bool {
    name.chars().last().map_or(false, |c| c.is_numeric())
}

fn series_subtitle_handling(name: &str, split_token: &str, list: &mut Vec<Box<str>>) -> bool {
    let mut iter = name.splitn(2, split_token);
    if let (Some(series), Some(subtitle)) = (iter.next(), iter.next()) {
        let series_abbreviations = abbreviate(series);
        let subtitle_abbreviations = abbreviate(subtitle);
        let series_trimmed = series.trim_end();

        let is_series_representative =
            ends_with_numeric(series_trimmed) || ends_with_roman_numeral(series_trimmed);

        let is_there_only_one_series_abbreviation = series_abbreviations.len() == 1;

        for subtitle_abbreviation in &subtitle_abbreviations {
            for series_abbreviation in &series_abbreviations {
                if is_series_representative
                    || &**series_abbreviation != series
                    || is_there_only_one_series_abbreviation
                {
                    list.push(
                        format!("{series_abbreviation}{split_token}{subtitle_abbreviation}").into(),
                    );
                }
            }
        }

        if is_series_representative {
            list.extend(series_abbreviations);
        }
        list.extend(subtitle_abbreviations);

        true
    } else {
        false
    }
}

fn left_right_handling(name: &str, split_token: &str, list: &mut Vec<Box<str>>) -> bool {
    let mut iter = name.splitn(2, split_token);
    if let (Some(series), Some(subtitle)) = (iter.next(), iter.next()) {
        let series_abbreviations = abbreviate(series);
        let subtitle_abbreviations = abbreviate(subtitle);

        for subtitle_abbreviation in &subtitle_abbreviations {
            for series_abbreviation in &series_abbreviations {
                list.push(
                    format!("{series_abbreviation}{split_token}{subtitle_abbreviation}").into(),
                );
            }
        }

        true
    } else {
        false
    }
}

fn and_handling(name: &str, list: &mut Vec<Box<str>>) -> bool {
    let and = UniCase::new("and");
    for word in name.split_whitespace() {
        if UniCase::new(word) == and {
            let index = word.as_ptr() as usize - name.as_ptr() as usize;
            let (left, rest) = name.split_at(index);
            let right = &rest[word.len()..];
            let name = format!("{left}&{right}");
            list.extend(abbreviate(&name));
            return true;
        }
    }
    false
}

fn remove_prefix_word<'a>(text: &'a str, word: &str) -> Option<&'a str> {
    let first_word = text.split_whitespace().next()?;
    if unicase::eq(first_word, word) {
        Some(text[first_word.len()..].trim_start())
    } else {
        None
    }
}

fn is_all_caps_or_digits(text: &str) -> bool {
    text.chars().all(|c| c.is_uppercase() || c.is_numeric())
}

pub fn abbreviate(name: &str) -> Vec<Box<str>> {
    let name = name.trim();
    let mut list = vec![];
    if name.is_empty() {
        return list;
    }

    let parenthesis = name
        .char_indices()
        .rev()
        .find(|&(_, c)| c == '(')
        .and_then(|(start, _)| {
            name[start + 1..]
                .char_indices()
                .find(|&(_, c)| c == ')')
                .map(|(end, _)| (start, end + 2))
        });

    if let Some((start, end)) = parenthesis {
        let (before_parenthesis, rest) = name.split_at(start);
        let after_parenthesis = &rest[end..];
        let name = format!(
            "{} {}",
            before_parenthesis.trim_end(),
            after_parenthesis.trim_start()
        );
        list.extend(abbreviate(&name));
    } else if series_subtitle_handling(name, ": ", &mut list)
        || series_subtitle_handling(name, " - ", &mut list)
        || left_right_handling(name, " | ", &mut list)
        || and_handling(name, &mut list)
    {
    } else {
        if let Some(rest) =
            remove_prefix_word(name, "the").or_else(|| remove_prefix_word(name, "a"))
        {
            list.push(rest.into());
        }

        if name.contains(char::is_whitespace) {
            let mut abbreviated = String::new();
            for word in name.split(|c: char| c.is_whitespace() || c == '-') {
                if let Some(first_char) = word.chars().next() {
                    let word_mapped = word.chars().map(|c| if c == '&' { 'a' } else { c });

                    if first_char.is_numeric() {
                        abbreviated.extend(word_mapped);
                    } else if word.len() <= 4 && is_all_caps_or_digits(word) {
                        if !abbreviated.is_empty() {
                            abbreviated.push(' ');
                        }
                        abbreviated.extend(word_mapped);
                    } else {
                        abbreviated.push(first_char);
                    }
                }
            }
            list.push(abbreviated.into());
        }
    }

    list.sort_unstable();
    list.dedup();

    if let Some(idx) = list.iter().position(|x| name == x.as_ref()) {
        let last = list.len() - 1;
        list.swap(idx, last);
    } else {
        list.push(name.into());
    }

    list
}

pub fn abbreviate_category(category: &str) -> Vec<Box<str>> {
    let mut abbrevs = Vec::new();

    let mut splits = category.splitn(2, '(');
    let before = splits.next().unwrap().trim();

    if let Some(rest) = splits.next() {
        splits = rest.splitn(2, ')');
        let inside = splits.next().unwrap();
        if let Some(after) = splits.next() {
            let after = after.trim_end();

            let mut buf = String::with_capacity(category.len());
            buf.push_str(before);
            buf.push_str(" (");

            let mut splits = inside.split(',');
            let mut variable = splits.next().unwrap();
            for next_variable in splits {
                buf.push_str(variable);
                let old_len = buf.len();

                buf.push(')');
                buf.push_str(after);
                abbrevs.push(buf.as_str().into());

                buf.drain(old_len..);
                buf.push(',');
                variable = next_variable;
            }

            if after.trim().is_empty() {
                buf.drain(before.len()..);
            } else {
                buf.drain(before.len() + 1..);
                buf.push_str(after);
            }

            abbrevs.push(buf.into());
        }
    }

    abbrevs.push(category.into());

    abbrevs
}

#[cfg(test)]
mod tests {
    use super::abbreviate;
    use alloc::boxed::Box;
    use alloc::vec;

    // The tests using actual game titles can be thrown out or edited if any
    // major changes need to be made to the abbreviation algorithm. Do not
    // hesitate to remove them if they are getting in the way of actual
    // improvements.
    //
    // They exist purely as another measure to prevent accidental breakage.
    #[test]
    fn game_test_1() {
        let abbreviations = abbreviate("Burnout 3: Takedown");

        let expected = vec![
            Box::from("B3"),
            Box::from("B3: Takedown"),
            Box::from("Burnout 3"),
            Box::from("Takedown"),
            Box::from("Burnout 3: Takedown"),
        ];

        assert_eq!(abbreviations, expected);
    }

    #[test]
    fn game_test_2() {
        let abbreviations = abbreviate("The Legend of Zelda: The Wind Waker");

        let expected = vec![
            Box::from("Legend of Zelda: TWW"),
            Box::from("Legend of Zelda: The Wind Waker"),
            Box::from("Legend of Zelda: Wind Waker"),
            Box::from("TLoZ: TWW"),
            Box::from("TLoZ: The Wind Waker"),
            Box::from("TLoZ: Wind Waker"),
            Box::from("TWW"),
            Box::from("The Wind Waker"),
            Box::from("Wind Waker"),
            Box::from("The Legend of Zelda: The Wind Waker"),
        ];

        assert_eq!(abbreviations, expected);
    }

    #[test]
    fn game_test_3() {
        let abbreviations = abbreviate("SpongeBob SquarePants: Battle for Bikini Bottom");

        let expected = vec![
            Box::from("Battle for Bikini Bottom"),
            Box::from("BfBB"),
            Box::from("SS: Battle for Bikini Bottom"),
            Box::from("SS: BfBB"),
            Box::from("SpongeBob SquarePants: Battle for Bikini Bottom"),
        ];

        assert_eq!(abbreviations, expected);
    }

    #[test]
    #[rustfmt::skip]
    fn game_test_4() {
        let abbreviations = abbreviate("Super Mario 64");

        let expected = vec![
            Box::from("SM64"),
            Box::from("Super Mario 64"),
        ];

        assert_eq!(abbreviations, expected);
    }

    #[test]
    fn contains_original_title() {
        let abbreviations = abbreviate("test title: the game");
        assert!(abbreviations.contains(&Box::from("test title: the game")));
    }

    #[test]
    fn removes_parens() {
        let abbreviations = abbreviate("test title (the game)");
        assert!(abbreviations.contains(&Box::from("test title")));
    }

    #[test]
    fn original_title_is_last() {
        let abbreviations = abbreviate("test title: the game");
        let last = abbreviations.last().unwrap();

        assert_eq!("test title: the game", last.as_ref())
    }
}