Skip to content

Commit

Permalink
Some small optimisations to textutils.urlEncode
Browse files Browse the repository at this point in the history
This probably isn't useful in practice — nobody is escaping 1MB of data.
Right. Right???? But no harm in doing it.

 - Cache globals as locals.
 - Remove redundant pattern capture.
 - Merge string.format calls into one.

Also remove the "if str then" check. I assume we accepted nil values a
long time ago, but that was broken when we added arg checks. Woops!
  • Loading branch information
SquidDev committed Aug 30, 2024
1 parent 89d1be1 commit 36d05e4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -944,22 +944,21 @@ unserialiseJSON = unserialise_json
-- @since 1.31
function urlEncode(str)
expect(1, str, "string")
if str then
str = string.gsub(str, "\n", "\r\n")
str = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
local n = string.byte(c)
if n < 128 then
-- ASCII
return string.format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return
string.format("%%%02X", 192 + bit32.band(bit32.arshift(n, 6), 31)) ..
string.format("%%%02X", 128 + bit32.band(n, 63))
end
end)
str = string.gsub(str, " ", "+")
end
local gsub, byte, format, band, arshift = string.gsub, string.byte, string.format, bit32.band, bit32.arshift

str = gsub(str, "\n", "\r\n")
str = gsub(str, "[^A-Za-z0-9%-%_%.]", function(c)
if c == " " then return "+" end

local n = byte(c)
if n < 128 then
-- ASCII
return format("%%%02X", n)
else
-- Non-ASCII (encode as UTF-8)
return format("%%%02X%%%02X", 192 + band(arshift(n, 6), 31), 128 + band(n, 63))
end
end)
return str
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,22 @@ describe("The textutils library", function()
textutils.urlEncode("")
expect.error(textutils.urlEncode, nil):eq("bad argument #1 (string expected, got nil)")
end)

it("encodes newlines", function()
expect(textutils.urlEncode("a\nb")):eq("a%0D%0Ab")
end)

it("leaves normal characters as-is", function()
expect(textutils.urlEncode("abcABC0123")):eq("abcABC0123")
end)

it("escapes spaces", function()
expect(textutils.urlEncode("a b c")):eq("a+b+c")
end)

it("escapes special characters", function()
expect(textutils.urlEncode("a%b\0\255")):eq("a%25b%00%C3%BF")
end)
end)

describe("textutils.complete", function()
Expand Down

0 comments on commit 36d05e4

Please sign in to comment.