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
use std::str::CharIndices;
#[inline]
pub fn char_width(ch: char) -> Option<usize> {
use unicode_width::UnicodeWidthChar;
ch.width()
}
#[inline]
pub fn is_combining_mark(ch: char) -> bool {
use unicode_normalization::char::is_combining_mark;
is_combining_mark(ch)
}
const CTRL_MASK: u8 = 0x1f;
const UNCTRL_BIT: u8 = 0x40;
#[inline]
pub fn ctrl(ch: char) -> char {
((ch as u8) & CTRL_MASK) as char
}
#[inline]
pub fn is_ctrl(ch: char) -> bool {
let ch = ch as u32;
ch & (CTRL_MASK as u32) == ch
}
#[inline]
pub fn unctrl_upper(ch: char) -> char {
((ch as u8) | UNCTRL_BIT) as char
}
#[inline]
pub fn unctrl_lower(ch: char) -> char {
unctrl_upper(ch).to_ascii_lowercase()
}
pub struct Prefixes<'a> {
s: &'a str,
iter: CharIndices<'a>,
}
#[inline]
pub fn prefixes(s: &str) -> Prefixes {
Prefixes{
s,
iter: s.char_indices(),
}
}
impl<'a> Iterator for Prefixes<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.iter.next().map(|(idx, ch)| &self.s[..idx + ch.len_utf8()])
}
}
#[cfg(test)]
mod test {
use super::{ctrl, is_ctrl, unctrl_lower, unctrl_upper, prefixes};
#[test]
fn test_unctrl() {
for ch in 0u8..255 {
let ch = ch as char;
if is_ctrl(ch) {
assert_eq!(ch, ctrl(unctrl_lower(ch)));
assert_eq!(ch, ctrl(unctrl_upper(ch)));
}
}
}
#[test]
fn test_prefix_iter() {
let mut pfxs = prefixes("foobar");
assert_eq!(pfxs.next(), Some("f"));
assert_eq!(pfxs.next(), Some("fo"));
assert_eq!(pfxs.next(), Some("foo"));
assert_eq!(pfxs.next(), Some("foob"));
assert_eq!(pfxs.next(), Some("fooba"));
assert_eq!(pfxs.next(), Some("foobar"));
assert_eq!(pfxs.next(), None);
let mut pfxs = prefixes("a");
assert_eq!(pfxs.next(), Some("a"));
assert_eq!(pfxs.next(), None);
let mut pfxs = prefixes("");
assert_eq!(pfxs.next(), None);
}
}