# HG changeset patch # User Kim Alvefur # Date 1546767573 -3600 # Node ID 1af5106a2c34efe04975ce65a78ca1c878c9651c # Parent d4a534e6bd7ce2c4e40815da0e66510b768fb52b util.http: Pre-generate urlencoding mappings (optimization) Function calls are more expensive than table lookups diff -r d4a534e6bd7c -r 1af5106a2c34 util/http.lua --- a/util/http.lua Sun Jan 06 09:44:55 2019 +0100 +++ b/util/http.lua Sun Jan 06 10:39:33 2019 +0100 @@ -6,24 +6,25 @@ -- local format, char = string.format, string.char; -local pairs, ipairs, tonumber = pairs, ipairs, tonumber; +local pairs, ipairs = pairs, ipairs; local t_insert, t_concat = table.insert, table.concat; +local url_codes = {}; +for i = 0, 255 do + local c = char(i); + local u = format("%%%02x", i); + url_codes[c] = u; + url_codes[u] = c; +end local function urlencode(s) - return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return format("%%%02x", c:byte()); end)); + return s and (s:gsub("[^a-zA-Z0-9.~_-]", url_codes)); end local function urldecode(s) - return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); + return s and (s:gsub("%%%x%x", url_codes)); end local function _formencodepart(s) - return s and (s:gsub("%W", function (c) - if c ~= " " then - return format("%%%02x", c:byte()); - else - return "+"; - end - end)); + return s and (urlencode(s):gsub("%%20", "+")); end local function formencode(form)