Skip to content

Commit bd91aa7

Browse files
nkochakiandarrachequesne
authored andcommitted
fix(browser): preserve the offset and length when creating a DataView (#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.
1 parent 75f5ac2 commit bd91aa7

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

browser/decode.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@ function Decoder(buffer) {
44
this.offset = 0;
55
if (buffer instanceof ArrayBuffer) {
66
this.buffer = buffer;
7+
this.view = new DataView(this.buffer);
78
} else if (ArrayBuffer.isView(buffer)) {
89
this.buffer = buffer.buffer;
10+
this.view = new DataView(this.buffer, buffer.byteOffset, buffer.byteLength);
911
} else {
1012
throw new Error('Invalid argument');
1113
}
12-
this.view = new DataView(buffer);
1314
}
1415

1516
function utf8Read(view, offset, length) {

test/test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
'use strict';
22

33
var notepack = require('../');
4+
var notepackBrowser = { encode : require('../browser/encode.js'),
5+
decode : require('../browser/decode.js') };
46

57
function array(length) {
68
var arr = new Array(length);
@@ -308,3 +310,23 @@ describe('notepack', function () {
308310
expect(notepack.decode(notepack.encode(fixture))).to.deep.equal(fixture);
309311
});
310312
});
313+
314+
describe('notepack browser', function() {
315+
it('ArrayBuffer view', function() {
316+
expect(notepackBrowser.decode(Uint8Array.from([ 0x93, 1, 2, 3 ]))).to.deep.equal([ 1, 2, 3 ]);
317+
});
318+
319+
it('offset ArrayBuffer view', function() {
320+
var buffer = new ArrayBuffer(14);
321+
var view = new Uint8Array(buffer);
322+
323+
// Fill with junk before setting the encoded data
324+
view.fill(0xFF);
325+
326+
// Put the encoded data somewhere in the middle of the buffer
327+
view.set([ 0x93, 1, 2, 3 ], 4);
328+
329+
expect(notepackBrowser.decode(new Uint8Array(buffer, 4, 4))).to.deep.equal([ 1, 2, 3 ]);
330+
expect(notepackBrowser.decode(new Uint16Array(buffer, 4, 2))).to.deep.equal([ 1, 2, 3 ]);
331+
});
332+
});

0 commit comments

Comments
 (0)