Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 10 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,22 @@ function BinarySplit (matcher) {
function write (buf, enc, done) {
bufcount++
var offset = 0

var lastMatch = 0
if (buffered) {
buf = bops.join([buffered, buf])
offset = buffered.length
buffered = undefined
}

while (buf) {
while (true) {
var idx = firstMatch(buf, offset)
if (idx) {
var line = bops.subarray(buf, offset, idx)
if (idx === buf.length) {
buffered = line
buf = undefined
offset = idx
} else {
this.push(line)
offset = idx + matcher.length
}
} else if (idx === 0) {
buf = bops.subarray(buf, offset + matcher.length)
if (idx !== -1 && idx < buf.length) {
this.push(bops.subarray(buf, lastMatch, idx))
offset = idx + matcher.length
lastMatch = offset
} else {
if (offset >= buf.length) {
buffered = undefined
} else {
buffered = buf
}
buf = undefined
buffered = bops.subarray(buf, lastMatch)
break
}
}

Expand All @@ -54,7 +43,7 @@ function BinarySplit (matcher) {
}

function firstMatch (buf, offset) {
if (offset >= buf.length) return false
if (offset >= buf.length) return -1
for (var i = offset; i < buf.length; i++) {
if (buf[i] === matcher[0]) {
if (matcher.length > 1) {
Expand Down
22 changes: 22 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,25 @@ test('matcher at index 0 check', function (t) {
splitStream.write(new Buffer('\nhello\nmax'))
splitStream.end()
})

test('chunked input', function (t) {
fs.createReadStream('test.json')
.pipe(split('\n'))
.pipe(split('i'))
.pipe(splitTest(':', function (err, items) {
if (err) throw err
t.equals(items.length, 4)
t.end()
}))
})

test('chunked input with long matcher', function (t) {
fs.createReadStream('test.json')
.pipe(split('\n'))
.pipe(splitTest('hello', function (err, items) {
if (err) throw err
t.equals(items.length, 2)
t.equals(items[0].toString(), '{"')
t.end()
}))
})