deno.land / std@0.224.0 / cli / _tools / generate_data.ts

generate_data.ts
View Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env -S deno run --allow-net --allow-read --allow-write// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// Ported from unicode_width rust crate, Copyright (c) 2015 The Rust Project Developers. MIT license.
import { assert } from "../../assert/assert.ts";import { runLengthEncode } from "../_run_length.ts";
// change this line and re-run the script to update for new Unicode versionsconst UNICODE_VERSION = "15.0.0";
const NUM_CODEPOINTS = 0x110000;const MAX_CODEPOINT_BITS = Math.ceil(Math.log2(NUM_CODEPOINTS - 1));
const OffsetType = { U2: 2, U4: 4, U8: 8,} as const;
type OffsetType = typeof OffsetType[keyof typeof OffsetType];
type CodePoint = number;type BitPos = number;
const TABLE_CFGS: [BitPos, BitPos, OffsetType][] = [ [13, MAX_CODEPOINT_BITS, OffsetType.U8], [6, 13, OffsetType.U8], [0, 6, OffsetType.U2],];
async function fetchUnicodeData(filename: string, version: string) { const res = await fetch( `https://www.unicode.org/Public/${version}/ucd/${filename}`, );
if (!res.ok) { throw new Error(`Failed to fetch ${filename}`); }
return await res.text();}
const EffectiveWidth = { Zero: 0, Narrow: 1, Wide: 2, Ambiguous: 3,} as const;
type EffectiveWidth = typeof EffectiveWidth[keyof typeof EffectiveWidth];
const widthCodes = { N: EffectiveWidth.Narrow, Na: EffectiveWidth.Narrow, H: EffectiveWidth.Narrow, W: EffectiveWidth.Wide, F: EffectiveWidth.Wide, A: EffectiveWidth.Ambiguous,};
async function loadEastAsianWidths(version: string) { const eaw = await fetchUnicodeData("EastAsianWidth.txt", version);
const single = /^([0-9A-F]+);(\w+)/; const multiple = /^([0-9A-F]+)\.\.([0-9A-F]+);(\w+)/;
const widthMap: EffectiveWidth[] = []; let current = 0;
for (const line of eaw.split("\n")) { let rawData: [string, string, string] | null = null;
let match: RegExpMatchArray | null = null; // deno-lint-ignore no-cond-assign if (match = line.match(single)) { rawData = [match[1]!, match[1]!, match[2]!]; // deno-lint-ignore no-cond-assign } else if (match = line.match(multiple)) { rawData = [match[1]!, match[2]!, match[3]!]; } else { continue; }
const low = parseInt(rawData[0], 16); const high = parseInt(rawData[1], 16); const width = widthCodes[rawData[2] as keyof typeof widthCodes];
assert(current <= high);
while (current <= high) { widthMap.push(current < low ? EffectiveWidth.Narrow : width); ++current; } }
while (widthMap.length < NUM_CODEPOINTS) { widthMap.push(EffectiveWidth.Narrow); }
return widthMap;}
async function loadZeroWidths(version: string) { const categories = await fetchUnicodeData("UnicodeData.txt", version);
const zwMap: boolean[] = []; let current = 0;
for (const line of categories.split("\n")) { const rawData = line.split(";");
if (rawData.length !== 15) { continue; } const [codepoint, name, catCode] = [ parseInt(rawData[0]!, 16), rawData[1], rawData[2], ];
const zeroWidth = ["Cc", "Cf", "Mn", "Me"].includes(catCode!);
assert(current <= codepoint);
while (current <= codepoint) { if (name!.endsWith(", Last>") || (current === codepoint)) { zwMap.push(zeroWidth); } else { zwMap.push(false); } ++current; } } while (zwMap.length < NUM_CODEPOINTS) { zwMap.push(false); }
return zwMap;}
class Bucket { entrySet: Set<string>; widths: EffectiveWidth[];
constructor() { this.entrySet = new Set(); this.widths = []; }
append(codepoint: CodePoint, width: EffectiveWidth) { this.entrySet.add(JSON.stringify([codepoint, width])); this.widths.push(width); }
tryExtend(attempt: Bucket) { const [less, more] = [this.widths, attempt.widths].sort((a, b) => a.length - b.length );
if (!more!.slice(0, less!.length).every((v, i) => v === less![i])) { return false; }
for (const x of attempt.entrySet.values()) { this.entrySet.add(x); }
this.widths = more!;
return true; }
entries() { const result = [...this.entrySet] .map((x) => JSON.parse(x) as [CodePoint, EffectiveWidth]);
return result.sort((a, b) => a[0] - b[0]); }
width() { return new Set(this.widths).size === 1 ? this.widths[0] : null; }}
function makeBuckets( entries: [CodePoint, EffectiveWidth][], lowBit: BitPos, capBit: BitPos,) { const numBits = capBit - lowBit; assert(numBits > 0); const buckets = Array.from({ length: 2 ** numBits }, () => new Bucket());
const mask = (1 << numBits) - 1;
for (const [codepoint, width] of entries) { buckets[(codepoint >> lowBit) & mask]!.append(codepoint, width); }
return buckets;}
class Table { lowBit: BitPos; capBit: BitPos; offsetType: OffsetType; entries: number[]; indexed: Bucket[];
constructor( entryGroups: [CodePoint, EffectiveWidth][][], lowBit: BitPos, capBit: BitPos, offsetType: OffsetType, ) { this.lowBit = lowBit; this.capBit = capBit; this.offsetType = offsetType; this.entries = []; this.indexed = [];
const buckets = entryGroups.flatMap((entries) => makeBuckets(entries, this.lowBit, this.capBit) );
for (const bucket of buckets) { let extended = false; for (const [i, existing] of this.indexed.entries()) { if (existing.tryExtend(bucket)) { this.entries.push(i); extended = true; break; } } if (!extended) { this.entries.push(this.indexed.length); this.indexed.push(bucket); } }
for (const index of this.entries) { assert(index < (1 << this.offsetType)); } }
indicesToWidths() { if (!this.indexed) { throw new Error(`Can't call indicesToWidths twice on the same Table`); }
this.entries = this.entries.map((i) => { const width = this.indexed[i]!.width(); if (width === null) throw new TypeError("width cannot be null"); return width!; });
this.indexed = null as unknown as Bucket[]; }
get buckets() { if (!this.indexed) { throw new Error(`Can't access buckets after calling indicesToWidths`); }
return this.indexed; }
toBytes() { const entriesPerByte = Math.trunc(8 / this.offsetType); const byteArray: number[] = []; for (let i = 0; i < this.entries.length; i += entriesPerByte) { let byte = 0; for (let j = 0; j < entriesPerByte; ++j) { byte |= this.entries[i + j]! << (j * this.offsetType); } byteArray.push(byte); }
return byteArray; }}
function makeTables( tableCfgs: [BitPos, BitPos, OffsetType][], entries: [CodePoint, EffectiveWidth][],) { const tables: Table[] = []; let entryGroups = [entries];
for (const [lowBit, capBit, offsetType] of tableCfgs) { const table = new Table(entryGroups, lowBit, capBit, offsetType); entryGroups = table.buckets.map((bucket) => bucket.entries());
tables.push(table); }
return tables;}
export async function tables(version: string) { console.info(`Generating tables for Unicode ${version}`);
const eawMap = await loadEastAsianWidths(version); const zwMap = await loadZeroWidths(version);
const widthMap = eawMap.map((x, i) => zwMap[i] ? EffectiveWidth.Zero : x);
widthMap[0x00AD] = EffectiveWidth.Narrow;
for (let i = 0x1160; i < 0x11FF + 1; ++i) { widthMap[i] = EffectiveWidth.Zero; }
const tables = makeTables(TABLE_CFGS, [...widthMap.entries()]);
tables[tables.length - 1]!.indicesToWidths();
return tables;}
const data = { UNICODE_VERSION, tables: (await tables(UNICODE_VERSION)).map((table) => runLengthEncode(table.toBytes()) ),};
assert(data.UNICODE_VERSION.split(".").length === 3);assert(data.tables.length === 3);
await Deno.writeTextFile("../_data.json", JSON.stringify(data, null, 2) + "\n");
std

Version Info

Tagged at
6 months ago