From d12262068d689eacc452a459a021df0ad8f6d46c Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Wed, 27 Mar 2019 14:56:10 -0300 Subject: Small optimizations in range checks Checks of the form '1 <= x && x <= M' were rewritten in the form '(unsigned)x - 1 < (unsigned)M', which is usually more efficient. (Other similar checks have similar translations.) Although some compilers do these optimizations, that does not happen for all compilers or all cases. --- ltablib.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'ltablib.c') diff --git a/ltablib.c b/ltablib.c index 29c53e94..a9169f9e 100644 --- a/ltablib.c +++ b/ltablib.c @@ -69,7 +69,9 @@ static int tinsert (lua_State *L) { case 3: { lua_Integer i; pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ - luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); + /* check whether 'pos' is in [1, e] */ + luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2, + "position out of bounds"); for (i = e; i > pos; i--) { /* move up elements */ lua_geti(L, 1, i - 1); lua_seti(L, 1, i); /* t[i] = t[i - 1] */ @@ -89,7 +91,9 @@ static int tremove (lua_State *L) { lua_Integer size = aux_getn(L, 1, TAB_RW); lua_Integer pos = luaL_optinteger(L, 2, size); if (pos != size) /* validate 'pos' if given */ - luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); + /* check whether 'pos' is in [1, size + 1] */ + luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 1, + "position out of bounds"); lua_geti(L, 1, pos); /* result = t[pos] */ for ( ; pos < size; pos++) { lua_geti(L, 1, pos + 1); -- cgit v1.2.3-55-g6feb