-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
93 lines (79 loc) · 1.56 KB
/
index.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
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
module.exports = inflate
var min = pushToPull(require('./min'))
, through = require('through')
function inflate() {
var stream = through(write, end)
, inner = min(read)
, accum = []
, cb
iter()
return stream
function iter() {
inner(null, function(err, data) {
if(err) {
stream.emit('error', err)
return
}
if(data === undefined) {
stream.queue(null)
return
}
stream.queue(data)
iter()
})
}
function write(buf) {
accum.push(buf)
if(!cb) {
return
}
while(accum.length) {
cb(null, accum.shift())
}
}
function end() {
}
function read(close, callback) {
if(close) {
if(close === true) {
stream.queue(null)
} else {
stream.emit('error', close)
}
return
}
cb = callback
}
}
function pushToPull(push) {
return function (read) {
var dataQueue = []
var readQueue = []
var reading = false
var emit = push(function () {
dataQueue.push(arguments)
check()
})
function check() {
while (dataQueue.length && readQueue.length) {
readQueue.shift().apply(null, dataQueue.shift())
}
if (!reading && readQueue.length) {
reading = true
read(null, onRead)
}
}
function onRead(err, item) {
reading = false
emit(err, item)
check()
}
return function (close, callback) {
if (close) {
return read(close, callback)
}
readQueue.push(callback)
check()
}
}
}