From 6021ff8ec6194601af98dcc92b32143ea2a4a3b1 Mon Sep 17 00:00:00 2001 From: Jon Michael Aanes Date: Sat, 22 Jul 2017 13:53:15 +0200 Subject: [PATCH] Removed some debug prints, and improved code structure --- pstring.lua | 48 ++++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/pstring.lua b/pstring.lua index 0600c55..da7f12f 100644 --- a/pstring.lua +++ b/pstring.lua @@ -40,33 +40,37 @@ local CHARACTERS_THAT_REQUIRE_ESCAPE_SEQ = '[%z\001-\008\011-\031\127]' -------------------------------------------------------------------------------- -- Util -local function requires_weird_escape_seq (str) +local function does_string_require_escaping (str) return not not str:find(CHARACTERS_THAT_REQUIRE_ESCAPE_SEQ) end -local function escape_string (str) - -- Attempts to escape the string, to a format that is both a valid Lua - -- constant, and ledible unicode. +local escape_string do - -- TODO: Escape invalid unicode sequences. + local ESCAPE_SINGLE_BYTE = function (char) return CHAR_TO_STR_REPR[char:byte()] end + local ESCAPE_MALFORMED_CONT_BYTE = function (a, b) return a..'\\' .. b:byte() end + local ESCAPE_MALFORMED_START_BYTE = function (a, b) return '\\'..a:byte() .. b end - -- Error checking - assert(type(str) == 'string') + function escape_string (str) + -- Attempts to escape the string, to a format that is both a valid Lua + -- constant, and ledible unicode. - -- First escape the easy ones. - local str = str:gsub('.', function (char) return CHAR_TO_STR_REPR[char:byte()] end) - -- Escape malformed continuation characters - repeat - local count - str, count = str:gsub('([^\128-\255])([\128-\191])', function(a, b) print(a,b) return a..'\\' .. b:byte() end) - until count == 0 - -- Escape malformed start characters - repeat - local count - str, count = str:gsub('([\191-\255])([^\128-\191])', function(a, b) print(a,b) return '\\'..a:byte() .. b end) - until count == 0 - -- return - return str + -- Error checking + assert(type(str) == 'string') + + -- Escape single bytes + local str, count = str:gsub('.', ESCAPE_SINGLE_BYTE), 0 + + -- Escape malformed continuation bytes + repeat str, count = str:gsub('([^\128-\255])([\128-\191])', ESCAPE_MALFORMED_CONT_BYTE) + until count == 0 + + -- Escape malformed start bytes + repeat str, count = str:gsub('([\191-\255])([^\128-\191])', ESCAPE_MALFORMED_START_BYTE) + until count == 0 + + -- Done, lets return + return str + end end local function smallest_secure_longform_string_level (str) @@ -189,7 +193,7 @@ return function (str, depth, l) return format_shortform_string(str, depth, l) elseif depth > 0 then return format_cut_string (str, depth, l) - elseif requires_weird_escape_seq (str) then + elseif does_string_require_escaping (str) then return format_concatted_string(str, depth, l) else return format_longform_string(str, depth, l)