diff --git a/index.js b/index.js index 9b3d1c7f..e7f66a50 100644 --- a/index.js +++ b/index.js @@ -77,7 +77,11 @@ function Buffer (subject, encoding, noZero) { } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data - length = +subject.length > 0 ? Math.floor(+subject.length) : 0 + // Support ArrayBuffer subjects + if (subject.length === undefined && typeof subject.byteLength === 'number') + length = subject.byteLength + else + length = +subject.length > 0 ? Math.floor(+subject.length) : 0 } else throw new Error('First argument needs to be a number, array or string.') diff --git a/test/basic.js b/test/basic.js index 2f79d19a..6c913a07 100644 --- a/test/basic.js +++ b/test/basic.js @@ -138,6 +138,19 @@ test('new buffer from float64array', function (t) { t.end() }) +test('new buffer from ArrayBuffer', function(t) { + if (typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined') { + var b1 = new ArrayBuffer(2) + var dataView = new DataView(b1) + dataView.setInt16(0, 256, true) + var b2 = new B(b1) + t.equal(b1.byteLength, b2.length) + t.equal(b1[0], 0) + t.equal(b1[1], 1) + } + t.end() +}) + test('buffer toArrayBuffer()', function (t) { var data = [1, 2, 3, 4, 5, 6, 7, 8] if (typeof Uint8Array !== 'undefined') {