Skip to content

Commit

Permalink
make .get() much faster by not copying anything
Browse files Browse the repository at this point in the history
  • Loading branch information
reconbot committed Oct 7, 2018
1 parent 6d71467 commit 172e3ee
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
9 changes: 5 additions & 4 deletions bl.js
Expand Up @@ -3,8 +3,6 @@ var DuplexStream = require('readable-stream').Duplex
, util = require('util')
, Buffer = require('safe-buffer').Buffer

var tempBuffer = Buffer.alloc(1)

function BufferList (callback) {
if (!(this instanceof BufferList))
return new BufferList(callback)
Expand Down Expand Up @@ -120,8 +118,11 @@ BufferList.prototype.end = function end (chunk) {


BufferList.prototype.get = function get (index) {
this.copy(tempBuffer, 0, index, index + 1)
return tempBuffer[0]
if (index > this.length || index < 0) {
return undefined
}
const offset = this._offset(index)
return this._bufs[offset[0]][offset[1]]
}


Expand Down
3 changes: 2 additions & 1 deletion test/test.js
Expand Up @@ -19,11 +19,12 @@ tape('single bytes from single buffer', function (t) {
bl.append(Buffer.from('abcd'))

t.equal(bl.length, 4)

t.equal(bl.get(-1), undefined)
t.equal(bl.get(0), 97)
t.equal(bl.get(1), 98)
t.equal(bl.get(2), 99)
t.equal(bl.get(3), 100)
t.equal(bl.get(4), undefined)

t.end()
})
Expand Down

0 comments on commit 172e3ee

Please sign in to comment.