@netifyjs/netify 0.0.0-stage → 1.0.0-alpha.1

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.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/package.json +65 -4
  4. package/src/bootstrap/client/index.ts +191 -0
  5. package/src/bootstrap/dispatcher/index.ts +204 -0
  6. package/src/bootstrap/index.ts +22 -0
  7. package/src/bootstrap/reconnect/index.ts +334 -0
  8. package/src/bootstrap/server/index.ts +284 -0
  9. package/src/buffer/bits/index.ts +2 -0
  10. package/src/buffer/bits/reader/index.ts +64 -0
  11. package/src/buffer/bits/writer/index.ts +79 -0
  12. package/src/buffer/index.ts +1375 -0
  13. package/src/buffer/pool/index.ts +46 -0
  14. package/src/buffer/quantizer/index.ts +101 -0
  15. package/src/channel/attribute/index.ts +89 -0
  16. package/src/channel/context/index.ts +621 -0
  17. package/src/channel/group/index.ts +256 -0
  18. package/src/channel/handler/duplex/index.ts +105 -0
  19. package/src/channel/handler/inbound/index.ts +78 -0
  20. package/src/channel/handler/index.ts +135 -0
  21. package/src/channel/handler/outbound/index.ts +33 -0
  22. package/src/channel/index.ts +619 -0
  23. package/src/channel/initializer/index.ts +77 -0
  24. package/src/channel/outbound/index.ts +611 -0
  25. package/src/channel/pipeline/head/index.ts +100 -0
  26. package/src/channel/pipeline/index.ts +414 -0
  27. package/src/channel/pipeline/tail/index.ts +45 -0
  28. package/src/channel/pipeline/tracker/index.ts +120 -0
  29. package/src/channel/queue/index.ts +203 -0
  30. package/src/channel/resolved/index.ts +34 -0
  31. package/src/channel/server/index.ts +164 -0
  32. package/src/channel/shutdown/index.ts +25 -0
  33. package/src/channel/simple/index.ts +38 -0
  34. package/src/channel/transport/index.ts +74 -0
  35. package/src/channel/transport/socket/index.ts +80 -0
  36. package/src/cluster/index.ts +360 -0
  37. package/src/codec/binary/index.ts +102 -0
  38. package/src/codec/decoder/index.ts +479 -0
  39. package/src/codec/delimiter/index.ts +189 -0
  40. package/src/codec/encoder/index.ts +48 -0
  41. package/src/codec/error/index.ts +33 -0
  42. package/src/codec/fixed/index.ts +45 -0
  43. package/src/codec/http/aggregator/index.ts +236 -0
  44. package/src/codec/http/client/index.ts +120 -0
  45. package/src/codec/http/decoder/index.ts +4 -0
  46. package/src/codec/http/decoder/object/index.ts +644 -0
  47. package/src/codec/http/decoder/request/index.ts +49 -0
  48. package/src/codec/http/decoder/response/index.ts +59 -0
  49. package/src/codec/http/encoder/index.ts +3 -0
  50. package/src/codec/http/encoder/object/index.ts +196 -0
  51. package/src/codec/http/encoder/request/index.ts +24 -0
  52. package/src/codec/http/encoder/response/index.ts +26 -0
  53. package/src/codec/http/headers/index.ts +287 -0
  54. package/src/codec/http/index.ts +33 -0
  55. package/src/codec/http/message/content/index.ts +36 -0
  56. package/src/codec/http/message/full/index.ts +10 -0
  57. package/src/codec/http/message/full/request/index.ts +45 -0
  58. package/src/codec/http/message/full/response/index.ts +43 -0
  59. package/src/codec/http/message/head/index.ts +79 -0
  60. package/src/codec/http/message/index.ts +16 -0
  61. package/src/codec/http/message/last/index.ts +27 -0
  62. package/src/codec/http/message/request/index.ts +39 -0
  63. package/src/codec/http/message/response/index.ts +31 -0
  64. package/src/codec/http/method/index.ts +101 -0
  65. package/src/codec/http/server/index.ts +81 -0
  66. package/src/codec/http/status/index.ts +170 -0
  67. package/src/codec/http/version/index.ts +70 -0
  68. package/src/codec/index.ts +83 -0
  69. package/src/codec/length/index.ts +330 -0
  70. package/src/codec/line/index.ts +45 -0
  71. package/src/codec/message/decoder/index.ts +84 -0
  72. package/src/codec/message/encoder/index.ts +56 -0
  73. package/src/codec/message/index.ts +2 -0
  74. package/src/codec/msgpack/index.ts +51 -0
  75. package/src/codec/prepender/index.ts +296 -0
  76. package/src/codec/protobuf/index.ts +57 -0
  77. package/src/codec/string/decoder/index.ts +47 -0
  78. package/src/codec/string/encoder/index.ts +26 -0
  79. package/src/codec/string/index.ts +2 -0
  80. package/src/codec/websocket/client/index.ts +235 -0
  81. package/src/codec/websocket/decoder/index.ts +371 -0
  82. package/src/codec/websocket/encoder/index.ts +170 -0
  83. package/src/codec/websocket/error/index.ts +42 -0
  84. package/src/codec/websocket/frame/base/index.ts +55 -0
  85. package/src/codec/websocket/frame/binary/index.ts +24 -0
  86. package/src/codec/websocket/frame/close/index.ts +82 -0
  87. package/src/codec/websocket/frame/continuation/index.ts +31 -0
  88. package/src/codec/websocket/frame/index.ts +10 -0
  89. package/src/codec/websocket/frame/opcode/index.ts +35 -0
  90. package/src/codec/websocket/frame/ping/index.ts +24 -0
  91. package/src/codec/websocket/frame/pong/index.ts +24 -0
  92. package/src/codec/websocket/frame/text/index.ts +31 -0
  93. package/src/codec/websocket/handshake/index.ts +38 -0
  94. package/src/codec/websocket/index.ts +25 -0
  95. package/src/codec/websocket/key/index.ts +41 -0
  96. package/src/codec/websocket/protocol/index.ts +147 -0
  97. package/src/codec/websocket/server/index.ts +233 -0
  98. package/src/codec/websocket/status/index.ts +97 -0
  99. package/src/codec/websocket/upgrade/index.ts +116 -0
  100. package/src/datagram/bootstrap/index.ts +269 -0
  101. package/src/datagram/channel/index.ts +103 -0
  102. package/src/datagram/index.ts +10 -0
  103. package/src/datagram/packet/index.ts +72 -0
  104. package/src/datagram/transport/index.ts +239 -0
  105. package/src/handler/flush/index.ts +187 -0
  106. package/src/handler/idle/index.ts +295 -0
  107. package/src/handler/index.ts +22 -0
  108. package/src/handler/logging/index.ts +195 -0
  109. package/src/handler/metrics/index.ts +300 -0
  110. package/src/handler/offload/index.ts +141 -0
  111. package/src/handler/timeout/error/index.ts +29 -0
  112. package/src/handler/timeout/index.ts +3 -0
  113. package/src/handler/timeout/read/index.ts +44 -0
  114. package/src/handler/timeout/write/index.ts +89 -0
  115. package/src/handler/traffic/index.ts +259 -0
  116. package/src/index.ts +258 -0
  117. package/src/logger/index.ts +47 -0
  118. package/src/reliable/bootstrap/index.ts +154 -0
  119. package/src/reliable/cipher/index.ts +227 -0
  120. package/src/reliable/cookie/index.ts +78 -0
  121. package/src/reliable/handler/index.ts +1202 -0
  122. package/src/reliable/handshake/index.ts +144 -0
  123. package/src/reliable/index.ts +38 -0
  124. package/src/reliable/lane/index.ts +420 -0
  125. package/src/reliable/message/index.ts +102 -0
  126. package/src/reliable/packet/index.ts +117 -0
  127. package/src/reliable/peer/index.ts +929 -0
  128. package/src/reliable/registry/index.ts +107 -0
  129. package/src/serve/bootstrap/index.ts +606 -0
  130. package/src/serve/channel/index.ts +246 -0
  131. package/src/serve/index.ts +17 -0
  132. package/src/serve/outbox/index.ts +292 -0
  133. package/src/serve/transport/index.ts +96 -0
  134. package/src/serve/writer/index.ts +119 -0
  135. package/src/shard/envelope/index.ts +44 -0
  136. package/src/shard/gateway/index.ts +119 -0
  137. package/src/shard/index.ts +11 -0
  138. package/src/shard/link/index.ts +743 -0
  139. package/src/shard/map/index.ts +91 -0
  140. package/src/worker/group/index.ts +175 -0
  141. package/src/worker/index.ts +10 -0
  142. package/src/worker/pool/index.ts +235 -0
  143. package/src/worker/service/index.ts +55 -0
@@ -0,0 +1,1375 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ import type { ByteBufPool } from './pool/index.ts'
4
+
5
+ /**
6
+ * Network order is big, which is the default everywhere here
7
+ */
8
+ export type Endian = 'big' | 'little'
9
+
10
+ /**
11
+ * Growable byte buffer with separate read and write positions, modelled on Netty's
12
+ * @class
13
+ */
14
+ export class ByteBuf {
15
+ /**
16
+ * Starting size for allocate when you don't pass one
17
+ */
18
+ public static readonly defaultCapacity: number = 256
19
+
20
+ /**
21
+ * Shared backing for pooled buffers that hold nothing yet
22
+ */
23
+ private static readonly empty: Uint8Array = new Uint8Array(0)
24
+
25
+ /**
26
+ * Stands in for the bytes of a released frame and throws on any use
27
+ */
28
+ private static readonly released: Uint8Array = new Proxy<Uint8Array>(
29
+ new Uint8Array(0),
30
+ {
31
+ /**
32
+ * Every lookup is a use after release
33
+ */
34
+ get: (): never => {
35
+ throw new Error('Frame was released')
36
+ },
37
+ },
38
+ )
39
+
40
+ /**
41
+ * Released frames throw on use instead of being reused, set by NETIFY_DEBUG_FRAMES
42
+ */
43
+ public static debugFrames: boolean = Bun.env.NETIFY_DEBUG_FRAMES === '1'
44
+
45
+ /**
46
+ * Largest a buffer can grow by default, 64 MiB, pass more to allocate if you need it
47
+ */
48
+ public static readonly defaultMaxCapacity: number = 64 * 1024 * 1024
49
+
50
+ /**
51
+ * One encoder for every buffer, they're stateless
52
+ */
53
+ private static readonly encoder: TextEncoder = new TextEncoder()
54
+
55
+ /**
56
+ * One decoder for every buffer, only used for whole strings
57
+ */
58
+ private static readonly decoder: TextDecoder = new TextDecoder()
59
+
60
+ /**
61
+ * Underlying bytes, swapped for a bigger array when we grow
62
+ */
63
+ private storage: Uint8Array
64
+
65
+ /**
66
+ * Built lazily for the 64 bit and float accessors, dropped on grow
67
+ */
68
+ private view: DataView | null
69
+
70
+ /**
71
+ * Next byte a read will return
72
+ */
73
+ private readerPosition: number
74
+
75
+ /**
76
+ * Next byte a write will fill, everything before it is data
77
+ */
78
+ private writerPosition: number
79
+
80
+ /**
81
+ * Saved by markReaderIndex so a decoder can rewind
82
+ */
83
+ private markedReaderPosition: number
84
+
85
+ /**
86
+ * Hard cap on growth
87
+ */
88
+ private limit: number
89
+
90
+ /**
91
+ * Where this buffer starts in storage, above 0 for slices
92
+ */
93
+ private base: number
94
+
95
+ /**
96
+ * Where this buffer ends in storage
97
+ */
98
+ private end: number
99
+
100
+ /**
101
+ * Reference count, it goes back to its pool at zero
102
+ */
103
+ private refs: number
104
+
105
+ /**
106
+ * Pool it came from, or null
107
+ */
108
+ private home: ByteBufPool | null
109
+
110
+ /**
111
+ * Prefer allocate, wrap or fromString, this one's mostly for internal use
112
+ * @param storage bytes to sit on top of, not copied
113
+ * @param writerIndex how many of those bytes are already data
114
+ * @param maxCapacity how far it may grow
115
+ * @param base where it starts in storage, 0 unless it's a slice
116
+ * @param end where it ends in storage, the end of storage unless it's a slice
117
+ */
118
+ public constructor(
119
+ storage: Uint8Array,
120
+ writerIndex: number,
121
+ maxCapacity: number,
122
+ base = 0,
123
+ end: number = storage.length,
124
+ ) {
125
+ ByteBuf.check(storage, writerIndex, maxCapacity, base, end)
126
+
127
+ this.storage = storage
128
+ this.view = null
129
+ this.readerPosition = 0
130
+ this.writerPosition = writerIndex
131
+ this.markedReaderPosition = 0
132
+ this.limit = maxCapacity
133
+ this.base = base
134
+ this.end = end
135
+ this.refs = 1
136
+ this.home = null
137
+ }
138
+
139
+ /**
140
+ * Empty buffer that belongs to a pool, for sliceInto to fill
141
+ * @param pool where release hands it back
142
+ */
143
+ public static forPool(pool: ByteBufPool): ByteBuf {
144
+ const buffer = new ByteBuf(ByteBuf.empty, 0, 0)
145
+
146
+ buffer.home = pool
147
+ buffer.refs = 0
148
+ return buffer
149
+ }
150
+
151
+ /**
152
+ * How many owners it has
153
+ */
154
+ public get refCnt(): number {
155
+ return this.refs
156
+ }
157
+
158
+ /**
159
+ * Whether release hands it back to a pool
160
+ */
161
+ public get pooled(): boolean {
162
+ return this.home !== null
163
+ }
164
+
165
+ /**
166
+ * Adds an owner, so it isn't reused while you hold it
167
+ */
168
+ public retain(): this {
169
+ if (this.refs <= 0 && this.home !== null) {
170
+ throw new Error('Frame was released')
171
+ }
172
+
173
+ this.refs += 1
174
+ return this
175
+ }
176
+
177
+ /**
178
+ * Drops an owner and goes back to its pool at zero, true if that was the last
179
+ */
180
+ public release(): boolean {
181
+ if (this.refs <= 0) return false
182
+ this.refs -= 1
183
+ if (this.refs > 0) return false
184
+
185
+ const home = this.home
186
+ if (home === null) return true
187
+ if (ByteBuf.debugFrames) {
188
+ this.storage = ByteBuf.released
189
+ this.view = null
190
+ } else {
191
+ home.give(this)
192
+ }
193
+
194
+ return true
195
+ }
196
+
197
+ /**
198
+ * Leaves its pool for good, so nothing can reuse it
199
+ */
200
+ public detach(): this {
201
+ this.home = null
202
+ return this
203
+ }
204
+
205
+ /**
206
+ * Fresh, empty buffer that grows as you write
207
+ * @param capacity bytes to start with
208
+ * @param maxCapacity growth cap
209
+ */
210
+ public static allocate(
211
+ capacity: number = ByteBuf.defaultCapacity,
212
+ maxCapacity: number = ByteBuf.defaultMaxCapacity,
213
+ ): ByteBuf {
214
+ return new ByteBuf(new Uint8Array(capacity), 0, maxCapacity)
215
+ }
216
+
217
+ /**
218
+ * Zero-copy, so changes to the array show up in the buffer and back
219
+ * @param bytes all of it counts as readable
220
+ */
221
+ public static wrap(bytes: Uint8Array): ByteBuf {
222
+ return new ByteBuf(bytes, bytes.length, ByteBuf.defaultMaxCapacity)
223
+ }
224
+
225
+ /**
226
+ * Like wrap, but points an existing buffer at the bytes instead of making one
227
+ * @param bytes all of it counts as readable
228
+ * @param target the buffer to reuse
229
+ */
230
+ public static wrapInto(bytes: Uint8Array, target: ByteBuf): ByteBuf {
231
+ target.storage = bytes
232
+ target.view = null
233
+ target.readerPosition = 0
234
+ target.writerPosition = bytes.length
235
+ target.markedReaderPosition = 0
236
+ target.limit = bytes.length
237
+ target.base = 0
238
+ target.end = bytes.length
239
+ target.refs = 1
240
+ return target
241
+ }
242
+
243
+ /**
244
+ * UTF-8 encodes the string into a new buffer
245
+ * @param value text to encode
246
+ */
247
+ public static fromString(value: string): ByteBuf {
248
+ return ByteBuf.wrap(ByteBuf.encoder.encode(value))
249
+ }
250
+
251
+ /**
252
+ * Throws if the constructor's arguments don't fit
253
+ * @param storage the bytes
254
+ * @param writerIndex how many are data
255
+ * @param maxCapacity growth cap
256
+ * @param base start in storage
257
+ * @param end end in storage
258
+ */
259
+ private static check(
260
+ storage: Uint8Array,
261
+ writerIndex: number,
262
+ maxCapacity: number,
263
+ base: number,
264
+ end: number,
265
+ ): void {
266
+ const size = end - base
267
+ const reason =
268
+ writerIndex === size ? null : ByteBuf.refusal(writerIndex, 0, 0, size)
269
+ if (reason !== null) throw new RangeError(reason)
270
+ if (maxCapacity < size) throw new RangeError('Capacity is exceeded')
271
+ if (base < 0 || end > storage.length) {
272
+ throw new RangeError('Index is out of range')
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Error text if the range isn't integral or falls outside the bounds, or null
278
+ * @param index where the range starts
279
+ * @param size how long it is
280
+ * @param lower smallest start allowed
281
+ * @param upper end can't go past this
282
+ */
283
+ private static refusal(
284
+ index: number,
285
+ size: number,
286
+ lower: number,
287
+ upper: number,
288
+ ): string | null {
289
+ if (!Number.isInteger(index) || !Number.isInteger(size)) {
290
+ return 'Index is not an integer'
291
+ }
292
+
293
+ if (size < 0) return 'Size is negative'
294
+ if (index < lower || index + size > upper) return 'Index is out of range'
295
+
296
+ return null
297
+ }
298
+
299
+ /**
300
+ * DataView over exactly the array's slice of its ArrayBuffer
301
+ * @param bytes the array to view
302
+ */
303
+ private static viewOf(bytes: Uint8Array): DataView {
304
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
305
+ }
306
+
307
+ /**
308
+ * The backing bytes, like Netty's array(), index 0 of this buffer sits at arrayOffset
309
+ */
310
+ public get array(): Uint8Array {
311
+ return this.storage
312
+ }
313
+
314
+ /**
315
+ * Where index 0 of this buffer sits in array
316
+ */
317
+ public get arrayOffset(): number {
318
+ return this.base
319
+ }
320
+
321
+ /**
322
+ * Where the next read starts
323
+ */
324
+ public get readerIndex(): number {
325
+ return this.readerPosition
326
+ }
327
+
328
+ /**
329
+ * Can't go past writerIndex
330
+ * @param value new read position
331
+ */
332
+ public set readerIndex(value: number) {
333
+ const reason = ByteBuf.refusal(value, 0, 0, this.writerPosition)
334
+ if (reason !== null) throw new RangeError(reason)
335
+
336
+ this.readerPosition = value
337
+ }
338
+
339
+ /**
340
+ * Where the next write lands
341
+ */
342
+ public get writerIndex(): number {
343
+ return this.writerPosition
344
+ }
345
+
346
+ /**
347
+ * Has to stay between readerIndex and capacity, so it won't grow the buffer
348
+ * @param value new write position
349
+ */
350
+ public set writerIndex(value: number) {
351
+ const reason = ByteBuf.refusal(
352
+ value,
353
+ 0,
354
+ this.readerPosition,
355
+ this.end - this.base,
356
+ )
357
+ if (reason !== null) throw new RangeError(reason)
358
+
359
+ this.writerPosition = value
360
+ }
361
+
362
+ /**
363
+ * Size of the backing array right now
364
+ */
365
+ public get capacity(): number {
366
+ return this.end - this.base
367
+ }
368
+
369
+ /**
370
+ * How big ensureWritable will let it get
371
+ */
372
+ public get maxCapacity(): number {
373
+ return this.limit
374
+ }
375
+
376
+ /**
377
+ * Bytes between readerIndex and writerIndex
378
+ */
379
+ public get readableBytes(): number {
380
+ return this.writerPosition - this.readerPosition
381
+ }
382
+
383
+ /**
384
+ * Room left before a write has to grow the array
385
+ */
386
+ public get writableBytes(): number {
387
+ return this.end - this.base - this.writerPosition
388
+ }
389
+
390
+ /**
391
+ * Quick check before a read so decoders can wait for more data
392
+ * @param size bytes you need, 1 if left out
393
+ */
394
+ public isReadable(size = 1): boolean {
395
+ return this.readableBytes >= size
396
+ }
397
+
398
+ /**
399
+ * At least doubles the array when it has to grow, throws past maxCapacity
400
+ * @param size bytes about to be written
401
+ */
402
+ public ensureWritable(size: number): this {
403
+ const required = this.writerPosition + size
404
+ const current = this.end - this.base
405
+ if (required <= current) return this
406
+ if (required > this.limit) throw new RangeError('Capacity is exceeded')
407
+
408
+ const capacity = Math.min(
409
+ this.limit,
410
+ Math.max(required, current * 2, ByteBuf.defaultCapacity),
411
+ )
412
+ const storage = new Uint8Array(capacity)
413
+ storage.set(
414
+ this.storage.subarray(this.base, this.base + this.writerPosition),
415
+ )
416
+
417
+ this.storage = storage
418
+ this.view = null
419
+ this.base = 0
420
+ this.end = capacity
421
+ return this
422
+ }
423
+
424
+ /**
425
+ * Rewinds everything to zero, the bytes themselves stay put
426
+ */
427
+ public clear(): this {
428
+ this.readerPosition = 0
429
+ this.writerPosition = 0
430
+ this.markedReaderPosition = 0
431
+ return this
432
+ }
433
+
434
+ /**
435
+ * Bookmark the read position, pair it with resetReaderIndex
436
+ */
437
+ public markReaderIndex(): this {
438
+ this.markedReaderPosition = this.readerPosition
439
+ return this
440
+ }
441
+
442
+ /**
443
+ * Back to wherever markReaderIndex left it
444
+ */
445
+ public resetReaderIndex(): this {
446
+ this.readerIndex = this.markedReaderPosition
447
+ return this
448
+ }
449
+
450
+ /**
451
+ * Like a read that throws the bytes away
452
+ * @param size how far to move, can't pass writerIndex
453
+ */
454
+ public skipBytes(size: number): this {
455
+ this.advanceReader(size)
456
+ return this
457
+ }
458
+
459
+ /**
460
+ * Shifts unread data down to index 0 to free up room at the end
461
+ */
462
+ public discardReadBytes(): this {
463
+ if (this.readerPosition === 0) return this
464
+
465
+ const base = this.base
466
+ this.storage.copyWithin(
467
+ base,
468
+ base + this.readerPosition,
469
+ base + this.writerPosition,
470
+ )
471
+ this.writerPosition -= this.readerPosition
472
+ this.markedReaderPosition = Math.max(
473
+ 0,
474
+ this.markedReaderPosition - this.readerPosition,
475
+ )
476
+ this.readerPosition = 0
477
+ return this
478
+ }
479
+
480
+ /**
481
+ * Doesn't move readerIndex, same for every get
482
+ * @param index absolute offset into the buffer
483
+ */
484
+ public getInt8(index: number): number {
485
+ return ((this.storage[this.checkIndex(index, 1)] ?? 0) << 24) >> 24
486
+ }
487
+
488
+ /**
489
+ * Single byte, 0 to 255
490
+ * @param index absolute offset
491
+ */
492
+ public getUint8(index: number): number {
493
+ return this.storage[this.checkIndex(index, 1)] ?? 0
494
+ }
495
+
496
+ /**
497
+ * Two bytes, sign-extended
498
+ * @param index absolute offset
499
+ * @param endian byte order, big unless told otherwise
500
+ */
501
+ public getInt16(index: number, endian: Endian = 'big'): number {
502
+ return (this.getUint16(index, endian) << 16) >> 16
503
+ }
504
+
505
+ /**
506
+ * Two bytes, 0 to 65535
507
+ * @param index absolute offset
508
+ * @param endian byte order, big by default
509
+ */
510
+ public getUint16(index: number, endian: Endian = 'big'): number {
511
+ const start = this.checkIndex(index, 2)
512
+
513
+ const first = this.storage[start] ?? 0
514
+ const second = this.storage[start + 1] ?? 0
515
+ return endian === 'big' ? (first << 8) | second : (second << 8) | first
516
+ }
517
+
518
+ /**
519
+ * Three bytes, handy for some length prefixes
520
+ * @param index absolute offset
521
+ * @param endian big or little
522
+ */
523
+ public getUint24(index: number, endian: Endian = 'big'): number {
524
+ const start = this.checkIndex(index, 3)
525
+
526
+ const first = this.storage[start] ?? 0
527
+ const middle = this.storage[start + 1] ?? 0
528
+ const last = this.storage[start + 2] ?? 0
529
+ return endian === 'big'
530
+ ? (first << 16) | (middle << 8) | last
531
+ : (last << 16) | (middle << 8) | first
532
+ }
533
+
534
+ /**
535
+ * Four bytes, sign included
536
+ * @param index absolute offset
537
+ * @param endian big by default
538
+ */
539
+ public getInt32(index: number, endian: Endian = 'big'): number {
540
+ return this.getUint32(index, endian) | 0
541
+ }
542
+
543
+ /**
544
+ * Four bytes, always comes back positive
545
+ * @param index absolute offset
546
+ * @param endian big or little
547
+ */
548
+ public getUint32(index: number, endian: Endian = 'big'): number {
549
+ const start = this.checkIndex(index, 4)
550
+
551
+ const bytes = this.storage
552
+ const value =
553
+ endian === 'big'
554
+ ? ((bytes[start] ?? 0) << 24) |
555
+ ((bytes[start + 1] ?? 0) << 16) |
556
+ ((bytes[start + 2] ?? 0) << 8) |
557
+ (bytes[start + 3] ?? 0)
558
+ : ((bytes[start + 3] ?? 0) << 24) |
559
+ ((bytes[start + 2] ?? 0) << 16) |
560
+ ((bytes[start + 1] ?? 0) << 8) |
561
+ (bytes[start] ?? 0)
562
+ return value >>> 0
563
+ }
564
+
565
+ /**
566
+ * Eight bytes as a bigint since numbers can't hold it
567
+ * @param index absolute offset
568
+ * @param endian big by default
569
+ */
570
+ public getInt64(index: number, endian: Endian = 'big'): bigint {
571
+ return this.data.getBigInt64(this.checkIndex(index, 8), endian === 'little')
572
+ }
573
+
574
+ /**
575
+ * Eight bytes as an unsigned bigint
576
+ * @param index absolute offset
577
+ * @param endian big or little
578
+ */
579
+ public getUint64(index: number, endian: Endian = 'big'): bigint {
580
+ return this.data.getBigUint64(
581
+ this.checkIndex(index, 8),
582
+ endian === 'little',
583
+ )
584
+ }
585
+
586
+ /**
587
+ * IEEE single precision
588
+ * @param index absolute offset
589
+ * @param endian big by default
590
+ */
591
+ public getFloat32(index: number, endian: Endian = 'big'): number {
592
+ return this.data.getFloat32(this.checkIndex(index, 4), endian === 'little')
593
+ }
594
+
595
+ /**
596
+ * IEEE double precision
597
+ * @param index absolute offset
598
+ * @param endian big or little
599
+ */
600
+ public getFloat64(index: number, endian: Endian = 'big'): number {
601
+ return this.data.getFloat64(this.checkIndex(index, 8), endian === 'little')
602
+ }
603
+
604
+ /**
605
+ * Overwrites in place without moving writerIndex, same for every set
606
+ * @param index absolute offset
607
+ * @param value low 8 bits are kept
608
+ */
609
+ public setInt8(index: number, value: number): this {
610
+ this.storage[this.checkIndex(index, 1)] = value & 0xff
611
+ return this
612
+ }
613
+
614
+ /**
615
+ * Same bytes as setInt8, kept for symmetry
616
+ * @param index absolute offset
617
+ * @param value low 8 bits are kept
618
+ */
619
+ public setUint8(index: number, value: number): this {
620
+ this.storage[this.checkIndex(index, 1)] = value & 0xff
621
+ return this
622
+ }
623
+
624
+ /**
625
+ * Bit pattern matches the unsigned one, so it delegates
626
+ * @param index absolute offset
627
+ * @param value low 16 bits are kept
628
+ * @param endian big by default
629
+ */
630
+ public setInt16(index: number, value: number, endian: Endian = 'big'): this {
631
+ return this.setUint16(index, value, endian)
632
+ }
633
+
634
+ /**
635
+ * Two bytes in place
636
+ * @param index absolute offset
637
+ * @param value low 16 bits are kept
638
+ * @param endian big or little
639
+ */
640
+ public setUint16(index: number, value: number, endian: Endian = 'big'): this {
641
+ const start = this.checkIndex(index, 2)
642
+
643
+ const high = (value >>> 8) & 0xff
644
+ const low = value & 0xff
645
+ this.storage[start] = endian === 'big' ? high : low
646
+ this.storage[start + 1] = endian === 'big' ? low : high
647
+ return this
648
+ }
649
+
650
+ /**
651
+ * Three bytes in place
652
+ * @param index absolute offset
653
+ * @param value low 24 bits are kept
654
+ * @param endian big by default
655
+ */
656
+ public setUint24(index: number, value: number, endian: Endian = 'big'): this {
657
+ const start = this.checkIndex(index, 3)
658
+
659
+ const high = (value >>> 16) & 0xff
660
+ const middle = (value >>> 8) & 0xff
661
+ const low = value & 0xff
662
+ this.storage[start] = endian === 'big' ? high : low
663
+ this.storage[start + 1] = middle
664
+ this.storage[start + 2] = endian === 'big' ? low : high
665
+ return this
666
+ }
667
+
668
+ /**
669
+ * Delegates to setUint32, the bits are the same
670
+ * @param index absolute offset
671
+ * @param value anything that fits in 32 bits
672
+ * @param endian big or little
673
+ */
674
+ public setInt32(index: number, value: number, endian: Endian = 'big'): this {
675
+ return this.setUint32(index, value, endian)
676
+ }
677
+
678
+ /**
679
+ * Four bytes in place
680
+ * @param index absolute offset
681
+ * @param value low 32 bits are kept
682
+ * @param endian big by default
683
+ */
684
+ public setUint32(index: number, value: number, endian: Endian = 'big'): this {
685
+ const start = this.checkIndex(index, 4)
686
+
687
+ const bytes = this.storage
688
+ const first = (value >>> 24) & 0xff
689
+ const second = (value >>> 16) & 0xff
690
+ const third = (value >>> 8) & 0xff
691
+ const fourth = value & 0xff
692
+ const big = endian === 'big'
693
+ bytes[start] = big ? first : fourth
694
+ bytes[start + 1] = big ? second : third
695
+ bytes[start + 2] = big ? third : second
696
+ bytes[start + 3] = big ? fourth : first
697
+ return this
698
+ }
699
+
700
+ /**
701
+ * Eight bytes in place from a bigint
702
+ * @param index absolute offset
703
+ * @param value signed bigint
704
+ * @param endian big or little
705
+ */
706
+ public setInt64(index: number, value: bigint, endian: Endian = 'big'): this {
707
+ this.data.setBigInt64(this.checkIndex(index, 8), value, endian === 'little')
708
+ return this
709
+ }
710
+
711
+ /**
712
+ * Eight bytes in place, unsigned
713
+ * @param index absolute offset
714
+ * @param value non-negative bigint
715
+ * @param endian big by default
716
+ */
717
+ public setUint64(index: number, value: bigint, endian: Endian = 'big'): this {
718
+ this.data.setBigUint64(
719
+ this.checkIndex(index, 8),
720
+ value,
721
+ endian === 'little',
722
+ )
723
+ return this
724
+ }
725
+
726
+ /**
727
+ * Stores a single, so expect some precision loss
728
+ * @param index absolute offset
729
+ * @param value number to store
730
+ * @param endian big or little
731
+ */
732
+ public setFloat32(
733
+ index: number,
734
+ value: number,
735
+ endian: Endian = 'big',
736
+ ): this {
737
+ this.data.setFloat32(this.checkIndex(index, 4), value, endian === 'little')
738
+ return this
739
+ }
740
+
741
+ /**
742
+ * Stores a full double
743
+ * @param index absolute offset
744
+ * @param value number to store
745
+ * @param endian big by default
746
+ */
747
+ public setFloat64(
748
+ index: number,
749
+ value: number,
750
+ endian: Endian = 'big',
751
+ ): this {
752
+ this.data.setFloat64(this.checkIndex(index, 8), value, endian === 'little')
753
+ return this
754
+ }
755
+
756
+ /**
757
+ * Takes one byte and moves on, throws if nothing's readable
758
+ */
759
+ public readInt8(): number {
760
+ return this.getInt8(this.advanceReader(1))
761
+ }
762
+
763
+ /**
764
+ * Takes one unsigned byte and moves on
765
+ */
766
+ public readUint8(): number {
767
+ return this.getUint8(this.advanceReader(1))
768
+ }
769
+
770
+ /**
771
+ * Signed short, reader moves 2
772
+ * @param endian big by default
773
+ */
774
+ public readInt16(endian: Endian = 'big'): number {
775
+ return this.getInt16(this.advanceReader(2), endian)
776
+ }
777
+
778
+ /**
779
+ * Unsigned short, reader moves 2
780
+ * @param endian big or little
781
+ */
782
+ public readUint16(endian: Endian = 'big'): number {
783
+ return this.getUint16(this.advanceReader(2), endian)
784
+ }
785
+
786
+ /**
787
+ * Unsigned 24 bit, reader moves 3
788
+ * @param endian big by default
789
+ */
790
+ public readUint24(endian: Endian = 'big'): number {
791
+ return this.getUint24(this.advanceReader(3), endian)
792
+ }
793
+
794
+ /**
795
+ * Signed int, reader moves 4
796
+ * @param endian big or little
797
+ */
798
+ public readInt32(endian: Endian = 'big'): number {
799
+ return this.getInt32(this.advanceReader(4), endian)
800
+ }
801
+
802
+ /**
803
+ * Unsigned int, reader moves 4
804
+ * @param endian big by default
805
+ */
806
+ public readUint32(endian: Endian = 'big'): number {
807
+ return this.getUint32(this.advanceReader(4), endian)
808
+ }
809
+
810
+ /**
811
+ * Signed bigint, reader moves 8
812
+ * @param endian big or little
813
+ */
814
+ public readInt64(endian: Endian = 'big'): bigint {
815
+ return this.getInt64(this.advanceReader(8), endian)
816
+ }
817
+
818
+ /**
819
+ * Unsigned bigint, reader moves 8
820
+ * @param endian big by default
821
+ */
822
+ public readUint64(endian: Endian = 'big'): bigint {
823
+ return this.getUint64(this.advanceReader(8), endian)
824
+ }
825
+
826
+ /**
827
+ * Single precision, reader moves 4
828
+ * @param endian big or little
829
+ */
830
+ public readFloat32(endian: Endian = 'big'): number {
831
+ return this.getFloat32(this.advanceReader(4), endian)
832
+ }
833
+
834
+ /**
835
+ * Double precision, reader moves 8
836
+ * @param endian big by default
837
+ */
838
+ public readFloat64(endian: Endian = 'big'): number {
839
+ return this.getFloat64(this.advanceReader(8), endian)
840
+ }
841
+
842
+ /**
843
+ * Copies, so the result is safe to keep after the buffer changes
844
+ * @param size how many bytes to take
845
+ */
846
+ public readBytes(size: number): Uint8Array {
847
+ const start = this.base + this.advanceReader(size)
848
+ return this.storage.slice(start, start + size)
849
+ }
850
+
851
+ /**
852
+ * Like slice, but points an existing buffer at the bytes instead of making one
853
+ * @param index where it starts, from the start of this buffer
854
+ * @param size how many bytes to take
855
+ * @param target the buffer to reuse
856
+ */
857
+ public sliceInto(index: number, size: number, target: ByteBuf): ByteBuf {
858
+ const start = this.checkIndex(index, size)
859
+
860
+ target.storage = this.storage
861
+ target.view = null
862
+ target.readerPosition = 0
863
+ target.writerPosition = size
864
+ target.markedReaderPosition = 0
865
+ target.limit = size
866
+ target.base = start
867
+ target.end = start + size
868
+ target.refs = 1
869
+ return target
870
+ }
871
+
872
+ /**
873
+ * No copy and the reader stays put, the slice shares memory
874
+ * @param index where it starts, from the start of this buffer
875
+ * @param size how many bytes to take
876
+ */
877
+ public slice(index: number, size: number): ByteBuf {
878
+ const start = this.checkIndex(index, size)
879
+
880
+ return new ByteBuf(this.storage, size, size, start, start + size)
881
+ }
882
+
883
+ /**
884
+ * No copy, the slice shares memory and is capped at its own size
885
+ * @param size how many bytes to take
886
+ */
887
+ public readSlice(size: number): ByteBuf {
888
+ const start = this.base + this.advanceReader(size)
889
+
890
+ return new ByteBuf(this.storage, size, size, start, start + size)
891
+ }
892
+
893
+ /**
894
+ * Writes a non-negative integer in as few bytes as it needs, LEB128 style
895
+ * @param value any safe integer from 0 up
896
+ */
897
+ public writeVarUint(value: number): this {
898
+ if (!Number.isSafeInteger(value) || value < 0) {
899
+ throw new RangeError('Value is out of range')
900
+ }
901
+
902
+ this.ensureWritable(ByteBuf.varUintSize(value))
903
+ const storage = this.storage
904
+ const base = this.base
905
+ let index = base + this.writerPosition
906
+ let rest = value
907
+ while (rest >= 0x80000000) {
908
+ storage[index++] = (rest % 0x80) | 0x80
909
+ rest = Math.floor(rest / 0x80)
910
+ }
911
+
912
+ while (rest >= 0x80) {
913
+ storage[index++] = (rest & 0x7f) | 0x80
914
+ rest >>>= 7
915
+ }
916
+
917
+ storage[index++] = rest
918
+ this.writerPosition = index - base
919
+ return this
920
+ }
921
+
922
+ /**
923
+ * Reads a non-negative integer written by writeVarUint
924
+ */
925
+ public readVarUint(): number {
926
+ const storage = this.storage
927
+ const base = this.base
928
+ const end = base + this.writerPosition
929
+ let index = base + this.readerPosition
930
+ let value = 0
931
+ let scale = 1
932
+
933
+ for (let count = 0; count < 8; count++) {
934
+ if (index >= end) throw new RangeError('Index is out of range')
935
+ const byte = storage[index++] ?? 0
936
+ value += (byte & 0x7f) * scale
937
+ if (byte < 0x80) {
938
+ this.readerPosition = index - base
939
+ return value
940
+ }
941
+
942
+ scale *= 0x80
943
+ }
944
+
945
+ throw new RangeError('Varint is too long')
946
+ }
947
+
948
+ /**
949
+ * Bytes a varint takes for this value
950
+ * @param value a non-negative safe integer
951
+ */
952
+ private static varUintSize(value: number): number {
953
+ if (value < 0x80) return 1
954
+ if (value < 0x4000) return 2
955
+ if (value < 0x200000) return 3
956
+ if (value < 0x10000000) return 4
957
+
958
+ let size = 4
959
+ for (
960
+ let rest = Math.floor(value / 0x10000000);
961
+ rest > 0;
962
+ rest = Math.floor(rest / 0x80)
963
+ ) {
964
+ size += 1
965
+ }
966
+ return size
967
+ }
968
+
969
+ /**
970
+ * Writes an integer from minus 2 to the 52 up to just under 2 to the 52, zigzagged so small negatives stay small
971
+ * @param value an integer in that range
972
+ */
973
+ public writeVarInt(value: number): this {
974
+ if (!Number.isInteger(value) || value < -(2 ** 52) || value >= 2 ** 52) {
975
+ throw new RangeError('Value is out of range')
976
+ }
977
+
978
+ return this.writeVarUint(value >= 0 ? value * 2 : -value * 2 - 1)
979
+ }
980
+
981
+ /**
982
+ * Reads an integer written by writeVarInt
983
+ */
984
+ public readVarInt(): number {
985
+ const zigzag = this.readVarUint()
986
+
987
+ return zigzag % 2 === 0 ? zigzag / 2 : -(zigzag + 1) / 2
988
+ }
989
+
990
+ /**
991
+ * Decodes that many bytes as UTF-8
992
+ * @param size length in bytes, not characters
993
+ */
994
+ public readString(size: number): string {
995
+ const start = this.base + this.advanceReader(size)
996
+ return ByteBuf.decoder.decode(this.storage.subarray(start, start + size))
997
+ }
998
+
999
+ /**
1000
+ * Appends one byte, growing if needed
1001
+ * @param value low 8 bits are kept
1002
+ */
1003
+ public writeInt8(value: number): this {
1004
+ return this.setInt8(this.advanceWriter(1), value)
1005
+ }
1006
+
1007
+ /**
1008
+ * Appends one unsigned byte
1009
+ * @param value 0 to 255, anything else is masked
1010
+ */
1011
+ public writeUint8(value: number): this {
1012
+ return this.setUint8(this.advanceWriter(1), value)
1013
+ }
1014
+
1015
+ /**
1016
+ * Appends two bytes
1017
+ * @param value signed short
1018
+ * @param endian big by default
1019
+ */
1020
+ public writeInt16(value: number, endian: Endian = 'big'): this {
1021
+ return this.setInt16(this.advanceWriter(2), value, endian)
1022
+ }
1023
+
1024
+ /**
1025
+ * Appends two bytes
1026
+ * @param value unsigned short
1027
+ * @param endian big or little
1028
+ */
1029
+ public writeUint16(value: number, endian: Endian = 'big'): this {
1030
+ return this.setUint16(this.advanceWriter(2), value, endian)
1031
+ }
1032
+
1033
+ /**
1034
+ * Appends three bytes
1035
+ * @param value up to 16777215
1036
+ * @param endian big by default
1037
+ */
1038
+ public writeUint24(value: number, endian: Endian = 'big'): this {
1039
+ return this.setUint24(this.advanceWriter(3), value, endian)
1040
+ }
1041
+
1042
+ /**
1043
+ * Appends four bytes
1044
+ * @param value signed int
1045
+ * @param endian big or little
1046
+ */
1047
+ public writeInt32(value: number, endian: Endian = 'big'): this {
1048
+ return this.setInt32(this.advanceWriter(4), value, endian)
1049
+ }
1050
+
1051
+ /**
1052
+ * Appends four bytes
1053
+ * @param value unsigned int
1054
+ * @param endian big by default
1055
+ */
1056
+ public writeUint32(value: number, endian: Endian = 'big'): this {
1057
+ return this.setUint32(this.advanceWriter(4), value, endian)
1058
+ }
1059
+
1060
+ /**
1061
+ * Appends eight bytes
1062
+ * @param value signed bigint
1063
+ * @param endian big or little
1064
+ */
1065
+ public writeInt64(value: bigint, endian: Endian = 'big'): this {
1066
+ return this.setInt64(this.advanceWriter(8), value, endian)
1067
+ }
1068
+
1069
+ /**
1070
+ * Appends eight bytes
1071
+ * @param value unsigned bigint
1072
+ * @param endian big by default
1073
+ */
1074
+ public writeUint64(value: bigint, endian: Endian = 'big'): this {
1075
+ return this.setUint64(this.advanceWriter(8), value, endian)
1076
+ }
1077
+
1078
+ /**
1079
+ * Appends a single
1080
+ * @param value number to store
1081
+ * @param endian big or little
1082
+ */
1083
+ public writeFloat32(value: number, endian: Endian = 'big'): this {
1084
+ return this.setFloat32(this.advanceWriter(4), value, endian)
1085
+ }
1086
+
1087
+ /**
1088
+ * Appends a double
1089
+ * @param value number to store
1090
+ * @param endian big by default
1091
+ */
1092
+ public writeFloat64(value: number, endian: Endian = 'big'): this {
1093
+ return this.setFloat64(this.advanceWriter(8), value, endian)
1094
+ }
1095
+
1096
+ /**
1097
+ * Appends raw bytes, and a ByteBuf source has its reader moved to the end
1098
+ * @param source array to copy or buffer to drain
1099
+ */
1100
+ public writeBytes(source: Uint8Array | ByteBuf): this
1101
+
1102
+ /**
1103
+ * Appends part of another buffer without touching its indexes, like Netty's writeBytes(src, index, length)
1104
+ * @param source buffer to copy from
1105
+ * @param index where in source to start
1106
+ * @param length how many bytes
1107
+ */
1108
+ public writeBytes(source: ByteBuf, index: number, length: number): this
1109
+
1110
+ /**
1111
+ * Appends bytes from an array or another buffer
1112
+ * @param source array or buffer to copy from
1113
+ * @param index where in source to start, or undefined to drain its readable bytes
1114
+ * @param length how many bytes when index is given
1115
+ */
1116
+ public writeBytes(
1117
+ source: Uint8Array | ByteBuf,
1118
+ index?: number,
1119
+ length?: number,
1120
+ ): this {
1121
+ if (source instanceof ByteBuf) {
1122
+ if (index !== undefined) {
1123
+ const size = length ?? 0
1124
+ const from = source.checkIndex(index, size)
1125
+ const to = this.base + this.advanceWriter(size)
1126
+ ByteBuf.copyBytes(source.storage, from, this.storage, to, size)
1127
+ return this
1128
+ }
1129
+
1130
+ const size = source.readableBytes
1131
+ const from = source.base + source.advanceReader(size)
1132
+ const to = this.base + this.advanceWriter(size)
1133
+ ByteBuf.copyBytes(source.storage, from, this.storage, to, size)
1134
+ return this
1135
+ }
1136
+
1137
+ const start = this.advanceWriter(source.length)
1138
+ this.storage.set(source, this.base + start)
1139
+ return this
1140
+ }
1141
+
1142
+ /**
1143
+ * An empty Buffer whose native copy works on any Uint8Array
1144
+ */
1145
+ private static readonly copier: Buffer = Buffer.alloc(0)
1146
+
1147
+ /**
1148
+ * Copies bytes between arrays, natively unless the run is tiny
1149
+ * @param source where to copy from
1150
+ * @param from start in source
1151
+ * @param target where to copy to
1152
+ * @param to start in target
1153
+ * @param size how many bytes
1154
+ */
1155
+ public static copyBytes(
1156
+ source: Uint8Array,
1157
+ from: number,
1158
+ target: Uint8Array,
1159
+ to: number,
1160
+ size: number,
1161
+ ): void {
1162
+ if (size >= 16) {
1163
+ ByteBuf.copier.copy.call(source, target, to, from, from + size)
1164
+ return
1165
+ }
1166
+
1167
+ let read = from
1168
+ let write = to
1169
+ const end = from + size
1170
+ while (read < end) target[write++] = source[read++] ?? 0
1171
+ }
1172
+
1173
+ /**
1174
+ * UTF-8 encodes and appends, hands back the byte count
1175
+ * @param value text to write
1176
+ */
1177
+ public writeString(value: string): number {
1178
+ const length = value.length
1179
+ if (length <= 1024) {
1180
+ const start = this.base + this.advanceWriter(length)
1181
+ const storage = this.storage
1182
+ let index = 0
1183
+ for (; index < length; index++) {
1184
+ const code = value.charCodeAt(index)
1185
+ if (code > 0x7f) break
1186
+ storage[start + index] = code
1187
+ }
1188
+
1189
+ if (index === length) return length
1190
+ this.writerPosition -= length - index
1191
+ return index + this.writeEncoded(value.slice(index))
1192
+ }
1193
+
1194
+ return this.writeEncoded(value)
1195
+ }
1196
+
1197
+ /**
1198
+ * UTF-8 encodes and appends, for text that isn't plain ASCII
1199
+ * @param value text to write
1200
+ */
1201
+ private writeEncoded(value: string): number {
1202
+ const bytes = ByteBuf.encoder.encode(value)
1203
+
1204
+ this.writeBytes(bytes)
1205
+ return bytes.length
1206
+ }
1207
+
1208
+ /**
1209
+ * Absolute index of the first match, -1 if there isn't one
1210
+ * @param value single byte or a sequence to look for
1211
+ * @param from where to start, readerIndex by default
1212
+ * @param to where to stop, writerIndex by default
1213
+ */
1214
+ public indexOf(
1215
+ value: number | Uint8Array,
1216
+ from: number = this.readerPosition,
1217
+ to: number = this.writerPosition,
1218
+ ): number {
1219
+ if (typeof value === 'number') return this.indexOfByte(value, from, to)
1220
+
1221
+ const base = this.base
1222
+ const needle = value
1223
+ const end = base + Math.min(to, this.writerPosition) - needle.length
1224
+ const first = needle[0]
1225
+ if (first === undefined) return Math.max(from, 0)
1226
+
1227
+ let index = this.storage.indexOf(first, base + Math.max(from, 0))
1228
+ while (index !== -1 && index <= end) {
1229
+ if (this.matches(index, needle)) return index - base
1230
+
1231
+ index = this.storage.indexOf(first, index + 1)
1232
+ }
1233
+
1234
+ return -1
1235
+ }
1236
+
1237
+ /**
1238
+ * Readable bytes as a view, not a copy, so don't hang on to it
1239
+ */
1240
+ public toUint8Array(): Uint8Array {
1241
+ const base = this.base
1242
+ if (
1243
+ base === 0 &&
1244
+ this.readerPosition === 0 &&
1245
+ this.writerPosition === this.storage.length
1246
+ ) {
1247
+ return this.storage
1248
+ }
1249
+
1250
+ return this.storage.subarray(
1251
+ base + this.readerPosition,
1252
+ base + this.writerPosition,
1253
+ )
1254
+ }
1255
+
1256
+ /**
1257
+ * Independent copy of just the readable part
1258
+ */
1259
+ public copy(): ByteBuf {
1260
+ return ByteBuf.wrap(
1261
+ this.storage.slice(
1262
+ this.base + this.readerPosition,
1263
+ this.base + this.writerPosition,
1264
+ ),
1265
+ )
1266
+ }
1267
+
1268
+ /**
1269
+ * Same memory, own indexes, so two readers don't trip over each other
1270
+ */
1271
+ public duplicate(): ByteBuf {
1272
+ const duplicate = new ByteBuf(
1273
+ this.storage,
1274
+ this.writerPosition,
1275
+ this.limit,
1276
+ this.base,
1277
+ this.end,
1278
+ )
1279
+
1280
+ duplicate.readerIndex = this.readerPosition
1281
+ return duplicate
1282
+ }
1283
+
1284
+ /**
1285
+ * Readable bytes as UTF-8, indexes untouched
1286
+ */
1287
+ public toString(): string {
1288
+ return ByteBuf.decoder.decode(this.toUint8Array())
1289
+ }
1290
+
1291
+ /**
1292
+ * Lazy DataView for the accessors that need one
1293
+ */
1294
+ private get data(): DataView {
1295
+ this.view ??= ByteBuf.viewOf(this.storage)
1296
+ return this.view
1297
+ }
1298
+
1299
+ /**
1300
+ * Throws if the range runs outside the array, otherwise returns index
1301
+ * @param index absolute offset
1302
+ * @param size bytes about to be touched
1303
+ */
1304
+ private checkIndex(index: number, size: number): number {
1305
+ const capacity = this.end - this.base
1306
+ if ((index | 0) === index && index >= 0 && index + size <= capacity) {
1307
+ return this.base + index
1308
+ }
1309
+
1310
+ const reason = ByteBuf.refusal(index, size, 0, capacity)
1311
+ throw new RangeError(reason ?? 'Index is out of range')
1312
+ }
1313
+
1314
+ /**
1315
+ * Returns the old position, throws if there aren't enough readable bytes
1316
+ * @param size how far to move
1317
+ */
1318
+ private advanceReader(size: number): number {
1319
+ const start = this.readerPosition
1320
+
1321
+ if ((size | 0) !== size || size < 0 || start + size > this.writerPosition) {
1322
+ const reason = ByteBuf.refusal(start, size, 0, this.writerPosition)
1323
+ throw new RangeError(reason ?? 'Index is out of range')
1324
+ }
1325
+
1326
+ this.readerPosition = start + size
1327
+ return start
1328
+ }
1329
+
1330
+ /**
1331
+ * Grows if needed and returns where the write should start
1332
+ * @param size how far to move
1333
+ */
1334
+ private advanceWriter(size: number): number {
1335
+ const start = this.writerPosition
1336
+
1337
+ if ((size | 0) !== size || size < 0) throw new RangeError('Size is invalid')
1338
+ if (start + size > this.end - this.base) this.ensureWritable(size)
1339
+
1340
+ this.writerPosition = start + size
1341
+ return start
1342
+ }
1343
+
1344
+ /**
1345
+ * Single-byte search using the native indexOf
1346
+ * @param value byte to look for
1347
+ * @param from first index to check
1348
+ * @param to stops before this
1349
+ */
1350
+ private indexOfByte(value: number, from: number, to: number): number {
1351
+ const base = this.base
1352
+ const index = this.storage.indexOf(value, base + Math.max(from, 0))
1353
+ const end = base + Math.min(to, this.writerPosition)
1354
+
1355
+ return index !== -1 && index < end ? index - base : -1
1356
+ }
1357
+
1358
+ /**
1359
+ * Byte zero is already known to match, so this checks the rest
1360
+ * @param index where the candidate starts
1361
+ * @param needle sequence to compare
1362
+ */
1363
+ private matches(index: number, needle: Uint8Array): boolean {
1364
+ for (let offset = 1; offset < needle.length; offset++) {
1365
+ if (this.storage[index + offset] !== needle[offset]) return false
1366
+ }
1367
+
1368
+ return true
1369
+ }
1370
+ }
1371
+
1372
+ export { BitReader, BitWriter } from './bits/index.ts'
1373
+ export { ByteBufPool } from './pool/index.ts'
1374
+ export { Quantizer } from './quantizer/index.ts'
1375
+ export type { QuantizerOptions } from './quantizer/index.ts'