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
pub fn chars(subject: &str) -> Vec<&str> {
if subject.is_empty() {
return vec![""];
}
subject.split_terminator("").skip(1).collect::<Vec<_>>()
}
pub fn split<'a>(subject: &'a str, pattern: &str) -> Vec<&'a str> {
if subject.is_empty() {
return vec![""];
}
if pattern.is_empty() {
return vec![subject];
}
subject.split_terminator(pattern).collect::<Vec<_>>()
}
use unicode_segmentation::UnicodeSegmentation;
pub fn words(subject: &str) -> Vec<&str> {
fn split_camel_case(string: &str) -> Vec<&str> {
#[derive(Clone, Copy, PartialEq)]
enum WordMode {
Boundary,
Lowercase,
Uppercase,
}
let mut words = Vec::new();
let mut word_start = 0;
let mut char_indices = string.char_indices().peekable();
let mut mode = WordMode::Boundary;
while let Some((c_idx, c)) = char_indices.next() {
if let Some(&(next_idx, next)) = char_indices.peek() {
let next_mode = if c.is_lowercase() {
WordMode::Lowercase
} else if c.is_uppercase() {
WordMode::Uppercase
} else {
mode
};
if next_mode == WordMode::Lowercase && next.is_uppercase() {
words.push(&string[word_start..next_idx]);
word_start = next_idx;
mode = WordMode::Boundary;
} else if mode == WordMode::Uppercase && c.is_uppercase() && next.is_lowercase() {
words.push(&string[word_start..c_idx]);
word_start = c_idx;
mode = WordMode::Boundary;
} else {
mode = next_mode;
}
}
}
words.push(&string[word_start..]);
words
}
let splitting_punctuation = ['-', '_'];
let split_by_whitespace_and_punctuation = subject
.unicode_words()
.flat_map(|w| w.split_terminator(|c| splitting_punctuation.contains(&c)))
.filter(|w| !w.is_empty());
let res = split_by_whitespace_and_punctuation.flat_map(split_camel_case);
res.collect()
}
pub fn graphemes(subject: &str) -> Vec<&str> {
if subject.is_empty() {
return vec![""];
}
UnicodeSegmentation::graphemes(subject, true).collect::<Vec<&str>>()
}