Removed 'int' size limit for string.rep

This commit is contained in:
Roberto Ierusalimschy 2024-06-21 16:26:49 -03:00
parent ec65ab878e
commit ef28e5f789
2 changed files with 5 additions and 16 deletions

View File

@ -37,16 +37,6 @@
#endif #endif
/*
** Some sizes are better limited to fit in 'int', but must also fit in
** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
*/
#define MAXSIZE \
(sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
static int str_len (lua_State *L) { static int str_len (lua_State *L) {
size_t l; size_t l;
luaL_checklstring(L, 1, &l); luaL_checklstring(L, 1, &l);
@ -149,10 +139,10 @@ static int str_rep (lua_State *L) {
const char *sep = luaL_optlstring(L, 3, "", &lsep); const char *sep = luaL_optlstring(L, 3, "", &lsep);
if (n <= 0) if (n <= 0)
lua_pushliteral(L, ""); lua_pushliteral(L, "");
else if (l_unlikely(l + lsep < l || l + lsep > MAXSIZE / n)) else if (l_unlikely(l + lsep < l || l + lsep > MAX_SIZE / n))
return luaL_error(L, "resulting string too large"); return luaL_error(L, "resulting string too large");
else { else {
size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep; size_t totallen = ((size_t)n * (l + lsep)) - lsep;
luaL_Buffer b; luaL_Buffer b;
char *p = luaL_buffinitsize(L, &b, totallen); char *p = luaL_buffinitsize(L, &b, totallen);
while (n-- > 1) { /* first n-1 copies (followed by separator) */ while (n-- > 1) { /* first n-1 copies (followed by separator) */

View File

@ -109,10 +109,9 @@ assert(string.rep('teste', 0) == '')
assert(string.rep('tés\00', 2) == 'tés\0têtés\000') assert(string.rep('tés\00', 2) == 'tés\0têtés\000')
assert(string.rep('', 10) == '') assert(string.rep('', 10) == '')
if string.packsize("i") == 4 then do
-- result length would be 2^31 (int overflow) checkerror("too large", string.rep, 'aa', math.maxinteger);
checkerror("too large", string.rep, 'aa', (1 << 30)) checkerror("too large", string.rep, 'a', math.maxinteger/2, ',')
checkerror("too large", string.rep, 'a', (1 << 30), ',')
end end
-- repetitions with separator -- repetitions with separator