1 -- Copyright 2008 Steven Barth <steven@midlink.org>
2 -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
3 -- Licensed to the public under the Apache License 2.0.
5 local nixio = require "nixio"
6 local util = require "luci.util"
7 local table = require "table"
8 local string = require "string"
9 local coroutine = require "coroutine"
12 local tonumber = tonumber
13 local tostring = tostring
21 local band = nixio.bit.band
22 local bor = nixio.bit.bor
23 local rshift = nixio.bit.rshift
24 local char = string.char
26 local getmetatable = getmetatable
31 function decode(json, ...)
32 local a = ActiveDecoder(function() return nil end, ...)
34 local s, obj = pcall(a.get, a)
35 return s and obj or nil
39 function encode(obj, ...)
41 local e = Encoder(obj, 1, ...):source()
47 return not err and table.concat(out) or nil
55 Encoder = util.class()
57 function Encoder.__init__(self, data, buffersize, fastescape)
59 self.buffersize = buffersize or 512
61 self.fastescape = fastescape
63 getmetatable(self).__call = Encoder.source
66 function Encoder.source(self)
67 local source = coroutine.create(self.dispatch)
69 local res, data = coroutine.resume(source, self, self.data, true)
78 function Encoder.dispatch(self, data, start)
79 local parser = self.parsers[type(data)]
84 if #self.buffer > 0 then
85 coroutine.yield(self.buffer)
92 function Encoder.put(self, chunk)
93 if self.buffersize < 2 then
94 coroutine.yield(chunk)
96 if #self.buffer + #chunk > self.buffersize then
98 local fbuffer = self.buffersize - #self.buffer
100 coroutine.yield(self.buffer .. chunk:sub(written + 1, fbuffer))
103 while #chunk - written > self.buffersize do
104 fbuffer = written + self.buffersize
105 coroutine.yield(chunk:sub(written + 1, fbuffer))
109 self.buffer = chunk:sub(written + 1)
111 self.buffer = self.buffer .. chunk
116 function Encoder.parse_nil(self)
120 function Encoder.parse_bool(self, obj)
121 self:put(obj and "true" or "false")
124 function Encoder.parse_number(self, obj)
125 self:put(tostring(obj))
128 function Encoder.parse_string(self, obj)
129 if self.fastescape then
130 self:put('"' .. obj:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"')
135 return '\\u00%02x' % char:byte()
142 function Encoder.parse_iter(self, obj)
144 return self:put("null")
147 if type(obj) == "table" and (#obj == 0 and next(obj)) then
151 for key, entry in pairs(obj) do
153 first = first or self:put(",")
154 first = first and false
155 self:parse_string(tostring(key))
166 if type(obj) == "table" then
168 first = first or self:put(",")
169 first = first and nil
170 self:dispatch(obj[i])
174 first = first or self:put(",")
175 first = first and nil
184 function Encoder.parse_udata(self, obj)
185 return self:parse_string(tostring(obj))
189 ['nil'] = Encoder.parse_nil,
190 ['table'] = Encoder.parse_iter,
191 ['number'] = Encoder.parse_number,
192 ['string'] = Encoder.parse_string,
193 ['boolean'] = Encoder.parse_bool,
194 ['function'] = Encoder.parse_iter,
195 ['userdata'] = Encoder.parse_udata,
199 Decoder = util.class()
201 function Decoder.__init__(self, customnull)
202 self.cnull = customnull
203 getmetatable(self).__call = Decoder.sink
206 function Decoder.sink(self)
207 local sink = coroutine.create(self.dispatch)
209 return coroutine.resume(sink, self, ...)
214 function Decoder.get(self)
218 function Decoder.dispatch(self, chunk, src_err, strict)
219 local robject, object
223 while chunk and #chunk < 1 do
227 assert(not strict or chunk, "Unexpected EOS")
228 if not chunk then break end
230 local char = chunk:sub(1, 1)
231 local parser = self.parsers[char]
232 or (char:match("%s") and self.parse_space)
233 or (char:match("[0-9-]") and self.parse_number)
234 or error("Unexpected char '%s'" % char)
236 chunk, robject = parser(self, chunk)
238 if parser ~= self.parse_space then
239 assert(not oset, "Scope violation: Too many objects")
249 assert(not src_err, src_err)
250 assert(oset, "Unexpected EOS")
256 function Decoder.fetch(self)
257 local tself, chunk, src_err = coroutine.yield()
258 assert(chunk or not src_err, src_err)
263 function Decoder.fetch_atleast(self, chunk, bytes)
264 while #chunk < bytes do
265 local nchunk = self:fetch()
266 assert(nchunk, "Unexpected EOS")
267 chunk = chunk .. nchunk
274 function Decoder.fetch_until(self, chunk, pattern)
275 local start = chunk:find(pattern)
278 local nchunk = self:fetch()
279 assert(nchunk, "Unexpected EOS")
280 chunk = chunk .. nchunk
281 start = chunk:find(pattern)
288 function Decoder.parse_space(self, chunk)
289 local start = chunk:find("[^%s]")
296 start = chunk:find("[^%s]")
299 return chunk:sub(start)
303 function Decoder.parse_literal(self, chunk, literal, value)
304 chunk = self:fetch_atleast(chunk, #literal)
305 assert(chunk:sub(1, #literal) == literal, "Invalid character sequence")
306 return chunk:sub(#literal + 1), value
310 function Decoder.parse_null(self, chunk)
311 return self:parse_literal(chunk, "null", self.cnull and null)
315 function Decoder.parse_true(self, chunk)
316 return self:parse_literal(chunk, "true", true)
320 function Decoder.parse_false(self, chunk)
321 return self:parse_literal(chunk, "false", false)
325 function Decoder.parse_number(self, chunk)
326 local chunk, start = self:fetch_until(chunk, "[^0-9eE.+-]")
327 local number = tonumber(chunk:sub(1, start - 1))
328 assert(number, "Invalid number specification")
329 return chunk:sub(start), number
333 function Decoder.parse_string(self, chunk)
336 assert(chunk:sub(1, 1) == '"', 'Expected "')
340 local spos = chunk:find('[\\"]')
342 str = str .. chunk:sub(1, spos - 1)
344 local char = chunk:sub(spos, spos)
345 if char == '"' then -- String end
346 chunk = chunk:sub(spos + 1)
348 elseif char == "\\" then -- Escape sequence
349 chunk, object = self:parse_escape(chunk:sub(spos))
355 assert(chunk, "Unexpected EOS while parsing a string")
363 function Decoder.utf8_encode(self, s1, s2)
364 local n = s1 * 256 + s2
366 if n >= 0 and n <= 0x7F then
368 elseif n >= 0 and n <= 0x7FF then
370 bor(band(rshift(n, 6), 0x1F), 0xC0),
371 bor(band(n, 0x3F), 0x80)
373 elseif n >= 0 and n <= 0xFFFF then
375 bor(band(rshift(n, 12), 0x0F), 0xE0),
376 bor(band(rshift(n, 6), 0x3F), 0x80),
377 bor(band(n, 0x3F), 0x80)
379 elseif n >= 0 and n <= 0x10FFFF then
381 bor(band(rshift(n, 18), 0x07), 0xF0),
382 bor(band(rshift(n, 12), 0x3F), 0x80),
383 bor(band(rshift(n, 6), 0x3F), 0x80),
384 bor(band(n, 0x3F), 0x80)
392 function Decoder.parse_escape(self, chunk)
394 chunk = self:fetch_atleast(chunk:sub(2), 1)
395 local char = chunk:sub(1, 1)
400 elseif char == "\\" then
402 elseif char == "u" then
403 chunk = self:fetch_atleast(chunk, 4)
404 local s1, s2 = chunk:sub(1, 2), chunk:sub(3, 4)
405 s1, s2 = tonumber(s1, 16), tonumber(s2, 16)
406 assert(s1 and s2, "Invalid Unicode character")
408 return chunk:sub(5), self:utf8_encode(s1, s2)
409 elseif char == "/" then
411 elseif char == "b" then
413 elseif char == "f" then
415 elseif char == "n" then
417 elseif char == "r" then
419 elseif char == "t" then
422 error("Unexpected escaping sequence '\\%s'" % char)
427 function Decoder.parse_array(self, chunk)
432 local chunk, object = self:parse_delimiter(chunk, "%]")
439 chunk, object = self:dispatch(chunk, nil, true)
440 table.insert(array, nextp, object)
443 chunk, object = self:parse_delimiter(chunk, ",%]")
444 assert(object, "Delimiter expected")
451 function Decoder.parse_object(self, chunk)
456 local chunk, object = self:parse_delimiter(chunk, "}")
463 chunk = self:parse_space(chunk)
464 assert(chunk, "Unexpected EOS")
466 chunk, name = self:parse_string(chunk)
468 chunk, object = self:parse_delimiter(chunk, ":")
469 assert(object, "Separator expected")
471 chunk, object = self:dispatch(chunk, nil, true)
474 chunk, object = self:parse_delimiter(chunk, ",}")
475 assert(object, "Delimiter expected")
482 function Decoder.parse_delimiter(self, chunk, delimiter)
484 chunk = self:fetch_atleast(chunk, 1)
485 local char = chunk:sub(1, 1)
486 if char:match("%s") then
487 chunk = self:parse_space(chunk)
488 assert(chunk, "Unexpected EOS")
489 elseif char:match("[%s]" % delimiter) then
490 return chunk:sub(2), char
499 ['"'] = Decoder.parse_string,
500 ['t'] = Decoder.parse_true,
501 ['f'] = Decoder.parse_false,
502 ['n'] = Decoder.parse_null,
503 ['['] = Decoder.parse_array,
504 ['{'] = Decoder.parse_object
508 ActiveDecoder = util.class(Decoder)
510 function ActiveDecoder.__init__(self, source, customnull)
511 Decoder.__init__(self, customnull)
514 getmetatable(self).__call = self.get
518 function ActiveDecoder.get(self)
519 local chunk, src_err, object
520 if not self.chunk then
521 chunk, src_err = self.source()
526 self.chunk, object = self:dispatch(chunk, src_err, true)
531 function ActiveDecoder.fetch(self)
532 local chunk, src_err = self.source()
533 assert(chunk or not src_err, src_err)