local W={}local function h(W)return string.format("\037\037\037\048\050\088",string.byte(W))end function W.quote(W,K)if type(W)~="\115\116\114\105\110\103"then return W end W=W:gsub("\n","\r\n")W=W:gsub("\040\091\094\065-\090\097-\122\048-\057 \037-\095\037\046\047\093\041",h)if K then W=W:gsub(" ","\043")W=W:gsub("\047",h)else W=W:gsub(" ","\037\037\050\048")end return W end local function K(W)return string.char(tonumber(W,16))end function W.unquote(W)if type(W)~="\115\116\114\105\110\103"then return W end W=W:gsub("\043"," ")W=W:gsub("\037\037\040\037\120\037\120\041",K)W=W:gsub("\r\n","\n")return W end return W
--- Python-style URL quoting library.
--
-- @module pl.url

local url = {}

local function quote_char(c)
    return string.format("%%%02X", string.byte(c))
end

--- Quote the url, replacing special characters using the '%xx' escape.
-- @string s the string
-- @bool quote_plus Also escape slashes and replace spaces by plus signs.
-- @return The quoted string, or if `s` wasn't a string, just plain unaltered `s`.
function url.quote(s, quote_plus)
    if type(s) ~= "string" then
        return s
    end

    s = s:gsub("\n", "\r\n")
    s = s:gsub("([^A-Za-z0-9 %-_%./])", quote_char)
    if quote_plus then
        s = s:gsub(" ", "+")
        s = s:gsub("/", quote_char)
    else
        s = s:gsub(" ", "%%20")
    end

    return s
end

local function unquote_char(h)
    return string.char(tonumber(h, 16))
end

--- Unquote the url, replacing '%xx' escapes and plus signs.
-- @string s the string
-- @return The unquoted string, or if `s` wasn't a string, just plain unaltered `s`.
function url.unquote(s)
    if type(s) ~= "string" then
        return s
    end

    s = s:gsub("+", " ")
    s = s:gsub("%%(%x%x)", unquote_char)
    s = s:gsub("\r\n", "\n")

    return s
end

return url
