Skip to content

Commit

Permalink
fix(browser): preserve the offset and length when creating a DataView (
Browse files Browse the repository at this point in the history
…#11)

This fixes an issue where a view passed to the browser decoder's constructor will start reading the
entire underlying ArrayBuffer instead of the portion that the view references.
  • Loading branch information
nkochakian authored and darrachequesne committed Aug 7, 2017
1 parent 75f5ac2 commit bd91aa7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
3 changes: 2 additions & 1 deletion browser/decode.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ function Decoder(buffer) {
this.offset = 0;
if (buffer instanceof ArrayBuffer) {
this.buffer = buffer;
this.view = new DataView(this.buffer);
} else if (ArrayBuffer.isView(buffer)) {
this.buffer = buffer.buffer;
this.view = new DataView(this.buffer, buffer.byteOffset, buffer.byteLength);
} else {
throw new Error('Invalid argument');
}
this.view = new DataView(buffer);
}

function utf8Read(view, offset, length) {
Expand Down
22 changes: 22 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
'use strict';

var notepack = require('../');
var notepackBrowser = { encode : require('../browser/encode.js'),
decode : require('../browser/decode.js') };

function array(length) {
var arr = new Array(length);
Expand Down Expand Up @@ -308,3 +310,23 @@ describe('notepack', function () {
expect(notepack.decode(notepack.encode(fixture))).to.deep.equal(fixture);
});
});

describe('notepack browser', function() {
it('ArrayBuffer view', function() {
expect(notepackBrowser.decode(Uint8Array.from([ 0x93, 1, 2, 3 ]))).to.deep.equal([ 1, 2, 3 ]);
});

it('offset ArrayBuffer view', function() {
var buffer = new ArrayBuffer(14);
var view = new Uint8Array(buffer);

// Fill with junk before setting the encoded data
view.fill(0xFF);

// Put the encoded data somewhere in the middle of the buffer
view.set([ 0x93, 1, 2, 3 ], 4);

expect(notepackBrowser.decode(new Uint8Array(buffer, 4, 4))).to.deep.equal([ 1, 2, 3 ]);
expect(notepackBrowser.decode(new Uint16Array(buffer, 4, 2))).to.deep.equal([ 1, 2, 3 ]);
});
});

0 comments on commit bd91aa7

Please sign in to comment.