forked from kriszyp/msgpackr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.js
63 lines (59 loc) · 1.37 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
58
59
60
61
62
63
"use strict"
var Transform = require('stream').Transform
var Packr = require('./pack').Packr
const { read, getPosition, Unpackr, clearSource } = require('./unpack')
var DEFAULT_OPTIONS = {objectMode: true}
class PackrStream extends Transform {
constructor(options) {
if (!options)
options = {}
super(options)
options.sequential = true
this.packr = new Packr(options)
}
write(value) {
this.push(this.packr.pack(value))
}
end(value) {
if (value != null)
this.push(this.packr.pack(value))
this.push(null)
}
}
class UnpackrStream extends Transform {
constructor(options) {
if (!options)
options = {}
options.objectMode = true
super(options)
options.structures = []
this.unpackr = new Unpackr(options)
}
_transform(chunk, encoding, callback) {
if (this.incompleteBuffer) {
chunk = Buffer.concat([this.incompleteBuffer, chunk])
this.incompleteBuffer = null
}
let position = 0
let size = chunk.length
try {
this.push(this.unpackr.unpack(chunk, size, true))
position = getPosition()
while (position < size) {
let value = read()
this.push(value)
position = getPosition()
}
} catch(error) {
if (error.incomplete)
this.incompleteBuffer = chunk.slice(position)
else
throw error
} finally {
clearSource()
}
if (callback) callback()
}
}
exports.PackrStream = PackrStream
exports.UnpackrStream = UnpackrStream