Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pass Array Buffer to constructor #39

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ 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
length = +subject.length > 0 ? Math.floor(+subject.length) :
+subject.byteLength > 0 ? Math.floor(+subject.byteLength) : 0
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not enough to merely set the right length. You can't directly manipulate the contents of an ArrayBuffer. That's what ArrayBufferViews (like Uint8Array, etc.) are for. So, you'd need to do subject = new Uint8Array(subject)

} else
throw new Error('First argument needs to be a number, array or string.')

Expand Down
14 changes: 14 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,20 @@ test('new buffer from buffer', function (t) {
t.end()
})

test('new buffer from arrayBuffer', function (t) {
if (typeof Uint8Array !== 'undefined') {
var b1 = new Uint8Array([0, 1, 2, 3])
var b2 = new B(b1.buffer)
t.equal(b1.length, b2.length)
t.equal(b1[0], 0)
t.equal(b1[1], 1)
t.equal(b1[2], 2)
t.equal(b1[3], 3)
t.equal(b1[4], undefined)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't actually checking the right buffer, b2.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do'h all I checked was that it failed without this patch

}
t.end()
})

test('new buffer from uint8array', function (t) {
if (typeof Uint8Array !== 'undefined') {
var b1 = new Uint8Array([0, 1, 2, 3])
Expand Down