@chr33s/pdf-unicode-trie 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,835 @@
1
+ import { deflate } from "@chr33s/pdf-common";
2
+ import { Buffer } from "node:buffer";
3
+ import UnicodeTrie from "./index.js";
4
+ import { swap32LE } from "./swap.js";
5
+ // Shift size for getting the index-1 table offset.
6
+ const SHIFT_1 = 6 + 5;
7
+ // Shift size for getting the index-2 table offset.
8
+ const SHIFT_2 = 5;
9
+ // Difference between the two shift sizes,
10
+ // for getting an index-1 offset from an index-2 offset. 6=11-5
11
+ const SHIFT_1_2 = SHIFT_1 - SHIFT_2;
12
+ // Number of index-1 entries for the BMP. 32=0x20
13
+ // This part of the index-1 table is omitted from the serialized form.
14
+ const OMITTED_BMP_INDEX_1_LENGTH = 0x10000 >> SHIFT_1;
15
+ // Number of code points per index-1 table entry. 2048=0x800
16
+ const CP_PER_INDEX_1_ENTRY = 1 << SHIFT_1;
17
+ // Number of entries in an index-2 block. 64=0x40
18
+ const INDEX_2_BLOCK_LENGTH = 1 << SHIFT_1_2;
19
+ // Mask for getting the lower bits for the in-index-2-block offset. */
20
+ const INDEX_2_MASK = INDEX_2_BLOCK_LENGTH - 1;
21
+ // Number of entries in a data block. 32=0x20
22
+ const DATA_BLOCK_LENGTH = 1 << SHIFT_2;
23
+ // Mask for getting the lower bits for the in-data-block offset.
24
+ const DATA_MASK = DATA_BLOCK_LENGTH - 1;
25
+ // Shift size for shifting left the index array values.
26
+ // Increases possible data size with 16-bit index values at the cost
27
+ // of compactability.
28
+ // This requires data blocks to be aligned by DATA_GRANULARITY.
29
+ const INDEX_SHIFT = 2;
30
+ // The alignment size of a data block. Also the granularity for compaction.
31
+ const DATA_GRANULARITY = 1 << INDEX_SHIFT;
32
+ // The BMP part of the index-2 table is fixed and linear and starts at offset 0.
33
+ // Length=2048=0x800=0x10000>>SHIFT_2.
34
+ const INDEX_2_OFFSET = 0;
35
+ // The part of the index-2 table for U+D800..U+DBFF stores values for
36
+ // lead surrogate code _units_ not code _points_.
37
+ // Values for lead surrogate code _points_ are indexed with this portion of the table.
38
+ // Length=32=0x20=0x400>>SHIFT_2. (There are 1024=0x400 lead surrogates.)
39
+ const LSCP_INDEX_2_OFFSET = 0x10000 >> SHIFT_2;
40
+ const LSCP_INDEX_2_LENGTH = 0x400 >> SHIFT_2;
41
+ // Count the lengths of both BMP pieces. 2080=0x820
42
+ const INDEX_2_BMP_LENGTH = LSCP_INDEX_2_OFFSET + LSCP_INDEX_2_LENGTH;
43
+ // The 2-byte UTF-8 version of the index-2 table follows at offset 2080=0x820.
44
+ // Length 32=0x20 for lead bytes C0..DF, regardless of SHIFT_2.
45
+ const UTF8_2B_INDEX_2_OFFSET = INDEX_2_BMP_LENGTH;
46
+ const UTF8_2B_INDEX_2_LENGTH = 0x800 >> 6; // U+0800 is the first code point after 2-byte UTF-8
47
+ // The index-1 table, only used for supplementary code points, at offset 2112=0x840.
48
+ // Variable length, for code points up to highStart, where the last single-value range starts.
49
+ // Maximum length 512=0x200=0x100000>>SHIFT_1.
50
+ // (For 0x100000 supplementary code points U+10000..U+10ffff.)
51
+ //
52
+ // The part of the index-2 table for supplementary code points starts
53
+ // after this index-1 table.
54
+ //
55
+ // Both the index-1 table and the following part of the index-2 table
56
+ // are omitted completely if there is only BMP data.
57
+ const INDEX_1_OFFSET = UTF8_2B_INDEX_2_OFFSET + UTF8_2B_INDEX_2_LENGTH;
58
+ const MAX_INDEX_1_LENGTH = 0x100000 >> SHIFT_1;
59
+ // The illegal-UTF-8 data block follows the ASCII block, at offset 128=0x80.
60
+ // Used with linear access for single bytes 0..0xbf for simple error handling.
61
+ // Length 64=0x40, not DATA_BLOCK_LENGTH.
62
+ const BAD_UTF8_DATA_OFFSET = 0x80;
63
+ // The start of non-linear-ASCII data blocks, at offset 192=0xc0.
64
+ // !!!!
65
+ const DATA_START_OFFSET = 0xc0;
66
+ // The null data block.
67
+ // Length 64=0x40 even if DATA_BLOCK_LENGTH is smaller,
68
+ // to work with 6-bit trail bytes from 2-byte UTF-8.
69
+ const DATA_NULL_OFFSET = DATA_START_OFFSET;
70
+ // The start of allocated data blocks.
71
+ const NEW_DATA_START_OFFSET = DATA_NULL_OFFSET + 0x40;
72
+ // The start of data blocks for U+0800 and above.
73
+ // Below, compaction uses a block length of 64 for 2-byte UTF-8.
74
+ // From here on, compaction uses DATA_BLOCK_LENGTH.
75
+ // Data values for 0x780 code points beyond ASCII.
76
+ const DATA_0800_OFFSET = NEW_DATA_START_OFFSET + 0x780;
77
+ // Start with allocation of 16k data entries. */
78
+ const INITIAL_DATA_LENGTH = 1 << 14;
79
+ // Grow about 8x each time.
80
+ const MEDIUM_DATA_LENGTH = 1 << 17;
81
+ // Maximum length of the runtime data array.
82
+ // Limited by 16-bit index values that are left-shifted by INDEX_SHIFT,
83
+ // and by uint16_t UTrie2Header.shiftedDataLength.
84
+ const MAX_DATA_LENGTH_RUNTIME = 0xffff << INDEX_SHIFT;
85
+ const INDEX_1_LENGTH = 0x110000 >> SHIFT_1;
86
+ // Maximum length of the build-time data array.
87
+ // One entry per 0x110000 code points, plus the illegal-UTF-8 block and the null block,
88
+ // plus values for the 0x400 surrogate code units.
89
+ const MAX_DATA_LENGTH_BUILDTIME = 0x110000 + 0x40 + 0x40 + 0x400;
90
+ // At build time, leave a gap in the index-2 table,
91
+ // at least as long as the maximum lengths of the 2-byte UTF-8 index-2 table
92
+ // and the supplementary index-1 table.
93
+ // Round up to INDEX_2_BLOCK_LENGTH for proper compacting.
94
+ const INDEX_GAP_OFFSET = INDEX_2_BMP_LENGTH;
95
+ const INDEX_GAP_LENGTH = (UTF8_2B_INDEX_2_LENGTH + MAX_INDEX_1_LENGTH + INDEX_2_MASK) & ~INDEX_2_MASK;
96
+ // Maximum length of the build-time index-2 array.
97
+ // Maximum number of Unicode code points (0x110000) shifted right by SHIFT_2,
98
+ // plus the part of the index-2 table for lead surrogate code points,
99
+ // plus the build-time index gap,
100
+ // plus the null index-2 block.)
101
+ const MAX_INDEX_2_LENGTH = (0x110000 >> SHIFT_2) + LSCP_INDEX_2_LENGTH + INDEX_GAP_LENGTH + INDEX_2_BLOCK_LENGTH;
102
+ // The null index-2 block, following the gap in the index-2 table.
103
+ const INDEX_2_NULL_OFFSET = INDEX_GAP_OFFSET + INDEX_GAP_LENGTH;
104
+ // The start of allocated index-2 blocks.
105
+ const INDEX_2_START_OFFSET = INDEX_2_NULL_OFFSET + INDEX_2_BLOCK_LENGTH;
106
+ // Maximum length of the runtime index array.
107
+ // Limited by its own 16-bit index values, and by uint16_t UTrie2Header.indexLength.
108
+ // (The actual maximum length is lower,
109
+ // (0x110000>>SHIFT_2)+UTF8_2B_INDEX_2_LENGTH+MAX_INDEX_1_LENGTH.)
110
+ const MAX_INDEX_LENGTH = 0xffff;
111
+ const equal_int = (a, s, t, length) => {
112
+ for (let i = 0; i < length; i++) {
113
+ if (a[s + i] !== a[t + i]) {
114
+ return false;
115
+ }
116
+ }
117
+ return true;
118
+ };
119
+ class UnicodeTrieBuilder {
120
+ #initialValue;
121
+ #errorValue;
122
+ #index1;
123
+ #index2;
124
+ #highStart;
125
+ #data;
126
+ #dataCapacity;
127
+ #firstFreeBlock;
128
+ #isCompacted;
129
+ #map;
130
+ #dataNullOffset;
131
+ #dataLength;
132
+ #index2NullOffset;
133
+ #index2Length;
134
+ constructor(initialValue = 0, errorValue = 0) {
135
+ let i, j;
136
+ if (initialValue == null) {
137
+ initialValue = 0;
138
+ }
139
+ this.#initialValue = initialValue;
140
+ if (errorValue == null) {
141
+ errorValue = 0;
142
+ }
143
+ this.#errorValue = errorValue;
144
+ this.#index1 = new Int32Array(INDEX_1_LENGTH);
145
+ this.#index2 = new Int32Array(MAX_INDEX_2_LENGTH);
146
+ this.#highStart = 0x110000;
147
+ this.#data = new Uint32Array(INITIAL_DATA_LENGTH);
148
+ this.#dataCapacity = INITIAL_DATA_LENGTH;
149
+ this.#firstFreeBlock = 0;
150
+ this.#isCompacted = false;
151
+ // Multi-purpose per-data-block table.
152
+ //
153
+ // Before compacting:
154
+ //
155
+ // Per-data-block reference counters/free-block list.
156
+ // 0: unused
157
+ // >0: reference counter (number of index-2 entries pointing here)
158
+ // <0: next free data block in free-block list
159
+ //
160
+ // While compacting:
161
+ //
162
+ // Map of adjusted indexes, used in compactData() and compactIndex2().
163
+ // Maps from original indexes to new ones.
164
+ this.#map = new Int32Array(MAX_DATA_LENGTH_BUILDTIME >> SHIFT_2);
165
+ for (i = 0; i < 0x80; i++) {
166
+ this.#data[i] = this.#initialValue;
167
+ }
168
+ for (; i < 0xc0; i++) {
169
+ this.#data[i] = this.#errorValue;
170
+ }
171
+ for (i = DATA_NULL_OFFSET; i < NEW_DATA_START_OFFSET; i++) {
172
+ this.#data[i] = this.#initialValue;
173
+ }
174
+ this.#dataNullOffset = DATA_NULL_OFFSET;
175
+ this.#dataLength = NEW_DATA_START_OFFSET;
176
+ // set the index-2 indexes for the 2=0x80>>SHIFT_2 ASCII data blocks
177
+ i = 0;
178
+ for (j = 0; j < 0x80; j += DATA_BLOCK_LENGTH) {
179
+ this.#index2[i] = j;
180
+ this.#map[i++] = 1;
181
+ }
182
+ // reference counts for the bad-UTF-8-data block
183
+ for (; j < 0xc0; j += DATA_BLOCK_LENGTH) {
184
+ this.#map[i++] = 0;
185
+ }
186
+ // Reference counts for the null data block: all blocks except for the ASCII blocks.
187
+ // Plus 1 so that we don't drop this block during compaction.
188
+ // Plus as many as needed for lead surrogate code points.
189
+ // i==newTrie->dataNullOffset
190
+ this.#map[i++] = (0x110000 >> SHIFT_2) - (0x80 >> SHIFT_2) + 1 + LSCP_INDEX_2_LENGTH;
191
+ j += DATA_BLOCK_LENGTH;
192
+ for (; j < NEW_DATA_START_OFFSET; j += DATA_BLOCK_LENGTH) {
193
+ this.#map[i++] = 0;
194
+ }
195
+ // set the remaining indexes in the BMP index-2 block
196
+ // to the null data block
197
+ for (i = 0x80 >> SHIFT_2; i < INDEX_2_BMP_LENGTH; i++) {
198
+ this.#index2[i] = DATA_NULL_OFFSET;
199
+ }
200
+ // Fill the index gap with impossible values so that compaction
201
+ // does not overlap other index-2 blocks with the gap.
202
+ for (i = 0; i < INDEX_GAP_LENGTH; i++) {
203
+ this.#index2[INDEX_GAP_OFFSET + i] = -1;
204
+ }
205
+ // set the indexes in the null index-2 block
206
+ for (i = 0; i < INDEX_2_BLOCK_LENGTH; i++) {
207
+ this.#index2[INDEX_2_NULL_OFFSET + i] = DATA_NULL_OFFSET;
208
+ }
209
+ this.#index2NullOffset = INDEX_2_NULL_OFFSET;
210
+ this.#index2Length = INDEX_2_START_OFFSET;
211
+ // set the index-1 indexes for the linear index-2 block
212
+ j = 0;
213
+ for (i = 0; i < OMITTED_BMP_INDEX_1_LENGTH; i++) {
214
+ this.#index1[i] = j;
215
+ j += INDEX_2_BLOCK_LENGTH;
216
+ }
217
+ // set the remaining index-1 indexes to the null index-2 block
218
+ for (; i < INDEX_1_LENGTH; i++) {
219
+ this.#index1[i] = INDEX_2_NULL_OFFSET;
220
+ }
221
+ // Preallocate and reset data for U+0080..U+07ff,
222
+ // for 2-byte UTF-8 which will be compacted in 64-blocks
223
+ // even if DATA_BLOCK_LENGTH is smaller.
224
+ for (i = 0x80; i < 0x800; i += DATA_BLOCK_LENGTH) {
225
+ this.set(i, this.#initialValue);
226
+ }
227
+ }
228
+ set(codePoint, value) {
229
+ if (codePoint < 0 || codePoint > 0x10ffff) {
230
+ throw new Error("Invalid code point");
231
+ }
232
+ if (this.#isCompacted) {
233
+ throw new Error("Already compacted");
234
+ }
235
+ const block = this.#getDataBlock(codePoint, true);
236
+ this.#data[block + (codePoint & DATA_MASK)] = value;
237
+ return this;
238
+ }
239
+ setRange(start, end, value, overwrite = true) {
240
+ let block, repeatBlock;
241
+ const shouldOverwrite = overwrite ?? true;
242
+ if (start > 0x10ffff || end > 0x10ffff || start > end) {
243
+ throw new Error("Invalid code point");
244
+ }
245
+ if (this.#isCompacted) {
246
+ throw new Error("Already compacted");
247
+ }
248
+ if (!shouldOverwrite && value === this.#initialValue) {
249
+ return this; // nothing to do
250
+ }
251
+ let limit = end + 1;
252
+ if ((start & DATA_MASK) !== 0) {
253
+ // set partial block at [start..following block boundary
254
+ block = this.#getDataBlock(start, true);
255
+ const nextStart = (start + DATA_BLOCK_LENGTH) & ~DATA_MASK;
256
+ if (nextStart <= limit) {
257
+ this.#fillBlock(block, start & DATA_MASK, DATA_BLOCK_LENGTH, value, this.#initialValue, shouldOverwrite);
258
+ start = nextStart;
259
+ }
260
+ else {
261
+ this.#fillBlock(block, start & DATA_MASK, limit & DATA_MASK, value, this.#initialValue, shouldOverwrite);
262
+ return this;
263
+ }
264
+ }
265
+ // number of positions in the last, partial block
266
+ const rest = limit & DATA_MASK;
267
+ // round down limit to a block boundary
268
+ limit &= ~DATA_MASK;
269
+ // iterate over all-value blocks
270
+ if (value === this.#initialValue) {
271
+ repeatBlock = this.#dataNullOffset;
272
+ }
273
+ else {
274
+ repeatBlock = -1;
275
+ }
276
+ while (start < limit) {
277
+ let setRepeatBlock = false;
278
+ if (value === this.#initialValue && this.#isInNullBlock(start, true)) {
279
+ start += DATA_BLOCK_LENGTH; // nothing to do
280
+ continue;
281
+ }
282
+ // get index value
283
+ let i2 = this.#getIndex2Block(start, true);
284
+ i2 += (start >> SHIFT_2) & INDEX_2_MASK;
285
+ block = this.#index2[i2];
286
+ if (this.#isWritableBlock(block)) {
287
+ // already allocated
288
+ if (shouldOverwrite && block >= DATA_0800_OFFSET) {
289
+ // We overwrite all values, and it's not a
290
+ // protected (ASCII-linear or 2-byte UTF-8) block:
291
+ // replace with the repeatBlock.
292
+ setRepeatBlock = true;
293
+ }
294
+ else {
295
+ // protected block: just write the values into this block
296
+ this.#fillBlock(block, 0, DATA_BLOCK_LENGTH, value, this.#initialValue, shouldOverwrite);
297
+ }
298
+ }
299
+ else if (this.#data[block] !== value &&
300
+ (shouldOverwrite || block === this.#dataNullOffset)) {
301
+ // Set the repeatBlock instead of the null block or previous repeat block:
302
+ //
303
+ // If !isWritableBlock() then all entries in the block have the same value
304
+ // because it's the null block or a range block (the repeatBlock from a previous
305
+ // call to utrie2_setRange32()).
306
+ // No other blocks are used multiple times before compacting.
307
+ //
308
+ // The null block is the only non-writable block with the initialValue because
309
+ // of the repeatBlock initialization above. (If value==initialValue, then
310
+ // the repeatBlock will be the null data block.)
311
+ //
312
+ // We set our repeatBlock if the desired value differs from the block's value,
313
+ // and if we overwrite any data or if the data is all initial values
314
+ // (which is the same as the block being the null block, see above).
315
+ setRepeatBlock = true;
316
+ }
317
+ if (setRepeatBlock) {
318
+ if (repeatBlock >= 0) {
319
+ this.#setIndex2Entry(i2, repeatBlock);
320
+ }
321
+ else {
322
+ // create and set and fill the repeatBlock
323
+ repeatBlock = this.#getDataBlock(start, true);
324
+ this.#writeBlock(repeatBlock, value);
325
+ }
326
+ }
327
+ start += DATA_BLOCK_LENGTH;
328
+ }
329
+ if (rest > 0) {
330
+ // set partial block at [last block boundary..limit
331
+ block = this.#getDataBlock(start, true);
332
+ this.#fillBlock(block, 0, rest, value, this.#initialValue, shouldOverwrite);
333
+ }
334
+ return this;
335
+ }
336
+ get(c, fromLSCP = true) {
337
+ let i2;
338
+ const useLSCP = fromLSCP ?? true;
339
+ if (c < 0 || c > 0x10ffff) {
340
+ return this.#errorValue;
341
+ }
342
+ if (c >= this.#highStart && (!(c >= 0xd800 && c < 0xdc00) || useLSCP)) {
343
+ return this.#data[this.#dataLength - DATA_GRANULARITY];
344
+ }
345
+ if (c >= 0xd800 && c < 0xdc00 && useLSCP) {
346
+ i2 = LSCP_INDEX_2_OFFSET - (0xd800 >> SHIFT_2) + (c >> SHIFT_2);
347
+ }
348
+ else {
349
+ i2 = this.#index1[c >> SHIFT_1] + ((c >> SHIFT_2) & INDEX_2_MASK);
350
+ }
351
+ const block = this.#index2[i2];
352
+ return this.#data[block + (c & DATA_MASK)];
353
+ }
354
+ #isInNullBlock(c, forLSCP) {
355
+ let i2;
356
+ if ((c & 0xfffffc00) === 0xd800 && forLSCP) {
357
+ i2 = LSCP_INDEX_2_OFFSET - (0xd800 >> SHIFT_2) + (c >> SHIFT_2);
358
+ }
359
+ else {
360
+ i2 = this.#index1[c >> SHIFT_1] + ((c >> SHIFT_2) & INDEX_2_MASK);
361
+ }
362
+ const block = this.#index2[i2];
363
+ return block === this.#dataNullOffset;
364
+ }
365
+ #allocIndex2Block() {
366
+ const newBlock = this.#index2Length;
367
+ const newTop = newBlock + INDEX_2_BLOCK_LENGTH;
368
+ if (newTop > this.#index2.length) {
369
+ // Should never occur.
370
+ // Either MAX_BUILD_TIME_INDEX_LENGTH is incorrect,
371
+ // or the code writes more values than should be possible.
372
+ throw new Error("Internal error in Trie2 creation.");
373
+ }
374
+ this.#index2Length = newTop;
375
+ this.#index2.set(this.#index2.subarray(this.#index2NullOffset, this.#index2NullOffset + INDEX_2_BLOCK_LENGTH), newBlock);
376
+ return newBlock;
377
+ }
378
+ #getIndex2Block(c, forLSCP) {
379
+ if (c >= 0xd800 && c < 0xdc00 && forLSCP) {
380
+ return LSCP_INDEX_2_OFFSET;
381
+ }
382
+ const i1 = c >> SHIFT_1;
383
+ let i2 = this.#index1[i1];
384
+ if (i2 === this.#index2NullOffset) {
385
+ i2 = this.#allocIndex2Block();
386
+ this.#index1[i1] = i2;
387
+ }
388
+ return i2;
389
+ }
390
+ #isWritableBlock(block) {
391
+ return block !== this.#dataNullOffset && this.#map[block >> SHIFT_2] === 1;
392
+ }
393
+ #allocDataBlock(copyBlock) {
394
+ let newBlock;
395
+ if (this.#firstFreeBlock !== 0) {
396
+ // get the first free block
397
+ newBlock = this.#firstFreeBlock;
398
+ this.#firstFreeBlock = -this.#map[newBlock >> SHIFT_2];
399
+ }
400
+ else {
401
+ // get a new block from the high end
402
+ newBlock = this.#dataLength;
403
+ const newTop = newBlock + DATA_BLOCK_LENGTH;
404
+ if (newTop > this.#dataCapacity) {
405
+ // out of memory in the data array
406
+ let capacity;
407
+ if (this.#dataCapacity < MEDIUM_DATA_LENGTH) {
408
+ capacity = MEDIUM_DATA_LENGTH;
409
+ }
410
+ else if (this.#dataCapacity < MAX_DATA_LENGTH_BUILDTIME) {
411
+ capacity = MAX_DATA_LENGTH_BUILDTIME;
412
+ }
413
+ else {
414
+ // Should never occur.
415
+ // Either MAX_DATA_LENGTH_BUILDTIME is incorrect,
416
+ // or the code writes more values than should be possible.
417
+ throw new Error("Internal error in Trie2 creation.");
418
+ }
419
+ const newData = new Uint32Array(capacity);
420
+ newData.set(this.#data.subarray(0, this.#dataLength));
421
+ this.#data = newData;
422
+ this.#dataCapacity = capacity;
423
+ }
424
+ this.#dataLength = newTop;
425
+ }
426
+ this.#data.set(this.#data.subarray(copyBlock, copyBlock + DATA_BLOCK_LENGTH), newBlock);
427
+ this.#map[newBlock >> SHIFT_2] = 0;
428
+ return newBlock;
429
+ }
430
+ #releaseDataBlock(block) {
431
+ // put this block at the front of the free-block chain
432
+ this.#map[block >> SHIFT_2] = -this.#firstFreeBlock;
433
+ this.#firstFreeBlock = block;
434
+ }
435
+ #setIndex2Entry(i2, block) {
436
+ ++this.#map[block >> SHIFT_2]; // increment first, in case block == oldBlock!
437
+ const oldBlock = this.#index2[i2];
438
+ if (--this.#map[oldBlock >> SHIFT_2] === 0) {
439
+ this.#releaseDataBlock(oldBlock);
440
+ }
441
+ this.#index2[i2] = block;
442
+ }
443
+ #getDataBlock(c, forLSCP) {
444
+ let i2 = this.#getIndex2Block(c, forLSCP);
445
+ i2 += (c >> SHIFT_2) & INDEX_2_MASK;
446
+ const oldBlock = this.#index2[i2];
447
+ if (this.#isWritableBlock(oldBlock)) {
448
+ return oldBlock;
449
+ }
450
+ // allocate a new data block
451
+ const newBlock = this.#allocDataBlock(oldBlock);
452
+ this.#setIndex2Entry(i2, newBlock);
453
+ return newBlock;
454
+ }
455
+ #fillBlock(block, start, limit, value, initialValue, overwrite) {
456
+ let i;
457
+ if (overwrite) {
458
+ for (i = block + start; i < block + limit; i++) {
459
+ this.#data[i] = value;
460
+ }
461
+ }
462
+ else {
463
+ for (i = block + start; i < block + limit; i++) {
464
+ if (this.#data[i] === initialValue) {
465
+ this.#data[i] = value;
466
+ }
467
+ }
468
+ }
469
+ }
470
+ #writeBlock(block, value) {
471
+ const limit = block + DATA_BLOCK_LENGTH;
472
+ while (block < limit) {
473
+ this.#data[block++] = value;
474
+ }
475
+ }
476
+ #findHighStart(highValue) {
477
+ let prevBlock, prevI2Block;
478
+ const data32 = this.#data;
479
+ const initialValue = this.#initialValue;
480
+ const index2NullOffset = this.#index2NullOffset;
481
+ const nullBlock = this.#dataNullOffset;
482
+ // set variables for previous range
483
+ if (highValue === initialValue) {
484
+ prevI2Block = index2NullOffset;
485
+ prevBlock = nullBlock;
486
+ }
487
+ else {
488
+ prevI2Block = -1;
489
+ prevBlock = -1;
490
+ }
491
+ const prev = 0x110000;
492
+ // enumerate index-2 blocks
493
+ let i1 = INDEX_1_LENGTH;
494
+ let c = prev;
495
+ while (c > 0) {
496
+ const i2Block = this.#index1[--i1];
497
+ if (i2Block === prevI2Block) {
498
+ // the index-2 block is the same as the previous one, and filled with highValue
499
+ c -= CP_PER_INDEX_1_ENTRY;
500
+ continue;
501
+ }
502
+ prevI2Block = i2Block;
503
+ if (i2Block === index2NullOffset) {
504
+ // this is the null index-2 block
505
+ if (highValue !== initialValue) {
506
+ return c;
507
+ }
508
+ c -= CP_PER_INDEX_1_ENTRY;
509
+ }
510
+ else {
511
+ // enumerate data blocks for one index-2 block
512
+ let i2 = INDEX_2_BLOCK_LENGTH;
513
+ while (i2 > 0) {
514
+ const block = this.#index2[i2Block + --i2];
515
+ if (block === prevBlock) {
516
+ // the block is the same as the previous one, and filled with highValue
517
+ c -= DATA_BLOCK_LENGTH;
518
+ continue;
519
+ }
520
+ prevBlock = block;
521
+ if (block === nullBlock) {
522
+ // this is the null data block
523
+ if (highValue !== initialValue) {
524
+ return c;
525
+ }
526
+ c -= DATA_BLOCK_LENGTH;
527
+ }
528
+ else {
529
+ let j = DATA_BLOCK_LENGTH;
530
+ while (j > 0) {
531
+ const value = data32[block + --j];
532
+ if (value !== highValue) {
533
+ return c;
534
+ }
535
+ --c;
536
+ }
537
+ }
538
+ }
539
+ }
540
+ }
541
+ // deliver last range
542
+ return 0;
543
+ }
544
+ #findSameDataBlock(dataLength, otherBlock, blockLength) {
545
+ // ensure that we do not even partially get past dataLength
546
+ dataLength -= blockLength;
547
+ let block = 0;
548
+ while (block <= dataLength) {
549
+ if (equal_int(this.#data, block, otherBlock, blockLength)) {
550
+ return block;
551
+ }
552
+ block += DATA_GRANULARITY;
553
+ }
554
+ return -1;
555
+ }
556
+ #findSameIndex2Block(index2Length, otherBlock) {
557
+ // ensure that we do not even partially get past index2Length
558
+ index2Length -= INDEX_2_BLOCK_LENGTH;
559
+ for (let block = 0; block <= index2Length; block++) {
560
+ if (equal_int(this.#index2, block, otherBlock, INDEX_2_BLOCK_LENGTH)) {
561
+ return block;
562
+ }
563
+ }
564
+ return -1;
565
+ }
566
+ #compactData() {
567
+ // do not compact linear-ASCII data
568
+ let newStart = DATA_START_OFFSET;
569
+ let start = 0;
570
+ let i = 0;
571
+ while (start < newStart) {
572
+ this.#map[i++] = start;
573
+ start += DATA_BLOCK_LENGTH;
574
+ }
575
+ // Start with a block length of 64 for 2-byte UTF-8,
576
+ // then switch to DATA_BLOCK_LENGTH.
577
+ let blockLength = 64;
578
+ let blockCount = blockLength >> SHIFT_2;
579
+ start = newStart;
580
+ while (start < this.#dataLength) {
581
+ // start: index of first entry of current block
582
+ // newStart: index where the current block is to be moved
583
+ // (right after current end of already-compacted data)
584
+ let mapIndex, movedStart;
585
+ if (start === DATA_0800_OFFSET) {
586
+ blockLength = DATA_BLOCK_LENGTH;
587
+ blockCount = 1;
588
+ }
589
+ // skip blocks that are not used
590
+ if (this.#map[start >> SHIFT_2] <= 0) {
591
+ // advance start to the next block
592
+ start += blockLength;
593
+ // leave newStart with the previous block!
594
+ continue;
595
+ }
596
+ // search for an identical block
597
+ if ((movedStart = this.#findSameDataBlock(newStart, start, blockLength)) >= 0) {
598
+ // found an identical block, set the other block's index value for the current block
599
+ mapIndex = start >> SHIFT_2;
600
+ for (i = blockCount; i > 0; i--) {
601
+ this.#map[mapIndex++] = movedStart;
602
+ movedStart += DATA_BLOCK_LENGTH;
603
+ }
604
+ // advance start to the next block
605
+ start += blockLength;
606
+ // leave newStart with the previous block!
607
+ continue;
608
+ }
609
+ // see if the beginning of this block can be overlapped with the end of the previous block
610
+ // look for maximum overlap (modulo granularity) with the previous, adjacent block
611
+ let overlap = blockLength - DATA_GRANULARITY;
612
+ while (overlap > 0 && !equal_int(this.#data, newStart - overlap, start, overlap)) {
613
+ overlap -= DATA_GRANULARITY;
614
+ }
615
+ if (overlap > 0 || newStart < start) {
616
+ // some overlap, or just move the whole block
617
+ movedStart = newStart - overlap;
618
+ mapIndex = start >> SHIFT_2;
619
+ for (i = blockCount; i > 0; i--) {
620
+ this.#map[mapIndex++] = movedStart;
621
+ movedStart += DATA_BLOCK_LENGTH;
622
+ }
623
+ // move the non-overlapping indexes to their new positions
624
+ start += overlap;
625
+ for (i = blockLength - overlap; i > 0; i--) {
626
+ this.#data[newStart++] = this.#data[start++];
627
+ }
628
+ }
629
+ else {
630
+ // no overlap && newStart==start
631
+ mapIndex = start >> SHIFT_2;
632
+ for (i = blockCount; i > 0; i--) {
633
+ this.#map[mapIndex++] = start;
634
+ start += DATA_BLOCK_LENGTH;
635
+ }
636
+ newStart = start;
637
+ }
638
+ }
639
+ // now adjust the index-2 table
640
+ i = 0;
641
+ while (i < this.#index2Length) {
642
+ // Gap indexes are invalid (-1). Skip over the gap.
643
+ if (i === INDEX_GAP_OFFSET) {
644
+ i += INDEX_GAP_LENGTH;
645
+ }
646
+ this.#index2[i] = this.#map[this.#index2[i] >> SHIFT_2];
647
+ ++i;
648
+ }
649
+ this.#dataNullOffset = this.#map[this.#dataNullOffset >> SHIFT_2];
650
+ // ensure dataLength alignment
651
+ while ((newStart & (DATA_GRANULARITY - 1)) !== 0) {
652
+ this.#data[newStart++] = this.#initialValue;
653
+ }
654
+ this.#dataLength = newStart;
655
+ }
656
+ #compactIndex2() {
657
+ // do not compact linear-BMP index-2 blocks
658
+ let newStart = INDEX_2_BMP_LENGTH;
659
+ let start = 0;
660
+ let i = 0;
661
+ while (start < newStart) {
662
+ this.#map[i++] = start;
663
+ start += INDEX_2_BLOCK_LENGTH;
664
+ }
665
+ // Reduce the index table gap to what will be needed at runtime.
666
+ newStart += UTF8_2B_INDEX_2_LENGTH + ((this.#highStart - 0x10000) >> SHIFT_1);
667
+ start = INDEX_2_NULL_OFFSET;
668
+ while (start < this.#index2Length) {
669
+ // start: index of first entry of current block
670
+ // newStart: index where the current block is to be moved
671
+ // (right after current end of already-compacted data)
672
+ // search for an identical block
673
+ let movedStart;
674
+ if ((movedStart = this.#findSameIndex2Block(newStart, start)) >= 0) {
675
+ // found an identical block, set the other block's index value for the current block
676
+ this.#map[start >> SHIFT_1_2] = movedStart;
677
+ // advance start to the next block
678
+ start += INDEX_2_BLOCK_LENGTH;
679
+ // leave newStart with the previous block!
680
+ continue;
681
+ }
682
+ // see if the beginning of this block can be overlapped with the end of the previous block
683
+ // look for maximum overlap with the previous, adjacent block
684
+ let overlap = INDEX_2_BLOCK_LENGTH - 1;
685
+ while (overlap > 0 && !equal_int(this.#index2, newStart - overlap, start, overlap)) {
686
+ --overlap;
687
+ }
688
+ if (overlap > 0 || newStart < start) {
689
+ // some overlap, or just move the whole block
690
+ this.#map[start >> SHIFT_1_2] = newStart - overlap;
691
+ // move the non-overlapping indexes to their new positions
692
+ start += overlap;
693
+ for (i = INDEX_2_BLOCK_LENGTH - overlap; i > 0; i--) {
694
+ this.#index2[newStart++] = this.#index2[start++];
695
+ }
696
+ }
697
+ else {
698
+ // no overlap && newStart==start
699
+ this.#map[start >> SHIFT_1_2] = start;
700
+ start += INDEX_2_BLOCK_LENGTH;
701
+ newStart = start;
702
+ }
703
+ }
704
+ // now adjust the index-1 table
705
+ for (i = 0; i < INDEX_1_LENGTH; i++) {
706
+ this.#index1[i] = this.#map[this.#index1[i] >> SHIFT_1_2];
707
+ }
708
+ this.#index2NullOffset = this.#map[this.#index2NullOffset >> SHIFT_1_2];
709
+ // Ensure data table alignment:
710
+ // Needs to be granularity-aligned for 16-bit trie
711
+ // (so that dataMove will be down-shiftable),
712
+ // and 2-aligned for uint32_t data.
713
+ // Arbitrary value: 0x3fffc not possible for real data.
714
+ while ((newStart & ((DATA_GRANULARITY - 1) | 1)) !== 0) {
715
+ this.#index2[newStart++] = 0x0000ffff << INDEX_SHIFT;
716
+ }
717
+ this.#index2Length = newStart;
718
+ }
719
+ #compact() {
720
+ // find highStart and round it up
721
+ let highValue = this.get(0x10ffff);
722
+ let highStart = this.#findHighStart(highValue);
723
+ highStart = (highStart + (CP_PER_INDEX_1_ENTRY - 1)) & ~(CP_PER_INDEX_1_ENTRY - 1);
724
+ if (highStart === 0x110000) {
725
+ highValue = this.#errorValue;
726
+ }
727
+ // Set trie->highStart only after utrie2_get32(trie, highStart).
728
+ // Otherwise utrie2_get32(trie, highStart) would try to read the highValue.
729
+ this.#highStart = highStart;
730
+ if (this.#highStart < 0x110000) {
731
+ // Blank out [highStart..10ffff] to release associated data blocks.
732
+ const suppHighStart = this.#highStart <= 0x10000 ? 0x10000 : this.#highStart;
733
+ this.setRange(suppHighStart, 0x10ffff, this.#initialValue, true);
734
+ }
735
+ this.#compactData();
736
+ if (this.#highStart > 0x10000) {
737
+ this.#compactIndex2();
738
+ }
739
+ // Store the highValue in the data array and round up the dataLength.
740
+ // Must be done after compactData() because that assumes that dataLength
741
+ // is a multiple of DATA_BLOCK_LENGTH.
742
+ this.#data[this.#dataLength++] = highValue;
743
+ while ((this.#dataLength & (DATA_GRANULARITY - 1)) !== 0) {
744
+ this.#data[this.#dataLength++] = this.#initialValue;
745
+ }
746
+ this.#isCompacted = true;
747
+ }
748
+ freeze() {
749
+ let allIndexesLength, i;
750
+ if (!this.#isCompacted) {
751
+ this.#compact();
752
+ }
753
+ if (this.#highStart <= 0x10000) {
754
+ allIndexesLength = INDEX_1_OFFSET;
755
+ }
756
+ else {
757
+ allIndexesLength = this.#index2Length;
758
+ }
759
+ const dataMove = allIndexesLength;
760
+ // are indexLength and dataLength within limits?
761
+ if (allIndexesLength > MAX_INDEX_LENGTH || // for unshifted indexLength
762
+ dataMove + this.#dataNullOffset > 0xffff || // for unshifted dataNullOffset
763
+ dataMove + DATA_0800_OFFSET > 0xffff || // for unshifted 2-byte UTF-8 index-2 values
764
+ dataMove + this.#dataLength > MAX_DATA_LENGTH_RUNTIME) {
765
+ // for shiftedDataLength
766
+ throw new Error("Trie data is too large.");
767
+ }
768
+ // calculate the sizes of, and allocate, the index and data arrays
769
+ const indexLength = allIndexesLength + this.#dataLength;
770
+ const data = new Uint32Array(indexLength);
771
+ // write the index-2 array values shifted right by INDEX_SHIFT, after adding dataMove
772
+ let destIdx = 0;
773
+ for (i = 0; i < INDEX_2_BMP_LENGTH; i++) {
774
+ data[destIdx++] = (this.#index2[i] + dataMove) >> INDEX_SHIFT;
775
+ }
776
+ // write UTF-8 2-byte index-2 values, not right-shifted
777
+ for (i = 0; i < 0xc2 - 0xc0; i++) {
778
+ // C0..C1
779
+ data[destIdx++] = dataMove + BAD_UTF8_DATA_OFFSET;
780
+ }
781
+ for (; i < 0xe0 - 0xc0; i++) {
782
+ // C2..DF
783
+ data[destIdx++] = dataMove + this.#index2[i << (6 - SHIFT_2)];
784
+ }
785
+ if (this.#highStart > 0x10000) {
786
+ const index1Length = (this.#highStart - 0x10000) >> SHIFT_1;
787
+ const index2Offset = INDEX_2_BMP_LENGTH + UTF8_2B_INDEX_2_LENGTH + index1Length;
788
+ // write 16-bit index-1 values for supplementary code points
789
+ for (i = 0; i < index1Length; i++) {
790
+ data[destIdx++] = INDEX_2_OFFSET + this.#index1[i + OMITTED_BMP_INDEX_1_LENGTH];
791
+ }
792
+ // write the index-2 array values for supplementary code points,
793
+ // shifted right by INDEX_SHIFT, after adding dataMove
794
+ for (i = 0; i < this.#index2Length - index2Offset; i++) {
795
+ data[destIdx++] = (dataMove + this.#index2[index2Offset + i]) >> INDEX_SHIFT;
796
+ }
797
+ }
798
+ // write 16-bit data values
799
+ for (i = 0; i < this.#dataLength; i++) {
800
+ data[destIdx++] = this.#data[i];
801
+ }
802
+ const dest = UnicodeTrie.fromJSON({
803
+ data,
804
+ highStart: this.#highStart,
805
+ errorValue: this.#errorValue,
806
+ });
807
+ return dest;
808
+ }
809
+ // Generates a Buffer containing the serialized and compressed trie.
810
+ // Trie data is compressed twice using the deflate algorithm to minimize file size.
811
+ // Format:
812
+ // uint32_t highStart;
813
+ // uint32_t errorValue;
814
+ // uint32_t uncompressedDataLength;
815
+ // uint8_t trieData[dataLength];
816
+ async toBuffer() {
817
+ const trie = this.freeze();
818
+ const data = new Uint8Array(trie.data.buffer);
819
+ // swap bytes to little-endian
820
+ swap32LE(data);
821
+ let compressed = await deflate(data, "deflate-raw");
822
+ compressed = await deflate(compressed, "deflate-raw"); // NOTE: double deflate ??
823
+ const buf = Buffer.alloc(compressed.length + 12);
824
+ buf.writeUInt32LE(trie.highStart, 0);
825
+ buf.writeUInt32LE(trie.errorValue, 4);
826
+ buf.writeUInt32LE(data.length, 8);
827
+ for (let i = 0; i < compressed.length; i++) {
828
+ const b = compressed[i];
829
+ buf[i + 12] = b;
830
+ }
831
+ return buf;
832
+ }
833
+ }
834
+ export default UnicodeTrieBuilder;
835
+ //# sourceMappingURL=builder.js.map