forked from bigeasy/packet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
puller.js
50 lines (46 loc) · 1.53 KB
/
puller.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
var cadence = require('cadence')
var Parser = require('./parser.sketch')
var Staccato = require('staccato')
function Puller (stream) {
this._stream = stream
this._ranges = []
this._staccato = new Staccato.Readable(stream)
}
Puller.prototype.parse = cadence(function (async, definition) {
var parser = new Parser(definition)
var loop = async(function () {
if (this._ranges.length != 0) {
var range = this._ranges[0]
var outcome = parser.parse(range.buffer, range.start, range.buffer.length)
if (outcome == null) {
return [ loop.break, parser.object ]
}
} else {
async(function () {
this._staccato.read(async())
}, function (buffer) {
this._ranges.push({ buffer: buffer, start: 0 })
})
}
})()
})
Puller.prototype.read = cadence(function (async, length) {
if (this._ranges.length == 0) {
async(function () {
this._staccato.read(async())
}, function (buffer) {
this._ranges.push({ buffer: buffer, start: 0 })
this.read(length, async())
})
} else {
var range = this._ranges[0]
var remaining = range.buffer.length - range.start
var slice = range.buffer.slice(range.start, range.start + Math.min(remaining, length))
range.start += slice.length
if (range.start == range.buffer.length) {
this._ranges.shift()
}
return slice
}
})
module.exports = Puller