encoder: Break apart the encoder into distinct modules + add call encoding
[luajson.git] / src / json / encode / strings.lua
blobe40dc6eedb1bc6623db42f013911c6b8141fba5c
1 local string_char = string.char
3 module("json.encode.strings")
5 local encodingMap = {
6 ['\\'] = '\\\\',
7 ['"'] = '\\"',
8 ['\n'] = '\\n',
9 ['\t'] = '\\t',
10 ['\b'] = '\\b',
11 ['\f'] = '\\f',
12 ['\r'] = '\\r',
13 ['/'] = '\\/'
16 -- Pre-encode the control characters to speed up encoding...
17 -- NOTE: UTF-8 may not work out right w/ JavaScript
18 -- JavaScript uses 2 bytes after a \u... yet UTF-8 is a
19 -- byte-stream encoding, not pairs of bytes (it does encode
20 -- some letters > 1 byte, but base case is 1)
21 for i = 1, 255 do
22 local c = string_char(i)
23 if c:match('%c') and not encodingMap[c] then
24 encodingMap[c] = ('\\u%.4X'):format(i)
25 end
26 end
28 function encode(s, options)
29 local stringPreprocess = options and options.strings and options.strings.preProcess
30 if stringPreprocess then
31 s = stringPreprocess(s)
32 end
33 return '"' .. s:gsub('[\\"/%c%z]', encodingMap) .. '"'
34 end