Avoid negation of signed integers in C that may hold INT*_MIN.

Reported by minoki.
Recent C compilers 'take advantage' of the undefined behavior.
This completely changes the meaning of expressions like (k == -k).
This commit is contained in:
Mike Pall
2022-12-22 00:03:06 +01:00
parent b2791179ef
commit 8a5e398c52
12 changed files with 32 additions and 32 deletions

View File

@@ -55,8 +55,8 @@ LJLIB_CF(bit_tohex)
int32_t i, n = L->base+1 >= L->top ? 8 : lj_lib_checkbit(L, 2);
const char *hexdigits = "0123456789abcdef";
char buf[8];
if (n < 0) { n = -n; hexdigits = "0123456789ABCDEF"; }
if (n > 8) n = 8;
if (n < 0) { n = (int32_t)(~(uint32_t)n+1u); hexdigits = "0123456789ABCDEF"; }
if ((uint32_t)n > 8) n = 8;
for (i = n; --i >= 0; ) { buf[i] = hexdigits[b & 15]; b >>= 4; }
lua_pushlstring(L, buf, (size_t)n);
return 1;