Skip to content

Commit

Permalink
fix: empty shallowSlice return
Browse files Browse the repository at this point in the history
Buffer.slice() and BL.slice() both support returning an empty dataset when start and end are both the same. We were defaulting the end arg assuming we’d always have a truthy value for end, when 0 is valid.
  • Loading branch information
reconbot committed Feb 2, 2019
1 parent 055a3ff commit 9b80b00
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
5 changes: 4 additions & 1 deletion bl.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,16 @@ BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {

BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
start = start || 0
end = end || this.length
end = typeof end !== 'number' ? this.length : end

if (start < 0)
start += this.length
if (end < 0)
end += this.length

if (start === end) {
return new BufferList()
}
var startOffset = this._offset(start)
, endOffset = this._offset(end)
, buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
Expand Down
14 changes: 14 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,20 @@ tape('shallow slice does not make a copy', function (t) {
t.equal(bl.toString(), 'hhhhhhhh')
})

tape('shallow slice with 0 length', function (t) {
t.plan(1)
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
var bl = (new BufferList(buffers)).shallowSlice(0, 0)
t.equal(bl.length, 0)
})

tape('shallow slice with 0 length from middle', function (t) {
t.plan(1)
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')]
var bl = (new BufferList(buffers)).shallowSlice(10, 10)
t.equal(bl.length, 0)
})

tape('duplicate', function (t) {
t.plan(2)

Expand Down

0 comments on commit 9b80b00

Please sign in to comment.