-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
140 lines (118 loc) · 3.91 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
/**
* @packageDocumentation
*
* This module makes it easy to send and receive length-prefixed byte arrays over streams.
*
* @example
*
* ```typescript
* import { lpStream } from 'it-length-prefixed-stream'
*
* const stream = lpStream(duplex)
*
* // read the next length-prefixed chunk
* const bytes = await stream.read()
*
* // write a length-prefixed chunk
* await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))
*
* // write several chunks, all individually length-prefixed
* await stream.writeV([
* Uint8Array.from([0, 1, 2, 3, 4]),
* Uint8Array.from([5, 6, 7, 8, 9])
* ])
* ```
*/
import { byteStream, type ByteStreamOpts } from 'it-byte-stream'
import * as varint from 'uint8-varint'
import { Uint8ArrayList } from 'uint8arraylist'
import type { Duplex } from 'it-stream-types'
class CodeError extends Error {
public readonly code: string
constructor (message: string, code: string) {
super(message)
this.code = code
}
}
export interface AbortOptions {
signal?: AbortSignal
}
export interface LengthPrefixedStream <Stream = unknown> {
/**
* Read the next length-prefixed number of bytes from the stream
*/
read(options?: AbortOptions): Promise<Uint8ArrayList>
/**
* Write the passed bytes to the stream prefixed by their length
*/
write(input: Uint8Array | Uint8ArrayList, options?: AbortOptions): Promise<void>
/**
* Write passed list of bytes, prefix by their individual lengths to the stream as a single write
*/
writeV(input: Array<Uint8Array | Uint8ArrayList>, options?: AbortOptions): Promise<void>
/**
* Returns the underlying stream
*/
unwrap(): Stream
}
export interface LengthPrefixedStreamOpts extends ByteStreamOpts {
// encoding opts
lengthEncoder (value: number): Uint8ArrayList | Uint8Array
// decoding opts
lengthDecoder (data: Uint8ArrayList): number
maxLengthLength: number
maxDataLength: number
}
export function lpStream <Stream extends Duplex<any, any, any>> (duplex: Stream, opts: Partial<LengthPrefixedStreamOpts> = {}): LengthPrefixedStream<Stream> {
const bytes = byteStream(duplex, opts)
if (opts.maxDataLength != null && opts.maxLengthLength == null) {
// if max data length is set but max length length is not, calculate the
// max length length needed to encode max data length
opts.maxLengthLength = varint.encodingLength(opts.maxDataLength)
}
const decodeLength = opts?.lengthDecoder ?? varint.decode
const encodeLength = opts?.lengthEncoder ?? varint.encode
const W: LengthPrefixedStream<Stream> = {
read: async (options?: AbortOptions) => {
let dataLength: number = -1
const lengthBuffer = new Uint8ArrayList()
while (true) {
// read one byte at a time until we can decode a varint
lengthBuffer.append(await bytes.read(1, options))
try {
dataLength = decodeLength(lengthBuffer)
} catch (err) {
if (err instanceof RangeError) {
continue
}
throw err
}
if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {
throw new CodeError('message length length too long', 'ERR_MSG_LENGTH_TOO_LONG')
}
if (dataLength > -1) {
break
}
}
if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {
throw new CodeError('message length too long', 'ERR_MSG_DATA_TOO_LONG')
}
return bytes.read(dataLength, options)
},
write: async (data, options?: AbortOptions) => {
// encode, write
await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options)
},
writeV: async (data, options?: AbortOptions) => {
const list = new Uint8ArrayList(
...data.flatMap(buf => ([encodeLength(buf.byteLength), buf]))
)
// encode, write
await bytes.write(list, options)
},
unwrap: () => {
return bytes.unwrap()
}
}
return W
}