-
Notifications
You must be signed in to change notification settings - Fork 13
/
unicode.rs
289 lines (267 loc) · 9.47 KB
/
unicode.rs
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
use std::char;
use std::collections::BTreeMap;
use std::fs::{create_dir_all, File};
use std::io::{BufRead, BufWriter, Cursor, Write};
use std::path::Path;
#[cfg(test)]
use std::collections::BTreeSet;
#[cfg(test)]
use std::iter::FromIterator;
use crate::fst_generator;
use anyhow::{anyhow, bail, Context, Result};
use fst::MapBuilder;
#[derive(PartialEq, Debug)]
enum LineType {
None,
Simple,
BlockStart(u32),
BlockEnd(u32),
}
const NAME_ALIASES: &[u8] = include_bytes!("../data/unicode/NameAliases.txt");
const UNICODE_DATA: &[u8] = include_bytes!("../data/unicode/UnicodeData.txt");
pub(crate) fn name_aliases() -> Cursor<&'static [u8]> {
Cursor::new(NAME_ALIASES)
}
pub(crate) fn unicode_data() -> Cursor<&'static [u8]> {
Cursor::new(UNICODE_DATA)
}
fn process_line(names: &mut fst_generator::Names, line: &str) -> Result<LineType> {
if line.starts_with('#') || line.trim_start() == "" {
return Ok(LineType::None);
}
let fields: Vec<&str> = line.splitn(15, ';').collect();
let cp = u32::from_str_radix(fields[0], 16)
.with_context(|| format!("Could not parse {} as base-16 integer", fields[0]))?;
if let Some(ch) = char::from_u32(cp) {
let query = fields[1].to_owned();
if query.ends_with(", First>") {
return Ok(LineType::BlockStart(ch as u32));
} else if query.ends_with(", Last>") {
return Ok(LineType::BlockEnd(ch as u32));
}
names.insert(vec![query], ch);
match fields.get(10) {
Some(&"") | None => {}
Some(&name) => names.insert(vec![name.to_string()], ch),
}
Ok(LineType::Simple)
} else {
Ok(LineType::None)
}
}
#[test]
fn test_processing() {
{
let mut sorted_names = fst_generator::Names::new();
// Non-data gets skipped:
assert_eq!(
LineType::None,
process_line(&mut sorted_names, "# this is a comment").unwrap()
);
assert_eq!(LineType::None, process_line(&mut sorted_names, "").unwrap());
assert_eq!(
LineType::None,
process_line(&mut sorted_names, " ").unwrap()
);
}
{
let mut sorted_names = fst_generator::Names::new();
assert_eq!(
LineType::Simple,
process_line(
&mut sorted_names,
"03BB;GREEK SMALL LETTER LAMDA;Ll;0;L;;;;;N;GREEK SMALL LETTER LAMBDA;;039B;;039B"
)
.unwrap()
);
let have = BTreeSet::from_iter(sorted_names.iter().map(|(name, chs)| {
let v: Vec<char> = chs.iter().map(|ch| ch.to_owned()).collect();
(name.as_str(), v)
}));
let want = BTreeSet::from_iter(vec![
// Current unicode spelling:
("greek", vec!['\u{03bb}']),
("greek small letter lamda", vec!['\u{03bb}']),
("lamda", vec!['\u{03bb}']),
// Unicode 1.0 spelling:
("greek small letter lambda", vec!['\u{03bb}']),
("lambda", vec!['\u{03bb}']),
]);
assert_eq!(have, want);
}
{
let mut sorted_names = fst_generator::Names::new();
// Some from NameAliases.txt:
assert_eq!(
LineType::Simple,
process_line(&mut sorted_names, "0091;PRIVATE USE ONE;control").unwrap()
);
assert_eq!(
LineType::Simple,
process_line(&mut sorted_names, "0092;PRIVATE USE TWO;control").unwrap()
);
assert_eq!(
LineType::Simple,
process_line(&mut sorted_names, "0005;ENQUIRY;control").unwrap()
);
assert_eq!(
LineType::Simple,
process_line(&mut sorted_names, "200D;ZWJ;abbreviation").unwrap()
);
// And some from UnicodeData.txt:
assert_eq!(
LineType::Simple,
process_line(
&mut sorted_names,
"00AE;REGISTERED SIGN;So;0;ON;;;;;N;REGISTERED TRADE MARK SIGN;;;;"
)
.unwrap()
);
assert_eq!(
LineType::Simple,
process_line(
&mut sorted_names,
"0214;LATIN CAPITAL LETTER U WITH DOUBLE GRAVE;Lu;0;L;0055 \
030F;;;;N;;;;0215;e"
)
.unwrap()
);
// CJK blocks:
assert_eq!(
LineType::BlockStart(0x3400),
process_line(
&mut sorted_names,
"3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;"
)
.unwrap()
);
assert_eq!(
LineType::BlockEnd(0x4DB5),
process_line(
&mut sorted_names,
"4DB5;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;"
)
.unwrap()
);
let have = BTreeSet::from_iter(sorted_names.iter().map(|(name, chs)| {
let v: Vec<char> = chs.iter().map(|ch| ch.to_owned()).collect();
(name.as_str(), v)
}));
let want = BTreeSet::from_iter(vec![
("capital", vec!['\u{0214}']),
("double", vec!['\u{0214}']),
("enquiry", vec!['\u{0005}']),
("grave", vec!['\u{0214}']),
("latin", vec!['\u{0214}']),
("latin capital letter u with double grave", vec!['\u{0214}']),
("one", vec!['\u{91}']),
("two", vec!['\u{92}']),
("private", vec!['\u{91}', '\u{92}']),
("use", vec!['\u{91}', '\u{92}']),
("private use one", vec!['\u{91}']),
("private use two", vec!['\u{92}']),
("registered", vec!['\u{AE}']),
("trade", vec!['\u{AE}']),
("mark", vec!['\u{AE}']),
("registered sign", vec!['\u{AE}']),
("registered trade mark sign", vec!['\u{AE}']),
// Skip the "U": it's too short to be meaningful
("zwj", vec!['\u{200D}']),
]);
assert_eq!(have, want);
}
}
#[test]
fn test_old_names() {}
pub fn read_names(names: &mut fst_generator::Names, reader: impl BufRead) -> Result<()> {
let mut lines = reader.lines();
while let Some(line) = lines.next() {
match process_line(names, line?.as_str())? {
LineType::Simple | LineType::None => {}
LineType::BlockStart(start) => {
let line = lines
.next()
.ok_or_else(|| anyhow!("Premature end of block from {:?}", start))?
.with_context(|| {
format!(
"Could not read the next line after block started at {:?}",
start
)
})?;
match process_line(names, &line)? {
LineType::BlockEnd(end) => {
for i in start..=end {
if let Some(ch) = char::from_u32(i) {
if let Some(name) = unicode_names2::name(ch) {
names.insert(vec![name.to_string()], ch);
}
}
}
}
line => {
bail!(
"Encountered a weird line after block start from {:?}: {:?}",
start,
line
);
}
}
}
LineType::BlockEnd(end) => {
bail!("Encountered a block end without a start: {:?}", end);
}
}
}
Ok(())
}
pub fn write_name_data(names: &fst_generator::Names, output: &Path) -> Result<()> {
create_dir_all(output)?;
let fst_byte_filename = output.join("name_fst.bin");
let out = BufWriter::new(File::create(fst_byte_filename)?);
let mut map_builder = MapBuilder::new(out)?;
let mut counter: u64 = 0;
let mut results: BTreeMap<String, u64> = BTreeMap::new();
for (name, chs) in names.iter() {
if chs.len() > 1 {
let mut key = String::new();
for c in chs {
key.push(*c)
}
let num: u64 = (0xff << 32)
| *results.entry(key).or_insert_with(|| {
counter += 1;
counter - 1
});
map_builder
.insert(name, num)
.with_context(|| format!("Inserting character num {:?} under {:?}", num, name))?;
} else {
map_builder
.insert(name, *chs.iter().next().unwrap() as u64)
.with_context(|| format!("Inserting {:?} as {:?}", chs, name))?;
}
}
map_builder.finish()?;
// Now generate the multi-results file:
let multi_result_filename = output.join("names.rs");
let mut rust_out = BufWriter::new(
File::create(&multi_result_filename)
.context(format!("Creating {:?}", &multi_result_filename))?,
);
let mut ambiguous_chars: Vec<String> = vec![String::new(); counter as usize];
for (chars, i) in results {
ambiguous_chars[i as usize] = chars;
}
writeln!(&mut rust_out, "/// Generated with `make names`")?;
writeln!(&mut rust_out, "#[rustfmt::skip]")?;
writeln!(
&mut rust_out,
"pub static AMBIGUOUS_CHARS: &[&str; {}] = &[",
ambiguous_chars.len()
)?;
for chars in ambiguous_chars {
writeln!(&mut rust_out, " {:?},", chars)?;
}
writeln!(&mut rust_out, "];")?;
Ok(())
}