-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharbitrary-binary-string.lua
More file actions
43 lines (35 loc) · 898 Bytes
/
arbitrary-binary-string.lua
File metadata and controls
43 lines (35 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
local abs = {}
local escapes = {
['\a'] = '\\a',
['\b'] = '\\b',
['\f'] = '\\f',
['\n'] = '\\n',
['\r'] = '\\r',
['\t'] = '\\t',
['\v'] = '\\v',
['\\'] = '\\\\',
['"'] = '\\"',
}
abs.ESCAPE_MINIMAL = '[\r\n\\"]'
abs.ESCAPE_CONTROL_CHARS = '[%c\r\n\\"]'
abs.ESCAPE_ALL_NONASCII = '[%c\r\n\\"\128-\255]'
function abs.encode(data, escape_pattern)
if not escape_pattern then escape_pattern = abs.ESCAPE_MINIMAL end
return data:gsub(escape_pattern, function(char)
return escapes[char] or string.format('\\%03d', string.byte(char))
end)
end
function abs.decode(encoded)
return abs.loadchunk(abs.getchunk(encoded))
end
function abs.quotedstring(encoded)
return '"' .. encoded .. '"'
end
function abs.getchunk(encoded)
return "return " .. abs.quotedstring(encoded)
end
function abs.loadchunk(chunk)
local loadfn = loadstring or load
return assert(loadfn(chunk))()
end
return abs