-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
69 lines (60 loc) · 1.52 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
const { Transform } = require('stream')
const { EOL } = require('os')
module.exports = BinarySplit
function firstMatch (buf, offset, matcher) {
if (offset >= buf.length) return -1
let i
for (i = offset; i < buf.length; i++) {
if (buf[i] === matcher[0]) {
if (matcher.length > 1) {
let fullMatch = true
let j = i
for (let k = 0; j < i + matcher.length; j++, k++) {
if (buf[j] !== matcher[k]) {
fullMatch = false
break
}
}
if (fullMatch) return j - matcher.length
} else {
break
}
}
}
const idx = i + matcher.length - 1
return idx
}
function BinarySplit (splitOn = EOL) {
const matcher = Buffer.from(splitOn)
let buffered
return new Transform({
readableObjectMode: true,
transform (buf, enc, done) {
let offset = 0
let lastMatch = 0
if (buffered) {
buf = Buffer.concat([buffered, buf])
offset = buffered.length
buffered = undefined
}
while (true) {
const idx = firstMatch(buf, offset - matcher.length + 1, matcher)
if (idx !== -1 && idx < buf.length) {
if (lastMatch !== idx) {
this.push(buf.slice(lastMatch, idx))
}
offset = idx + matcher.length
lastMatch = offset
} else {
buffered = buf.slice(lastMatch)
break
}
}
done()
},
flush (done) {
if (buffered && buffered.length > 0) this.push(buffered)
done()
}
})
}