Skip to main content

rsjson_lua/
lib.rs

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