-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.ts
692 lines (563 loc) · 18.3 KB
/
index.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/**
* @packageDocumentation
*
* A class that lets you do operations over a list of Uint8Arrays without
* copying them.
*
* ```js
* import { Uint8ArrayList } from 'uint8arraylist'
*
* const list = new Uint8ArrayList()
* list.append(Uint8Array.from([0, 1, 2]))
* list.append(Uint8Array.from([3, 4, 5]))
*
* list.subarray()
* // -> Uint8Array([0, 1, 2, 3, 4, 5])
*
* list.consume(3)
* list.subarray()
* // -> Uint8Array([3, 4, 5])
*
* // you can also iterate over the list
* for (const buf of list) {
* // ..do something with `buf`
* }
*
* list.subarray(0, 1)
* // -> Uint8Array([0])
* ```
*
* ## Converting Uint8ArrayLists to Uint8Arrays
*
* There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.
*
* ### slice
*
* Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.
*
* ```js
* const list = new Uint8ArrayList()
* list.append(Uint8Array.from([0, 1, 2]))
* list.append(Uint8Array.from([3, 4, 5]))
*
* list.slice(0, 1)
* // -> Uint8Array([0])
* ```
*
* ### subarray
*
* Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.
*
* ```js
* const list = new Uint8ArrayList()
* list.append(Uint8Array.from([0, 1, 2]))
* list.append(Uint8Array.from([3, 4, 5]))
*
* list.subarray(0, 1)
* // -> Uint8Array([0]) - no-copy
*
* list.subarray(2, 5)
* // -> Uint8Array([2, 3, 4]) - copy
* ```
*
* ### sublist
*
* Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.
*
* ```js
* const list = new Uint8ArrayList()
* list.append(Uint8Array.from([0, 1, 2]))
* list.append(Uint8Array.from([3, 4, 5]))
*
* list.sublist(0, 1)
* // -> Uint8ArrayList([0]) - no-copy
*
* list.sublist(2, 5)
* // -> Uint8ArrayList([2], [3, 4]) - no-copy
* ```
*
* ## Inspiration
*
* Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.
*/
import { allocUnsafe, alloc } from 'uint8arrays/alloc'
import { concat } from 'uint8arrays/concat'
import { equals } from 'uint8arrays/equals'
const symbol = Symbol.for('@achingbrain/uint8arraylist')
export type Appendable = Uint8ArrayList | Uint8Array
function findBufAndOffset (bufs: Uint8Array[], index: number): { buf: Uint8Array, index: number } {
if (index == null || index < 0) {
throw new RangeError('index is out of bounds')
}
let offset = 0
for (const buf of bufs) {
const bufEnd = offset + buf.byteLength
if (index < bufEnd) {
return {
buf,
index: index - offset
}
}
offset = bufEnd
}
throw new RangeError('index is out of bounds')
}
/**
* Check if object is a CID instance
*
* @example
*
* ```js
* import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'
*
* isUint8ArrayList(true) // false
* isUint8ArrayList([]) // false
* isUint8ArrayList(new Uint8ArrayList()) // true
* ```
*/
export function isUint8ArrayList (value: any): value is Uint8ArrayList {
return Boolean(value?.[symbol])
}
export class Uint8ArrayList implements Iterable<Uint8Array> {
private bufs: Uint8Array[]
public length: number
public readonly [symbol] = true
constructor (...data: Appendable[]) {
this.bufs = []
this.length = 0
if (data.length > 0) {
this.appendAll(data)
}
}
* [Symbol.iterator] (): Iterator<Uint8Array> {
yield * this.bufs
}
get byteLength (): number {
return this.length
}
/**
* Add one or more `bufs` to the end of this Uint8ArrayList
*/
append (...bufs: Appendable[]): void {
this.appendAll(bufs)
}
/**
* Add all `bufs` to the end of this Uint8ArrayList
*/
appendAll (bufs: Appendable[]): void {
let length = 0
for (const buf of bufs) {
if (buf instanceof Uint8Array) {
length += buf.byteLength
this.bufs.push(buf)
} else if (isUint8ArrayList(buf)) {
length += buf.byteLength
this.bufs.push(...buf.bufs)
} else {
throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList')
}
}
this.length += length
}
/**
* Add one or more `bufs` to the start of this Uint8ArrayList
*/
prepend (...bufs: Appendable[]): void {
this.prependAll(bufs)
}
/**
* Add all `bufs` to the start of this Uint8ArrayList
*/
prependAll (bufs: Appendable[]): void {
let length = 0
for (const buf of bufs.reverse()) {
if (buf instanceof Uint8Array) {
length += buf.byteLength
this.bufs.unshift(buf)
} else if (isUint8ArrayList(buf)) {
length += buf.byteLength
this.bufs.unshift(...buf.bufs)
} else {
throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList')
}
}
this.length += length
}
/**
* Read the value at `index`
*/
get (index: number): number {
const res = findBufAndOffset(this.bufs, index)
return res.buf[res.index]
}
/**
* Set the value at `index` to `value`
*/
set (index: number, value: number): void {
const res = findBufAndOffset(this.bufs, index)
res.buf[res.index] = value
}
/**
* Copy bytes from `buf` to the index specified by `offset`
*/
write (buf: Appendable, offset: number = 0): void {
if (buf instanceof Uint8Array) {
for (let i = 0; i < buf.length; i++) {
this.set(offset + i, buf[i])
}
} else if (isUint8ArrayList(buf)) {
for (let i = 0; i < buf.length; i++) {
this.set(offset + i, buf.get(i))
}
} else {
throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList')
}
}
/**
* Remove bytes from the front of the pool
*/
consume (bytes: number): void {
// first, normalize the argument, in accordance with how Buffer does it
bytes = Math.trunc(bytes)
// do nothing if not a positive number
if (Number.isNaN(bytes) || bytes <= 0) {
return
}
// if consuming all bytes, skip iterating
if (bytes === this.byteLength) {
this.bufs = []
this.length = 0
return
}
while (this.bufs.length > 0) {
if (bytes >= this.bufs[0].byteLength) {
bytes -= this.bufs[0].byteLength
this.length -= this.bufs[0].byteLength
this.bufs.shift()
} else {
this.bufs[0] = this.bufs[0].subarray(bytes)
this.length -= bytes
break
}
}
}
/**
* Extracts a section of an array and returns a new array.
*
* This is a copy operation as it is with Uint8Arrays and Arrays
* - note this is different to the behaviour of Node Buffers.
*/
slice (beginInclusive?: number, endExclusive?: number): Uint8Array {
const { bufs, length } = this._subList(beginInclusive, endExclusive)
return concat(bufs, length)
}
/**
* Returns a alloc from the given start and end element index.
*
* In the best case where the data extracted comes from a single Uint8Array
* internally this is a no-copy operation otherwise it is a copy operation.
*/
subarray (beginInclusive?: number, endExclusive?: number): Uint8Array {
const { bufs, length } = this._subList(beginInclusive, endExclusive)
if (bufs.length === 1) {
return bufs[0]
}
return concat(bufs, length)
}
/**
* Returns a allocList from the given start and end element index.
*
* This is a no-copy operation.
*/
sublist (beginInclusive?: number, endExclusive?: number): Uint8ArrayList {
const { bufs, length } = this._subList(beginInclusive, endExclusive)
const list = new Uint8ArrayList()
list.length = length
// don't loop, just set the bufs
list.bufs = [...bufs]
return list
}
private _subList (beginInclusive?: number, endExclusive?: number): { bufs: Uint8Array[], length: number } {
beginInclusive = beginInclusive ?? 0
endExclusive = endExclusive ?? this.length
if (beginInclusive < 0) {
beginInclusive = this.length + beginInclusive
}
if (endExclusive < 0) {
endExclusive = this.length + endExclusive
}
if (beginInclusive < 0 || endExclusive > this.length) {
throw new RangeError('index is out of bounds')
}
if (beginInclusive === endExclusive) {
return { bufs: [], length: 0 }
}
if (beginInclusive === 0 && endExclusive === this.length) {
return { bufs: this.bufs, length: this.length }
}
const bufs: Uint8Array[] = []
let offset = 0
for (let i = 0; i < this.bufs.length; i++) {
const buf = this.bufs[i]
const bufStart = offset
const bufEnd = bufStart + buf.byteLength
// for next loop
offset = bufEnd
if (beginInclusive >= bufEnd) {
// start after this buf
continue
}
const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd
const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd
if (sliceStartInBuf && sliceEndsInBuf) {
// slice is wholly contained within this buffer
if (beginInclusive === bufStart && endExclusive === bufEnd) {
// requested whole buffer
bufs.push(buf)
break
}
// requested part of buffer
const start = beginInclusive - bufStart
bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)))
break
}
if (sliceStartInBuf) {
// slice starts in this buffer
if (beginInclusive === 0) {
// requested whole buffer
bufs.push(buf)
continue
}
// requested part of buffer
bufs.push(buf.subarray(beginInclusive - bufStart))
continue
}
if (sliceEndsInBuf) {
if (endExclusive === bufEnd) {
// requested whole buffer
bufs.push(buf)
break
}
// requested part of buffer
bufs.push(buf.subarray(0, endExclusive - bufStart))
break
}
// slice started before this buffer and ends after it
bufs.push(buf)
}
return { bufs, length: endExclusive - beginInclusive }
}
indexOf (search: Uint8ArrayList | Uint8Array, offset: number = 0): number {
if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {
throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array')
}
const needle = search instanceof Uint8Array ? search : search.subarray()
offset = Number(offset ?? 0)
if (isNaN(offset)) {
offset = 0
}
if (offset < 0) {
offset = this.length + offset
}
if (offset < 0) {
offset = 0
}
if (search.length === 0) {
return offset > this.length ? this.length : offset
}
// https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm
const M: number = needle.byteLength
if (M === 0) {
throw new TypeError('search must be at least 1 byte long')
}
// radix
const radix: number = 256
const rightmostPositions: Int32Array = new Int32Array(radix)
// position of the rightmost occurrence of the byte c in the pattern
for (let c: number = 0; c < radix; c++) {
// -1 for bytes not in pattern
rightmostPositions[c] = -1
}
for (let j = 0; j < M; j++) {
// rightmost position for bytes in pattern
rightmostPositions[needle[j]] = j
}
// Return offset of first match, -1 if no match
const right = rightmostPositions
const lastIndex = this.byteLength - needle.byteLength
const lastPatIndex = needle.byteLength - 1
let skip: number
for (let i = offset; i <= lastIndex; i += skip) {
skip = 0
for (let j = lastPatIndex; j >= 0; j--) {
const char: number = this.get(i + j)
if (needle[j] !== char) {
skip = Math.max(1, j - right[char])
break
}
}
if (skip === 0) {
return i
}
}
return -1
}
getInt8 (byteOffset: number): number {
const buf = this.subarray(byteOffset, byteOffset + 1)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getInt8(0)
}
setInt8 (byteOffset: number, value: number): void {
const buf = allocUnsafe(1)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setInt8(0, value)
this.write(buf, byteOffset)
}
getInt16 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 2)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getInt16(0, littleEndian)
}
setInt16 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(2)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setInt16(0, value, littleEndian)
this.write(buf, byteOffset)
}
getInt32 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getInt32(0, littleEndian)
}
setInt32 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setInt32(0, value, littleEndian)
this.write(buf, byteOffset)
}
getBigInt64 (byteOffset: number, littleEndian?: boolean): bigint {
const buf = this.subarray(byteOffset, byteOffset + 8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getBigInt64(0, littleEndian)
}
setBigInt64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {
const buf = alloc(8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setBigInt64(0, value, littleEndian)
this.write(buf, byteOffset)
}
getUint8 (byteOffset: number): number {
const buf = this.subarray(byteOffset, byteOffset + 1)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getUint8(0)
}
setUint8 (byteOffset: number, value: number): void {
const buf = allocUnsafe(1)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setUint8(0, value)
this.write(buf, byteOffset)
}
getUint16 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 2)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getUint16(0, littleEndian)
}
setUint16 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(2)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setUint16(0, value, littleEndian)
this.write(buf, byteOffset)
}
getUint32 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getUint32(0, littleEndian)
}
setUint32 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setUint32(0, value, littleEndian)
this.write(buf, byteOffset)
}
getBigUint64 (byteOffset: number, littleEndian?: boolean): bigint {
const buf = this.subarray(byteOffset, byteOffset + 8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getBigUint64(0, littleEndian)
}
setBigUint64 (byteOffset: number, value: bigint, littleEndian?: boolean): void {
const buf = alloc(8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setBigUint64(0, value, littleEndian)
this.write(buf, byteOffset)
}
getFloat32 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getFloat32(0, littleEndian)
}
setFloat32 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(4)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setFloat32(0, value, littleEndian)
this.write(buf, byteOffset)
}
getFloat64 (byteOffset: number, littleEndian?: boolean): number {
const buf = this.subarray(byteOffset, byteOffset + 8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
return view.getFloat64(0, littleEndian)
}
setFloat64 (byteOffset: number, value: number, littleEndian?: boolean): void {
const buf = alloc(8)
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
view.setFloat64(0, value, littleEndian)
this.write(buf, byteOffset)
}
equals (other: any): other is Uint8ArrayList {
if (other == null) {
return false
}
if (!(other instanceof Uint8ArrayList)) {
return false
}
if (other.bufs.length !== this.bufs.length) {
return false
}
for (let i = 0; i < this.bufs.length; i++) {
if (!equals(this.bufs[i], other.bufs[i])) {
return false
}
}
return true
}
/**
* Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this
* method if you know the total size of all the Uint8Arrays ahead of time.
*/
static fromUint8Arrays (bufs: Uint8Array[], length?: number): Uint8ArrayList {
const list = new Uint8ArrayList()
list.bufs = bufs
if (length == null) {
length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0)
}
list.length = length
return list
}
}
/*
function indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {
for (let i = offset; i < haystack.byteLength; i++) {
for (let j = 0; j < needle.length; j++) {
if (haystack[i + j] !== needle[j]) {
break
}
if (j === needle.byteLength -1) {
return i
}
}
if (haystack.byteLength - i < needle.byteLength) {
break
}
}
return -1
}
*/