1mod 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("array_mt", lua.array_metatable())?;
15
16 table.set("null", lua.null())?;
17
18 table.set("EncodeConfig", lua.create_proxy::<EncodeConfig>()?)?;
19
20 table.set("DecodeConfig", lua.create_proxy::<DecodeConfig>()?)?;
21
22 table.set(
23 "encode",
24 lua.create_function(
25 |lua, (value, config): (mlua::Value, Option<EncodeConfig>)| {
26 encode::encode(lua, &value, config)
27 },
28 )?,
29 )?;
30
31 table.set(
32 "decode",
33 lua.create_function(
34 |lua, (json, config): (mlua::BorrowedBytes, Option<DecodeConfig>)| {
35 decode::decode(lua, &json, config)
36 },
37 )?,
38 )?;
39
40 Ok(table)
41}
42
43#[cfg(test)]
44mod test {
45 use mlua::ObjectLike;
46
47 use super::*;
48
49 fn setup_lua() -> mlua::Lua {
50 let lua = mlua::Lua::new();
51
52 let table = rsjson_lua(&lua).unwrap();
53 lua.globals().set("rsjson", table).unwrap();
54
55 lua
56 }
57
58 #[test]
59 fn it_rsjson_table() {
60 let lua = setup_lua();
61
62 let table: mlua::Table = lua.globals().get("rsjson").unwrap();
63
64 let encode_func: mlua::Value = table.get("encode").unwrap();
65 let decode_func: mlua::Value = table.get("decode").unwrap();
66 let null_val: mlua::Value = table.get("null").unwrap();
67 let array_mt: mlua::Value = table.get("array_mt").unwrap();
68 let enc_conf: mlua::Value = table.get("EncodeConfig").unwrap();
69 let dec_conf: mlua::Value = table.get("DecodeConfig").unwrap();
70
71 assert!(encode_func.is_function());
72 assert!(decode_func.is_function());
73 assert!(null_val.is_null());
74 assert!(array_mt.is_table());
75 assert!(array_mt.equals(&lua.array_metatable().to_value()).unwrap());
76 assert!(enc_conf.is_userdata());
77 assert!(dec_conf.is_userdata());
78 }
79}