Implement truncate operations

This commit is contained in:
Rerumu 2021-11-26 22:31:44 -05:00
parent c0a5d0c7dd
commit 9126b43b1f

View File

@ -22,6 +22,14 @@ typedef union {
} Reinterpret; } Reinterpret;
]] ]]
local function truncate(num)
if num >= 0 then
return math.floor(num)
else
return math.ceil(num)
end
end
do do
local div = {} local div = {}
@ -30,7 +38,7 @@ do
function div.i32(lhs, rhs) function div.i32(lhs, rhs)
if rhs == 0 then error('division by zero') end if rhs == 0 then error('division by zero') end
return math.floor(lhs / rhs) return truncate(lhs / rhs)
end end
function div.u32(lhs, rhs) function div.u32(lhs, rhs)
@ -198,8 +206,9 @@ do
end end
do do
local extend = {}
local wrap = {} local wrap = {}
local trunc = {}
local extend = {}
local convert = {} local convert = {}
local reinterpret = {} local reinterpret = {}
@ -207,23 +216,35 @@ do
-- ... thankfully this isn't one. -- ... thankfully this isn't one.
local RE_INSTANCE = ffi.new('Reinterpret') local RE_INSTANCE = ffi.new('Reinterpret')
module.extend = extend local function truncate_i64(num) return i64(truncate(num)) end
module.wrap = wrap module.wrap = wrap
module.trunc = trunc
module.extend = extend
module.convert = convert module.convert = convert
module.reinterpret = reinterpret module.reinterpret = reinterpret
function extend.u64_i32(num)
RE_INSTANCE.i32 = num
return RE_INSTANCE.i64
end
function wrap.i32_i64(num) function wrap.i32_i64(num)
RE_INSTANCE.i64 = num RE_INSTANCE.i64 = num
return RE_INSTANCE.i32 return RE_INSTANCE.i32
end end
trunc.i32_f32 = truncate
trunc.i32_f64 = truncate
trunc.u32_f32 = truncate
trunc.u32_f64 = truncate
trunc.i64_f32 = truncate_i64
trunc.i64_f64 = truncate_i64
trunc.u64_f32 = truncate_i64
trunc.u64_f64 = truncate_i64
function extend.u64_i32(num)
RE_INSTANCE.i32 = num
return RE_INSTANCE.i64
end
function convert.f32_i32(num) return num end function convert.f32_i32(num) return num end
function convert.f32_u32(num) return tonumber(u32(num)) end function convert.f32_u32(num) return tonumber(u32(num)) end
function convert.f32_i64(num) return tonumber(num) end function convert.f32_i64(num) return tonumber(num) end