mirror of
https://github.com/SquidDev-CC/CC-Tweaked
synced 2025-05-05 17:04:14 +00:00
Some small optimisations to textutils.urlEncode
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!
This commit is contained in:
parent
89d1be17c9
commit
36d05e4774
@ -944,22 +944,21 @@ unserialiseJSON = unserialise_json
|
|||||||
-- @since 1.31
|
-- @since 1.31
|
||||||
function urlEncode(str)
|
function urlEncode(str)
|
||||||
expect(1, str, "string")
|
expect(1, str, "string")
|
||||||
if str then
|
local gsub, byte, format, band, arshift = string.gsub, string.byte, string.format, bit32.band, bit32.arshift
|
||||||
str = string.gsub(str, "\n", "\r\n")
|
|
||||||
str = string.gsub(str, "([^A-Za-z0-9 %-%_%.])", function(c)
|
str = gsub(str, "\n", "\r\n")
|
||||||
local n = string.byte(c)
|
str = gsub(str, "[^A-Za-z0-9%-%_%.]", function(c)
|
||||||
if n < 128 then
|
if c == " " then return "+" end
|
||||||
-- ASCII
|
|
||||||
return string.format("%%%02X", n)
|
local n = byte(c)
|
||||||
else
|
if n < 128 then
|
||||||
-- Non-ASCII (encode as UTF-8)
|
-- ASCII
|
||||||
return
|
return format("%%%02X", n)
|
||||||
string.format("%%%02X", 192 + bit32.band(bit32.arshift(n, 6), 31)) ..
|
else
|
||||||
string.format("%%%02X", 128 + bit32.band(n, 63))
|
-- Non-ASCII (encode as UTF-8)
|
||||||
end
|
return format("%%%02X%%%02X", 192 + band(arshift(n, 6), 31), 128 + band(n, 63))
|
||||||
end)
|
end
|
||||||
str = string.gsub(str, " ", "+")
|
end)
|
||||||
end
|
|
||||||
return str
|
return str
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@ -296,6 +296,22 @@ describe("The textutils library", function()
|
|||||||
textutils.urlEncode("")
|
textutils.urlEncode("")
|
||||||
expect.error(textutils.urlEncode, nil):eq("bad argument #1 (string expected, got nil)")
|
expect.error(textutils.urlEncode, nil):eq("bad argument #1 (string expected, got nil)")
|
||||||
end)
|
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)
|
end)
|
||||||
|
|
||||||
describe("textutils.complete", function()
|
describe("textutils.complete", function()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user