forked from kriszyp/cbor-x
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.js
57 lines (55 loc) · 1.35 KB
/
stream.js
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
import { Transform } from 'stream'
import { Encoder } from './encode.js'
import { checkedRead, getPosition, Decoder, clearSource } from './decode.js'
var DEFAULT_OPTIONS = {objectMode: true}
export class EncoderStream extends Transform {
constructor(options) {
if (!options)
options = {}
options.writableObjectMode = true
super(options)
options.sequential = true
this.encoder = options.encoder || new Encoder(options)
}
_transform(value, encoding, callback) {
this.push(this.encoder.encode(value))
callback()
}
}
export class DecoderStream extends Transform {
constructor(options) {
if (!options)
options = {}
options.objectMode = true
super(options)
options.structures = []
this.decoder = options.decoder || new Decoder(options)
}
_transform(chunk, encoding, callback) {
if (this.incompleteBuffer) {
chunk = Buffer.concat([this.incompleteBuffer, chunk])
this.incompleteBuffer = null
}
let values
try {
values = this.decoder.decodeMultiple(chunk)
} catch(error) {
if (error.incomplete) {
this.incompleteBuffer = chunk.slice(error.lastPosition)
values = error.values
}
else
throw error
} finally {
for (let value of values || []) {
if (value === null)
value = this.getNullValue()
this.push(value)
}
}
if (callback) callback()
}
getNullValue() {
return Symbol.for(null)
}
}