Add Lua::create_ser_any_userdata() function

This commit is contained in:
Alex Orlenko
2024-04-05 12:03:40 +01:00
parent f67f8646ae
commit 62f0bb97b0
2 changed files with 30 additions and 0 deletions
+15
View File
@@ -1746,6 +1746,21 @@ impl Lua {
unsafe { self.make_any_userdata(UserDataCell::new(data)) }
}
/// Creates a Lua userdata object from a custom serializable Rust type.
///
/// See [`Lua::create_any_userdata()`] for more details.
///
/// Requires `feature = "serialize"`
#[cfg(feature = "serialize")]
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
#[inline]
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
where
T: Serialize + MaybeSend + 'static,
{
unsafe { self.make_any_userdata(UserDataCell::new_ser(data)) }
}
/// Registers a custom Rust type in Lua to use in userdata objects.
///
/// This methods provides a way to add fields or methods to userdata objects of a type `T`.
+15
View File
@@ -115,6 +115,21 @@ fn test_serialize_in_scope() -> LuaResult<()> {
Ok(())
}
#[test]
fn test_serialize_any_userdata() -> Result<(), Box<dyn StdError>> {
let lua = Lua::new();
let json_val = serde_json::json!({
"a": 1,
"b": "test",
});
let json_ud = lua.create_ser_any_userdata(json_val)?;
let json_str = serde_json::to_string_pretty(&json_ud)?;
assert_eq!(json_str, "{\n \"a\": 1,\n \"b\": \"test\"\n}");
Ok(())
}
#[test]
fn test_serialize_failure() -> Result<(), Box<dyn StdError>> {
#[derive(Serialize)]