Skip to content

Commit

Permalink
Implement ArrayBuffer handling for moreTypes #135
Browse files Browse the repository at this point in the history
  • Loading branch information
kriszyp committed May 10, 2024
1 parent 2550f79 commit 943ed70
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions pack.js
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,7 @@ function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
}
target[position++] = 0x74 // "t" for typed array
target[position++] = type
if (!typedArray.buffer) typedArray = new Uint8Array(typedArray)
target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position)
}
function writeBuffer(buffer, allocateForWrite) {
Expand Down
10 changes: 9 additions & 1 deletion tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -708,8 +708,12 @@ suite('msgpackr basic tests', function() {
test: 'string',
children: [
{ name: 'child' }
]
],
value: new ArrayBuffer(10)
}
let u8 = new Uint8Array(object.value)
u8[0] = 1
u8[1] = 2
object.self = object
object.children[1] = object
object.children[2] = object.children[0]
Expand All @@ -725,6 +729,10 @@ suite('msgpackr basic tests', function() {
assert.equal(deserialized.children[1], deserialized)
assert.equal(deserialized.children[0], deserialized.children[2])
assert.equal(deserialized.children, deserialized.childrenAgain)
assert.equal(deserialized.value.constructor.name, 'ArrayBuffer')
u8 = new Uint8Array(deserialized.value)
assert.equal(u8[0], 1)
assert.equal(u8[1], 2)
})

test('structured cloning: types', function() {
Expand Down
9 changes: 8 additions & 1 deletion unpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -1054,8 +1054,15 @@ let glbl = typeof globalThis === 'object' ? globalThis : window;
currentExtensions[0x74] = (data) => {
let typeCode = data[0]
let typedArrayName = typedArrays[typeCode]
if (!typedArrayName)
if (!typedArrayName) {
if (typeCode === 16) {
let ab = new ArrayBuffer(data.length - 1)
let u8 = new Uint8Array(ab)
u8.set(data.subarray(1))
return ab;
}
throw new Error('Could not find typed array for code ' + typeCode)
}
// we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
}
Expand Down

0 comments on commit 943ed70

Please sign in to comment.