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
185 ['nil'] = Encoder.parse_nil,
186 ['table'] = Encoder.parse_iter,
187 ['number'] = Encoder.parse_number,
188 ['string'] = Encoder.parse_string,
189 ['boolean'] = Encoder.parse_bool,
190 ['function'] = Encoder.parse_iter
194 Decoder = util.class()
196 function Decoder.__init__(self, customnull)
197 self.cnull = customnull
198 getmetatable(self).__call = Decoder.sink
201 function Decoder.sink(self)
202 local sink = coroutine.create(self.dispatch)
204 return coroutine.resume(sink, self, ...)
209 function Decoder.get(self)
213 function Decoder.dispatch(self, chunk, src_err, strict)
214 local robject, object
218 while chunk and #chunk < 1 do
222 assert(not strict or chunk, "Unexpected EOS")
223 if not chunk then break end
225 local char = chunk:sub(1, 1)
226 local parser = self.parsers[char]
227 or (char:match("%s") and self.parse_space)
228 or (char:match("[0-9-]") and self.parse_number)
229 or error("Unexpected char '%s'" % char)
231 chunk, robject = parser(self, chunk)
233 if parser ~= self.parse_space then
234 assert(not oset, "Scope violation: Too many objects")
244 assert(not src_err, src_err)
245 assert(oset, "Unexpected EOS")
251 function Decoder.fetch(self)
252 local tself, chunk, src_err = coroutine.yield()
253 assert(chunk or not src_err, src_err)
258 function Decoder.fetch_atleast(self, chunk, bytes)
259 while #chunk < bytes do
260 local nchunk = self:fetch()
261 assert(nchunk, "Unexpected EOS")
262 chunk = chunk .. nchunk
269 function Decoder.fetch_until(self, chunk, pattern)
270 local start = chunk:find(pattern)
273 local nchunk = self:fetch()
274 assert(nchunk, "Unexpected EOS")
275 chunk = chunk .. nchunk
276 start = chunk:find(pattern)
283 function Decoder.parse_space(self, chunk)
284 local start = chunk:find("[^%s]")
291 start = chunk:find("[^%s]")
294 return chunk:sub(start)
298 function Decoder.parse_literal(self, chunk, literal, value)
299 chunk = self:fetch_atleast(chunk, #literal)
300 assert(chunk:sub(1, #literal) == literal, "Invalid character sequence")
301 return chunk:sub(#literal + 1), value
305 function Decoder.parse_null(self, chunk)
306 return self:parse_literal(chunk, "null", self.cnull and null)
310 function Decoder.parse_true(self, chunk)
311 return self:parse_literal(chunk, "true", true)
315 function Decoder.parse_false(self, chunk)
316 return self:parse_literal(chunk, "false", false)
320 function Decoder.parse_number(self, chunk)
321 local chunk, start = self:fetch_until(chunk, "[^0-9eE.+-]")
322 local number = tonumber(chunk:sub(1, start - 1))
323 assert(number, "Invalid number specification")
324 return chunk:sub(start), number
328 function Decoder.parse_string(self, chunk)
331 assert(chunk:sub(1, 1) == '"', 'Expected "')
335 local spos = chunk:find('[\\"]')
337 str = str .. chunk:sub(1, spos - 1)
339 local char = chunk:sub(spos, spos)
340 if char == '"' then -- String end
341 chunk = chunk:sub(spos + 1)
343 elseif char == "\\" then -- Escape sequence
344 chunk, object = self:parse_escape(chunk:sub(spos))
350 assert(chunk, "Unexpected EOS while parsing a string")
358 function Decoder.utf8_encode(self, s1, s2)
359 local n = s1 * 256 + s2
361 if n >= 0 and n <= 0x7F then
363 elseif n >= 0 and n <= 0x7FF then
365 bor(band(rshift(n, 6), 0x1F), 0xC0),
366 bor(band(n, 0x3F), 0x80)
368 elseif n >= 0 and n <= 0xFFFF then
370 bor(band(rshift(n, 12), 0x0F), 0xE0),
371 bor(band(rshift(n, 6), 0x3F), 0x80),
372 bor(band(n, 0x3F), 0x80)
374 elseif n >= 0 and n <= 0x10FFFF then
376 bor(band(rshift(n, 18), 0x07), 0xF0),
377 bor(band(rshift(n, 12), 0x3F), 0x80),
378 bor(band(rshift(n, 6), 0x3F), 0x80),
379 bor(band(n, 0x3F), 0x80)
387 function Decoder.parse_escape(self, chunk)
389 chunk = self:fetch_atleast(chunk:sub(2), 1)
390 local char = chunk:sub(1, 1)
395 elseif char == "\\" then
397 elseif char == "u" then
398 chunk = self:fetch_atleast(chunk, 4)
399 local s1, s2 = chunk:sub(1, 2), chunk:sub(3, 4)
400 s1, s2 = tonumber(s1, 16), tonumber(s2, 16)
401 assert(s1 and s2, "Invalid Unicode character")
403 return chunk:sub(5), self:utf8_encode(s1, s2)
404 elseif char == "/" then
406 elseif char == "b" then
408 elseif char == "f" then
410 elseif char == "n" then
412 elseif char == "r" then
414 elseif char == "t" then
417 error("Unexpected escaping sequence '\\%s'" % char)
422 function Decoder.parse_array(self, chunk)
427 local chunk, object = self:parse_delimiter(chunk, "%]")
434 chunk, object = self:dispatch(chunk, nil, true)
435 table.insert(array, nextp, object)
438 chunk, object = self:parse_delimiter(chunk, ",%]")
439 assert(object, "Delimiter expected")
446 function Decoder.parse_object(self, chunk)
451 local chunk, object = self:parse_delimiter(chunk, "}")
458 chunk = self:parse_space(chunk)
459 assert(chunk, "Unexpected EOS")
461 chunk, name = self:parse_string(chunk)
463 chunk, object = self:parse_delimiter(chunk, ":")
464 assert(object, "Separator expected")
466 chunk, object = self:dispatch(chunk, nil, true)
469 chunk, object = self:parse_delimiter(chunk, ",}")
470 assert(object, "Delimiter expected")
477 function Decoder.parse_delimiter(self, chunk, delimiter)
479 chunk = self:fetch_atleast(chunk, 1)
480 local char = chunk:sub(1, 1)
481 if char:match("%s") then
482 chunk = self:parse_space(chunk)
483 assert(chunk, "Unexpected EOS")
484 elseif char:match("[%s]" % delimiter) then
485 return chunk:sub(2), char
494 ['"'] = Decoder.parse_string,
495 ['t'] = Decoder.parse_true,
496 ['f'] = Decoder.parse_false,
497 ['n'] = Decoder.parse_null,
498 ['['] = Decoder.parse_array,
499 ['{'] = Decoder.parse_object
503 ActiveDecoder = util.class(Decoder)
505 function ActiveDecoder.__init__(self, source, customnull)
506 Decoder.__init__(self, customnull)
509 getmetatable(self).__call = self.get
513 function ActiveDecoder.get(self)
514 local chunk, src_err, object
515 if not self.chunk then
516 chunk, src_err = self.source()
521 self.chunk, object = self:dispatch(chunk, src_err, true)
526 function ActiveDecoder.fetch(self)
527 local chunk, src_err = self.source()
528 assert(chunk or not src_err, src_err)