Comparison

util/http.lua @ 9759:1af5106a2c34

util.http: Pre-generate urlencoding mappings (optimization) Function calls are more expensive than table lookups
author Kim Alvefur <zash@zash.se>
date Sun, 06 Jan 2019 10:39:33 +0100
parent 9504:cfbea3064aa9
child 9785:ff88b03c343f
comparison
equal deleted inserted replaced
9758:d4a534e6bd7c 9759:1af5106a2c34
4 -- This project is MIT/X11 licensed. Please see the 4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information. 5 -- COPYING file in the source package for more information.
6 -- 6 --
7 7
8 local format, char = string.format, string.char; 8 local format, char = string.format, string.char;
9 local pairs, ipairs, tonumber = pairs, ipairs, tonumber; 9 local pairs, ipairs = pairs, ipairs;
10 local t_insert, t_concat = table.insert, table.concat; 10 local t_insert, t_concat = table.insert, table.concat;
11 11
12 local url_codes = {};
13 for i = 0, 255 do
14 local c = char(i);
15 local u = format("%%%02x", i);
16 url_codes[c] = u;
17 url_codes[u] = c;
18 end
12 local function urlencode(s) 19 local function urlencode(s)
13 return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return format("%%%02x", c:byte()); end)); 20 return s and (s:gsub("[^a-zA-Z0-9.~_-]", url_codes));
14 end 21 end
15 local function urldecode(s) 22 local function urldecode(s)
16 return s and (s:gsub("%%(%x%x)", function (c) return char(tonumber(c,16)); end)); 23 return s and (s:gsub("%%%x%x", url_codes));
17 end 24 end
18 25
19 local function _formencodepart(s) 26 local function _formencodepart(s)
20 return s and (s:gsub("%W", function (c) 27 return s and (urlencode(s):gsub("%%20", "+"));
21 if c ~= " " then
22 return format("%%%02x", c:byte());
23 else
24 return "+";
25 end
26 end));
27 end 28 end
28 29
29 local function formencode(form) 30 local function formencode(form)
30 local result = {}; 31 local result = {};
31 if form[1] then -- Array of ordered { name, value } 32 if form[1] then -- Array of ordered { name, value }