generated from okikio/transferables
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_arrays.ts
454 lines (405 loc) · 18.5 KB
/
_arrays.ts
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import { bytesToCodePoint, bytesToCodePointFromBuffer, codePointAt, getByteLength } from "../byte_methods.ts";
import { UTF8_MAX_BYTE_LENGTH } from "../constants.ts";
/**
* Iterate through iterables using `TextDecoder` (stream mode) and `String.protoype.codePointAt(...)` to get and return an array of codepoints
*/
export async function textDecoderArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
const iterator = Symbol.asyncIterator in iterable
? iterable[Symbol.asyncIterator]() :
Symbol.iterator in iterable
? iterable[Symbol.iterator]()
: iterable;
// Use a while loop to iterate over the async iterator.
while (true) {
const result = await iterator.next();
if (result.done) break;
const chunk = result.value;
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
const len = str.length;
for (let i = 0; i < len;) {
const codePoint = str.codePointAt(i)!;
if (codePoint !== undefined) {
arr.push(codePoint);
i += codePoint > 0xFFFF ? 2 : 1; // Adjust index based on code point size
}
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* Iterate through iterables using `TextDecoder` (stream mode) and `String.protoype.codePointAt(...)` to get and return an array of codepoints
*/
export async function ForTextDecoderArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
// Use a while loop to iterate over the async iterator.
for await (const chunk of iterable) {
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
let i = 0;
const size = str.length;
while (i < size) {
const codePoint = str.codePointAt(i)!;
arr.push(codePoint);
i += codePoint > 0xFFFF ? 2 : 1; // Adjust index based on code point size
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* `textDecoderArray` but use the custom `codePointAt(...)` method instead of `String.protoype.codePointAt(...)`
*/
export async function textDecoderCustomCodePointAtArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
const iterator = Symbol.asyncIterator in iterable
? iterable[Symbol.asyncIterator]() :
Symbol.iterator in iterable
? iterable[Symbol.iterator]()
: iterable;
// Use a while loop to iterate over the async iterator.
while (true) {
const result = await iterator.next();
if (result.done) break;
const chunk = result.value;
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
let i = 0;
while (i < str.length) {
const codePoint = codePointAt(str, i);
if (codePoint === undefined) break; // If codePointAt returns undefined, break the loop.
arr.push(codePoint);
// Increment the index based on the size of the character (1 for BMP characters, 2 for others).
if (codePoint > 0xFFFF) i += 2; // Surrogate pairs take up two units.
else i++; // Regular characters take up one unit.
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* `textDecoderArray` but use the custom `codePointAt(...)` method instead of `String.protoype.codePointAt(...)`
*/
export async function ForTextDecoderCustomCodePointAtArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
// Use a while loop to iterate over the async iterator.
for await (const chunk of iterable) {
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
let i = 0;
while (i < str.length) {
const codePoint = codePointAt(str, i);
if (codePoint === undefined) break; // If codePointAt returns undefined, break the loop.
arr.push(codePoint);
// Increment the index based on the size of the character (1 for BMP characters, 2 for others).
if (codePoint > 0xFFFF) i += 2; // Surrogate pairs take up two units.
else i++; // Regular characters take up one unit.
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* `textDecoderArray` but more complex, hopefully faster
*
* Converts an iterable of UTF-8 filled Uint8Array's into an async generator of Unicode code points.
*
* The function iterates through the input iterable, which yields chunks of bytes (Uint8Array).
* It processes each chunk to extract UTF-8 characters and calculate their corresponding Unicode code points.
* The code points are then yielded one by one.
*
* What's happening here is the optimized version of https://gist.github.com/okikio/6eb88f317ceeb2146b8268a255744fc6#file-uint8array-to-utf-8-ts
*
* In simpler terms:
*
* 1. Iterate through the iterable
* 2. Grab the Uint8Array chunk from the iterable (it doesn't have to be a Uint8Array, but the default expected value is Uint8Array)
* 3. Get the number of bytes required to represent a specific utf-8 character (utf-8 characters can range from 1 to 4 bytes)
* 4. Loop through the Uint8Array chunk til you find all the bytes required for a utf-8 character
* a. If the last couple of bytes for a character span multiple 2 or more chunks
* b. Store the current gathered utf-8 character bytes til the full list of bytes have been acquired from other chunks
* 5. Yield utf-8 character codepoint
* 6. Go through steps 1 - 5, til you've gone through all chunks in the iterable
*
* @param iterable - Iterator or async iterator of UTF-8 filled Uint8Array's.
* @returns An async generator that yields Unicode code points.
*/
export async function textDecoderComplexArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
const iterator = Symbol.asyncIterator in iterable
? iterable[Symbol.asyncIterator]() :
Symbol.iterator in iterable
? iterable[Symbol.iterator]()
: iterable;
// Use a while loop to iterate over the async iterator.
while (true) {
const result = await iterator.next();
if (result.done) { break; }
const chunk = result.value;
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
let i = 0;
const size = str.length;
while (i < size) {
const first = str.charCodeAt(i);
if (
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > i + 1 // there is a next code unit
) {
const second = str.charCodeAt(i + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// Calculate the code point using the surrogate pair formula
const codePoint = ((first - 0xD800) << 10) + (second - 0xDC00) + 0x10000;
arr.push(codePoint);
i++; // Skip the next code unit (part of the surrogate pair)
} else {
// Unmatched high surrogate, treat it as an individual code point
arr.push(first);
}
} else {
// Regular code point (not part of a surrogate pair)
arr.push(first);
}
++i; // Use the ++i increment operator
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* `textDecoderArray` but more complex, hopefully faster
*
* Converts an iterable of UTF-8 filled Uint8Array's into an async generator of Unicode code points.
*
* The function iterates through the input iterable, which yields chunks of bytes (Uint8Array).
* It processes each chunk to extract UTF-8 characters and calculate their corresponding Unicode code points.
* The code points are then yielded one by one.
*
* What's happening here is the optimized version of https://gist.github.com/okikio/6eb88f317ceeb2146b8268a255744fc6#file-uint8array-to-utf-8-ts
*
* In simpler terms:
*
* 1. Iterate through the iterable
* 2. Grab the Uint8Array chunk from the iterable (it doesn't have to be a Uint8Array, but the default expected value is Uint8Array)
* 3. Get the number of bytes required to represent a specific utf-8 character (utf-8 characters can range from 1 to 4 bytes)
* 4. Loop through the Uint8Array chunk til you find all the bytes required for a utf-8 character
* a. If the last couple of bytes for a character span multiple 2 or more chunks
* b. Store the current gathered utf-8 character bytes til the full list of bytes have been acquired from other chunks
* 5. Yield utf-8 character codepoint
* 6. Go through steps 1 - 5, til you've gone through all chunks in the iterable
*
* @param iterable - Iterator or async iterator of UTF-8 filled Uint8Array's.
* @returns An async generator that yields Unicode code points.
*/
export async function ForTextDecoderComplexArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
const utf8Decoder = new TextDecoder("utf-8");
// Create an async iterator from the source (works for both async and sync iterables).
// Use a while loop to iterate over the async iterator.
for await (const chunk of iterable) {
const str = utf8Decoder.decode(chunk, { stream: true });
// Extract code points in larger batches
let i = 0;
const size = str.length;
while (i < size) {
const first = str.charCodeAt(i);
if (
first >= 0xD800 && first <= 0xDBFF && // high surrogate
size > i + 1 // there is a next code unit
) {
const second = str.charCodeAt(i + 1);
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
// Calculate the code point using the surrogate pair formula
const codePoint = ((first - 0xD800) << 10) + (second - 0xDC00) + 0x10000;
arr.push(codePoint);
i++; // Skip the next code unit (part of the surrogate pair)
} else {
// Unmatched high surrogate, treat it as an individual code point
arr.push(first);
}
} else {
// Regular code point (not part of a surrogate pair)
arr.push(first);
}
++i; // Use the ++i increment operator
}
}
// Flush the decoder's internal state
utf8Decoder.decode(new Uint8Array());
return arr;
}
/**
* Use a constant size `Uint8Array` as a buffer window to write and read, to get the utf-8 codepoints
*
* Converts an iterable of UTF-8 filled Uint8Array's into an async generator of Unicode code points.
*
* The function iterates through the input iterable, which yields chunks of bytes (Uint8Array).
* It processes each chunk to extract UTF-8 characters and calculate their corresponding Unicode code points.
* The code points are then yielded one by one.
*
* What's happening here is the optimized version of https://gist.github.com/okikio/6eb88f317ceeb2146b8268a255744fc6#file-uint8array-to-utf-8-ts
*
* In simpler terms:
*
* 1. Iterate through the iterable
* 2. Grab the Uint8Array chunk from the iterable (it doesn't have to be a Uint8Array, but the default expected value is Uint8Array)
* 3. Get the number of bytes required to represent a specific utf-8 character (utf-8 characters can range from 1 to 4 bytes)
* 4. Loop through the Uint8Array chunk til you find all the bytes required for a utf-8 character
* a. If the last couple of bytes for a character span multiple 2 or more chunks
* b. Store the current gathered utf-8 character bytes til the full list of bytes have been acquired from other chunks
* 5. Yield utf-8 character codepoint
* 6. Go through steps 1 - 5, til you've gone through all chunks in the iterable
*
* @param iterable - Iterator or async iterator of UTF-8 filled Uint8Array's.
* @returns An async generator that yields Unicode code points.
*/
export async function asCodePointsBufferWindowArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
/**
* - `byteSequence` stores the bytes of the current UTF-8 character being processed.
* - `byteSequenceRemainingBytes` keeps track of the remaining bytes needed for the current UTF-8 character.
*/
const byteSequence = new Uint8Array(UTF8_MAX_BYTE_LENGTH);
let byteSequenceRemainingBytes = 0;
// Create an async iterator from the source (works for both async and sync iterables).
const iterator = Symbol.asyncIterator in iterable
? iterable[Symbol.asyncIterator]() :
Symbol.iterator in iterable
? iterable[Symbol.iterator]()
: iterable;
let head = 0; // Head pointer (start position)
let tail = 0; // Tail pointer (end position)
while (true) {
const result = await iterator.next();
if (result.done) break;
const chunk = result.value;
const len = chunk.length;
for (let i = 0; i < len; ++i) {
const byte = chunk[i];
byteSequence[tail] = byte;
tail = (tail + 1) % UTF8_MAX_BYTE_LENGTH; // Circular buffer
// If `byteSequenceRemainingBytes` is zero, it means we are at the start of a new UTF-8 character.
// We calculate the number of bytes required for this character using `getByteLength`.
if (byteSequenceRemainingBytes === 0) {
byteSequenceRemainingBytes = getByteLength(byte) - 1;
} else {
// Decrement `byteSequenceRemainingBytes` as we process each byte of the current UTF-8 character.
--byteSequenceRemainingBytes;
}
// When `byteSequenceRemainingBytes` reaches zero, we have collected all the bytes needed for the current UTF-8 character.
// We calculate and yield its code point using `bytesToCodePoint`.
if (byteSequenceRemainingBytes === 0) {
// Calculate code point from buffer
const byteLength = (tail - head + UTF8_MAX_BYTE_LENGTH) % UTF8_MAX_BYTE_LENGTH || UTF8_MAX_BYTE_LENGTH;
arr.push(bytesToCodePointFromBuffer(byteLength, byteSequence, head));
head = tail; // Move head pointer to the current tail pointer
}
}
}
if (head !== tail) {
// Calculate code point for the last UTF-8 character in buffer
const byteLength = (tail - head + UTF8_MAX_BYTE_LENGTH) % UTF8_MAX_BYTE_LENGTH || UTF8_MAX_BYTE_LENGTH;
arr.push(bytesToCodePointFromBuffer(byteLength, byteSequence, head));
}
return arr;
}
/**
* Use a constant size `Uint8Array` as a buffer window to write and read, to get the utf-8 codepoints
*
* Converts an iterable of UTF-8 filled Uint8Array's into an async generator of Unicode code points.
*
* The function iterates through the input iterable, which yields chunks of bytes (Uint8Array).
* It processes each chunk to extract UTF-8 characters and calculate their corresponding Unicode code points.
* The code points are then yielded one by one.
*
* What's happening here is the optimized version of https://gist.github.com/okikio/6eb88f317ceeb2146b8268a255744fc6#file-uint8array-to-utf-8-ts
*
* In simpler terms:
*
* 1. Iterate through the iterable
* 2. Grab the Uint8Array chunk from the iterable (it doesn't have to be a Uint8Array, but the default expected value is Uint8Array)
* 3. Get the number of bytes required to represent a specific utf-8 character (utf-8 characters can range from 1 to 4 bytes)
* 4. Loop through the Uint8Array chunk til you find all the bytes required for a utf-8 character
* a. If the last couple of bytes for a character span multiple 2 or more chunks
* b. Store the current gathered utf-8 character bytes til the full list of bytes have been acquired from other chunks
* 5. Yield utf-8 character codepoint
* 6. Go through steps 1 - 5, til you've gone through all chunks in the iterable
*
* @param iterable - Iterator or async iterator of UTF-8 filled Uint8Array's.
* @returns An async generator that yields Unicode code points.
*/
export async function ForAsCodePointsBufferWindowArray<T extends Uint8Array>(
iterable: AsyncIterable<T> | Iterable<T>
) {
const arr: number[] = [];
/**
* - `byteSequence` stores the bytes of the current UTF-8 character being processed.
* - `byteSequenceRemainingBytes` keeps track of the remaining bytes needed for the current UTF-8 character.
*/
const byteSequence = new Uint8Array(UTF8_MAX_BYTE_LENGTH);
let byteSequenceRemainingBytes = 0;
let head = 0; // Head pointer (start position)
let tail = 0; // Tail pointer (end position)
// Create an async iterator from the source (works for both async and sync iterables).
for await (const chunk of iterable) {
const len = chunk.length;
for (let i = 0; i < len; ++i) {
const byte = chunk[i];
byteSequence[tail] = byte;
tail = (tail + 1) % UTF8_MAX_BYTE_LENGTH; // Circular buffer
// If `byteSequenceRemainingBytes` is zero, it means we are at the start of a new UTF-8 character.
// We calculate the number of bytes required for this character using `getByteLength`.
if (byteSequenceRemainingBytes === 0) {
byteSequenceRemainingBytes = getByteLength(byte) - 1;
} else {
// Decrement `byteSequenceRemainingBytes` as we process each byte of the current UTF-8 character.
--byteSequenceRemainingBytes;
}
// When `byteSequenceRemainingBytes` reaches zero, we have collected all the bytes needed for the current UTF-8 character.
// We calculate and yield its code point using `bytesToCodePoint`.
if (byteSequenceRemainingBytes === 0) {
// Calculate code point from buffer
const byteLength = (tail - head + UTF8_MAX_BYTE_LENGTH) % UTF8_MAX_BYTE_LENGTH || UTF8_MAX_BYTE_LENGTH;
arr.push(bytesToCodePointFromBuffer(byteLength, byteSequence, head));
head = tail; // Move head pointer to the current tail pointer
}
}
}
if (head !== tail) {
// Calculate code point for the last UTF-8 character in buffer
const byteLength = (tail - head + UTF8_MAX_BYTE_LENGTH) % UTF8_MAX_BYTE_LENGTH || UTF8_MAX_BYTE_LENGTH;
arr.push(bytesToCodePointFromBuffer(byteLength, byteSequence, head));
}
return arr;
}