diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2019-03-27 14:56:10 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2019-03-27 14:56:10 -0300 |
commit | d12262068d689eacc452a459a021df0ad8f6d46c (patch) | |
tree | d3e839cd1ddf3daf5e12c8f472c10a980b7d9d8c /ltablib.c | |
parent | 0443ad9e288825b6e4441eb11104bcdb4ff4593a (diff) | |
download | lua-d12262068d689eacc452a459a021df0ad8f6d46c.tar.gz lua-d12262068d689eacc452a459a021df0ad8f6d46c.tar.bz2 lua-d12262068d689eacc452a459a021df0ad8f6d46c.zip |
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.
Diffstat (limited to 'ltablib.c')
-rw-r--r-- | ltablib.c | 8 |
1 files changed, 6 insertions, 2 deletions
@@ -69,7 +69,9 @@ static int tinsert (lua_State *L) { | |||
69 | case 3: { | 69 | case 3: { |
70 | lua_Integer i; | 70 | lua_Integer i; |
71 | pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ | 71 | pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ |
72 | luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); | 72 | /* check whether 'pos' is in [1, e] */ |
73 | luaL_argcheck(L, (lua_Unsigned)pos - 1u < (lua_Unsigned)e, 2, | ||
74 | "position out of bounds"); | ||
73 | for (i = e; i > pos; i--) { /* move up elements */ | 75 | for (i = e; i > pos; i--) { /* move up elements */ |
74 | lua_geti(L, 1, i - 1); | 76 | lua_geti(L, 1, i - 1); |
75 | lua_seti(L, 1, i); /* t[i] = t[i - 1] */ | 77 | lua_seti(L, 1, i); /* t[i] = t[i - 1] */ |
@@ -89,7 +91,9 @@ static int tremove (lua_State *L) { | |||
89 | lua_Integer size = aux_getn(L, 1, TAB_RW); | 91 | lua_Integer size = aux_getn(L, 1, TAB_RW); |
90 | lua_Integer pos = luaL_optinteger(L, 2, size); | 92 | lua_Integer pos = luaL_optinteger(L, 2, size); |
91 | if (pos != size) /* validate 'pos' if given */ | 93 | if (pos != size) /* validate 'pos' if given */ |
92 | luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); | 94 | /* check whether 'pos' is in [1, size + 1] */ |
95 | luaL_argcheck(L, (lua_Unsigned)pos - 1u <= (lua_Unsigned)size, 1, | ||
96 | "position out of bounds"); | ||
93 | lua_geti(L, 1, pos); /* result = t[pos] */ | 97 | lua_geti(L, 1, pos); /* result = t[pos] */ |
94 | for ( ; pos < size; pos++) { | 98 | for ( ; pos < size; pos++) { |
95 | lua_geti(L, 1, pos + 1); | 99 | lua_geti(L, 1, pos + 1); |