summaryrefslogtreecommitdiff
blob: 36c0ef16cec525da5149adfdfd0b2384c97251d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
From e245d3a18957e43ef902a59a72c8902e2e4435b9 Mon Sep 17 00:00:00 2001
From: Philipp Janda <siffiejoe@gmx.net>
Date: Sat, 10 Oct 2020 16:43:46 +0200
Subject: [PATCH] Fix bit32 conversion issues for Lua 5.1 on 32 bit

The default unsigned conversion procedure from upstream using
`lua_Integer` as an intermediate value fails if `lua_Integer` has only
32 bits (as is the case on 32 bit Lua 5.1). This fix uses a `lua_Number`
(hopefully double) as intermediate value in those cases.
---
 lbitlib.c            | 14 ++++++++++++--
 tests/test-bit32.lua |  1 +
 2 files changed, 13 insertions(+), 2 deletions(-)

diff --git a/lbitlib.c b/lbitlib.c
index 4786c0d..db2652a 100644
--- a/lbitlib.c
+++ b/lbitlib.c
@@ -19,8 +19,18 @@
 #if defined(LUA_COMPAT_BITLIB)		/* { */
 
 
-#define pushunsigned(L,n)	lua_pushinteger(L, (lua_Integer)(n))
-#define checkunsigned(L,i)	((lua_Unsigned)luaL_checkinteger(L,i))
+#define pushunsigned(L,n)	(sizeof(lua_Integer) > 4 ? lua_pushinteger(L, (lua_Integer)(n)) : lua_pushnumber(L, (lua_Number)(n)))
+static lua_Unsigned checkunsigned(lua_State *L, int i) {
+  if (sizeof(lua_Integer) > 4)
+    return (lua_Unsigned)luaL_checkinteger(L, i);
+  else {
+    lua_Number d = luaL_checknumber(L, i);
+    if (d < 0)
+      d = (d + 1) + (~(lua_Unsigned)0);
+    luaL_argcheck(L, d >= 0 && d <= (~(lua_Unsigned)0), i, "value out of range");
+    return (lua_Unsigned)d;
+  }
+}
 
 
 /* number of bits to consider in a number */
diff --git a/tests/test-bit32.lua b/tests/test-bit32.lua
index cc91e52..a408b7d 100755
--- a/tests/test-bit32.lua
+++ b/tests/test-bit32.lua
@@ -4,6 +4,7 @@ local bit32 = require("bit32")
 
 
 assert(bit32.bnot(0) == 2^32-1)
+assert(bit32.bnot(-1) == 0)
 assert(bit32.band(1, 3, 5) == 1)
 assert(bit32.bor(1, 3, 5) == 7)