]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
export a JSON decode function to lua
authorAnbang Wen <xofyarg@gmail.com>
Wed, 18 Apr 2018 20:37:42 +0000 (13:37 -0700)
committerPetr Špaček <petr.spacek@nic.cz>
Fri, 20 Apr 2018 10:53:07 +0000 (12:53 +0200)
Since there is already a bundled JSON library, expose it to lua for
modules to use.

daemon/engine.c
tests/config/basic.test.lua

index 91390c452322e7713d69bc7bbb0c301ccf9d2789..7dc89d431a307f9c576e77d05b9e229fb50fedea 100644 (file)
@@ -472,6 +472,26 @@ static int l_tojson(lua_State *L)
        return 1;
 }
 
+static int l_fromjson(lua_State *L)
+{
+       if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
+               lua_pushliteral(L, "a JSON string is required");
+               lua_error(L);
+       }
+
+       const char *json_str = lua_tostring(L, 1);
+       JsonNode *root_node = json_decode(json_str);
+
+       if (!root_node) {
+               lua_pushliteral(L, "invalid JSON string");
+               lua_error(L);
+       }
+       l_unpack_json(L, root_node);
+       json_delete(root_node);
+
+       return 1;
+}
+
 /** @internal Throw Lua error if expr is false */
 #define expr_checked(expr) \
        if (!(expr)) { lua_pushboolean(L, false); lua_rawseti(L, -2, lua_rawlen(L, -2) + 1); continue; }
@@ -642,6 +662,8 @@ static int init_state(struct engine *engine)
        lua_setglobal(engine->L, "libzscanner_SONAME");
        lua_pushcfunction(engine->L, l_tojson);
        lua_setglobal(engine->L, "tojson");
+       lua_pushcfunction(engine->L, l_fromjson);
+       lua_setglobal(engine->L, "fromjson");
        lua_pushcfunction(engine->L, l_map);
        lua_setglobal(engine->L, "map");
        lua_pushlightuserdata(engine->L, engine);
index b4d756285f942c75ba6c807133be64a8dd749afa..1d0ea6b42d877e1b2a23c3afce4e4ce011f91b8d 100644 (file)
@@ -122,9 +122,32 @@ local function test_packet_functions()
        is(#pkt:towire(), 12, 'recycle() clears the packet wireformat')
 end
 
+-- test JSON encode/decode functions
+local function test_json_functions()
+       for msg, obj in pairs({
+                       ['number'] = 0,
+                       ['string'] = 'ok',
+                       ['list'] = {1, 2, 3},
+                       ['map'] = {foo='bar'},
+                       ['nest structure'] = {foo='bar', baz={1,2,3}},
+       }) do
+               same(fromjson(tojson(obj)), obj, 'json test: ' .. msg)
+       end
+
+       for _, str in ipairs({
+                       '{', '}',
+                       '[', ']',
+                       'x,',
+                       '[1,2,3,]',
+       }) do
+               boom(fromjson, {'{'}, 'json test: invalid \'' .. str .. '\'')
+       end
+end
+
 return {
        test_constants,
        test_globals,
        test_rrset_functions,
        test_packet_functions,
+       test_json_functions,
 }