diff --git a/lib/serialize/buffers.js b/lib/serialize/buffers.js index bd0add26..355a8599 100644 --- a/lib/serialize/buffers.js +++ b/lib/serialize/buffers.js @@ -158,33 +158,32 @@ registerSerializer(ARRAY_BUFFER_TYPE, serializeArrayBuffer); function serializeSharedArrayBuffer(record) { const uint = new Uint8Array(record.extra.buf); - let valNodes, - numTrailingZeros = 0, - firstNonZeroIndex = 0; - uint.forEach((val, index) => { - if (val !== 0) { - if (!valNodes) { - valNodes = []; - firstNonZeroIndex = index; - } - valNodes.push(t.numericLiteral(val)); - numTrailingZeros = 0; - } else if (valNodes) { - valNodes.push(null); - numTrailingZeros++; - } - }); - // `new SharedArrayBuffer(8)` + const len = uint.length; const node = t.newExpression( this.traceAndSerializeGlobal(SharedArrayBuffer), - [t.numericLiteral(uint.length)] + [t.numericLiteral(len)] ); - if (valNodes) { - // `new Uint8Array(arr).set([1, 2, 3]);` + // Set non-zero values (if any) + const firstNonZeroIndex = uint.findIndex(byte => byte !== 0); + if (firstNonZeroIndex !== -1) { + const valNodes = []; + let numTrailingZeros = 0; + for (let index = firstNonZeroIndex; index < len; index++) { + const val = uint[index]; + if (val === 0) { + valNodes.push(null); + numTrailingZeros++; + } else { + valNodes.push(t.numericLiteral(val)); + numTrailingZeros = 0; + } + } + if (numTrailingZeros > 0) valNodes.length -= numTrailingZeros; + // `new Uint8Array(arr).set([1, 2, 3]);` this.assignmentNodes.push( t.expressionStatement( t.callExpression(