Assert for negative `field` in bit32 polyfill

This more closely matches the behavior of lua5.2.
This commit is contained in:
Guldoman 2022-01-12 19:56:09 +01:00
parent 51975472a9
commit e51c76c72b
No known key found for this signature in database
GPG Key ID: C08A498EC7F1AFDD
1 changed files with 9 additions and 4 deletions

View File

@ -11,18 +11,23 @@ local function mask(n)
return (~((ALLONES << 1) << ((n) - 1))) return (~((ALLONES << 1) << ((n) - 1)))
end end
local function check_args(field, width)
assert(field >= 0, "field cannot be negative")
assert(width > 0, "width must be positive")
assert(field + width < LUA_NBITS and field + width >= 0,
"trying to access non-existent bits")
end
function bit.extract(n, field, width) function bit.extract(n, field, width)
local w = width or 1 local w = width or 1
assert(w > 0, "width must be positive") check_args(field, w)
assert(field + w < LUA_NBITS and field + w >= 0, "trying to access non-existent bits")
local m = trim(n) local m = trim(n)
return m >> field & mask(w) return m >> field & mask(w)
end end
function bit.replace(n, v, field, width) function bit.replace(n, v, field, width)
local w = width or 1 local w = width or 1
assert(w > 0, "width must be positive") check_args(field, w)
assert(field + w < LUA_NBITS and field + w >= 0, "trying to access non-existent bits")
local m = trim(n) local m = trim(n)
local x = v & mask(width); local x = v & mask(width);
return m & ~(mask(w) << field) | (x << field) return m & ~(mask(w) << field) | (x << field)