Skip to content
Open
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
11 changes: 10 additions & 1 deletion lib/web/webidl/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,16 @@ webidl.util.ConvertToInt = function (V, bitLength, signedness, flags) {
x = webidl.util.IntegerPart(x)

// 10. Set x to x modulo 2^bitLength.
x = x % Math.pow(2, bitLength)
// Use the ECMA-262 "modulo" definition whose result has the sign of the
// divisor, so negative inputs wrap via two's complement instead of being
// returned as-is. Normalize a potential -0 to +0.
const y = Math.pow(2, bitLength)
x = x % y
if (x < 0) {
x += y
} else if (x === 0) {
x = 0
}

// 11. If signedness is "signed" and x ≥ 2^(bitLength − 1),
// then return x − 2^bitLength.
Expand Down
13 changes: 12 additions & 1 deletion test/webidl/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ test('webidl.util.ConvertToInt(V)', () => {
assert.equal(ConvertToInt(-max - 1, 64, 'signed'), -max, 'signed neg')

assert.equal(ConvertToInt(max + 1, 64, 'unsigned'), max + 1, 'unsigned pos')
assert.equal(ConvertToInt(-max - 1, 64, 'unsigned'), -max - 1, 'unsigned neg')
assert.equal(ConvertToInt(-max - 1, 64, 'unsigned'), 2 ** 64 - max, 'unsigned neg wraps to two\'s complement')

for (const signedness of ['signed', 'unsigned']) {
assert.equal(ConvertToInt(Infinity, 64, signedness), 0)
Expand Down Expand Up @@ -144,4 +144,15 @@ test('webidl.util.ConvertToInt(V)', () => {
-(2 ** 31),
'32-bit signed EnforceRange lower bound'
)

// Negative inputs must wrap via two's complement instead of being returned
// as-is. These mirror the corresponding typed-array behavior, e.g.
// new Uint8Array([-3])[0] === 253, new Int8Array([-200])[0] === 56.
assert.equal(ConvertToInt(-3, 8, 'unsigned'), 253, '8-bit unsigned wraps -3 to 253')
assert.equal(ConvertToInt(-1, 32, 'unsigned'), 4294967295, '32-bit unsigned wraps -1')
assert.equal(ConvertToInt(-200, 8, 'signed'), 56, '8-bit signed wraps -200 to 56')
assert.ok(
Object.is(ConvertToInt(-256, 8, 'unsigned'), 0),
'modulo wrap of negative multiple of 2^bitLength returns +0, not -0'
)
})
Loading