Skip to main content

rsjson_lua/
lib.rs

1// SPDX-License-Identifier: MIT
2
3mod config;
4mod decode;
5mod encode;
6
7use mlua::prelude::{Lua, LuaError, LuaResult, LuaSerdeExt, LuaString, LuaTable, LuaValue};
8
9use crate::config::{DecodeConfig, EncodeConfig};
10
11#[cfg_attr(feature = "module", mlua::lua_module(name = "serde_json"))]
12pub fn rsjson_lua(lua: &Lua) -> LuaResult<LuaTable> {
13    let table = lua.create_table()?;
14
15    table.set("null", lua.null())?;
16
17    table.set("EncodeConfig", lua.create_proxy::<EncodeConfig>()?)?;
18
19    table.set("DecodeConfig", lua.create_proxy::<DecodeConfig>()?)?;
20
21    table.set(
22        "encode",
23        lua.create_function(|lua, (value, config): (LuaValue, Option<EncodeConfig>)| {
24            encode::encode(lua, &value, config).map_err(LuaError::external)
25        })?,
26    )?;
27
28    table.set(
29        "decode",
30        lua.create_function(|lua, (json, config): (LuaString, Option<DecodeConfig>)| {
31            decode::decode(lua, &json.as_bytes(), config).map_err(LuaError::external)
32        })?,
33    )?;
34
35    Ok(table)
36}
37
38#[cfg(test)]
39mod test {
40    use super::*;
41
42    fn setup_lua() -> Lua {
43        let lua = Lua::new();
44
45        let table = rsjson_lua(&lua).unwrap();
46        lua.globals().set("rsjson", table).unwrap();
47
48        lua
49    }
50
51    #[test]
52    fn it_rsjson_table() {
53        let lua = setup_lua();
54
55        let table: LuaTable = lua.globals().get("rsjson").unwrap();
56
57        let encode_func: LuaValue = table.get("encode").unwrap();
58        let decode_func: LuaValue = table.get("decode").unwrap();
59        let null_val: LuaValue = table.get("null").unwrap();
60        let enc_conf: LuaValue = table.get("EncodeConfig").unwrap();
61        let dec_conf: LuaValue = table.get("DecodeConfig").unwrap();
62
63        assert!(encode_func.is_function());
64        assert!(decode_func.is_function());
65        assert!(null_val.is_null());
66        assert!(enc_conf.is_userdata());
67        assert!(dec_conf.is_userdata());
68    }
69}