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)
 
