Skip to content

Commit 5daf32d

Browse files
committed
tests/lapi: fix string_byte_test
The patch fixes the following issues: - `string.char()` returns the internal numeric codes of the characters, not a single number. - `string.char()` returns `nil` when values `i` or `j` are outside the acceptable range (less than zero and greater than the length of the string). It is not documented.
1 parent d9134b9 commit 5daf32d

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

tests/lapi/string_byte_test.lua

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
--[[
1+
--[=[[
22
SPDX-License-Identifier: ISC
33
Copyright (c) 2023-2025, Sergey Bronnikov.
44
@@ -7,28 +7,32 @@ https://www.lua.org/manual/5.3/manual.html#6.4
77
88
string.byte gets confused with some out-of-range negative indices,
99
https://www.lua.org/bugs.html#5.1.3-9
10-
]]
1110
12-
-- Synopsis: string.byte(s [, i [, j]])
11+
Synopsis: string.byte(s [, i [, j]])
12+
]]=]
1313

1414
local luzer = require("luzer")
1515
local test_lib = require("lib")
1616

17+
local unpack = unpack or table.unpack
18+
1719
local function TestOneInput(buf, _size)
1820
local fdp = luzer.FuzzedDataProvider(buf)
1921
os.setlocale(test_lib.random_locale(fdp), "all")
2022
local str = fdp:consume_string(test_lib.MAX_STR_LEN)
21-
local i = fdp:consume_integer(0, test_lib.MAX_INT)
22-
local j = fdp:consume_integer(0, test_lib.MAX_INT)
23+
local i = fdp:consume_integer(test_lib.MIN_INT, test_lib.MAX_INT)
24+
local j = fdp:consume_integer(test_lib.MIN_INT, test_lib.MAX_INT)
2325
-- `string.byte()` is the same as `str:byte()`.
2426
assert(string.byte(str, i, j) == str:byte(i, j))
25-
local char_code = string.byte(str, i, j)
26-
if char_code then
27-
assert(type(char_code) == "number")
28-
local byte = string.char(char_code)
29-
assert(byte)
30-
assert(byte == str)
27+
local char_codes = { string.byte(str, i, j) }
28+
-- `string.byte()` returns `nil` when values `i` or `j` are
29+
-- outside the acceptable range (less than zero and greater
30+
-- than the length of the string). It is undocumented.
31+
if #char_codes == 0 then
32+
return
3133
end
34+
local bytes = string.char(unpack(char_codes))
35+
assert(bytes == string.sub(str, i, j))
3236
end
3337

3438
local args = {

0 commit comments

Comments
 (0)