Skip to content

Commit

Permalink
indexOf: Add native indexOf support for 1 byte searchs
Browse files Browse the repository at this point in the history
  • Loading branch information
reconbot committed Oct 3, 2018
1 parent 0d4d16a commit 104b478
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
29 changes: 28 additions & 1 deletion bl.js
Expand Up @@ -44,12 +44,21 @@ BufferList.prototype._offset = function _offset (offset) {
if (offset === 0) return [ 0, 0 ]
for (; i < this._bufs.length; i++) {
_t = tot + this._bufs[i].length
if (offset < _t || i == this._bufs.length - 1)
if (offset < _t || i == this._bufs.length - 1) {
return [ i, offset - tot ]
}
tot = _t
}
}

BufferList.prototype._reverseOffset = function (blOffset) {
const bufferId = blOffset[0]
let offset = blOffset[1]
for (let i = 0; i < bufferId; i++) {
offset += this._bufs[i].length
}
return offset
}

BufferList.prototype.append = function append (buf) {
var i = 0
Expand Down Expand Up @@ -285,6 +294,24 @@ BufferList.prototype.indexOf = function (search, offset, encoding) {
return offset > this.length ? this.length : offset
}

// Use the native buffer indexOf
if (search.length === 1) {
const searchBuffer = search.slice()
const blOffset = this._offset(offset)
let blIndex = blOffset[0]
let buffOffset = blOffset[1]

for (blIndex; blIndex < this._bufs.length; blIndex++) {
let position = this._bufs[blIndex].indexOf(searchBuffer, buffOffset)
if (position !== -1) {
return this._reverseOffset([blIndex, position])
}
buffOffset = 0
}
return -1
}


let searchOffset = 0
let searchPosition = -1

Expand Down
4 changes: 3 additions & 1 deletion test/test.js
Expand Up @@ -428,9 +428,11 @@ tape('test toString encoding', function (t) {
})

tape('indexOf single byte needle', t => {
const bl = new BufferList(['abcdefg', 'abcdefg'])
const bl = new BufferList(['abcdefg', 'abcdefg', '12345'])
t.equal(bl.indexOf('e'), 4)
t.equal(bl.indexOf('e', 5), 11)
t.equal(bl.indexOf('e', 12), -1)
t.equal(bl.indexOf('5'), 18)
t.end()
})

Expand Down

0 comments on commit 104b478

Please sign in to comment.