Implement ToLua/FromLua for Box<str> and Box<[T]>

This commit is contained in:
Alex Orlenko 2021-05-03 01:15:36 +01:00
parent 1bb3c5c19f
commit 4af7bcf0d9
2 changed files with 66 additions and 0 deletions

View file

@ -229,6 +229,28 @@ impl<'lua> ToLua<'lua> for Cow<'_, str> {
}
}
impl<'lua> ToLua<'lua> for Box<str> {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::String(lua.create_string(&*self)?))
}
}
impl<'lua> FromLua<'lua> for Box<str> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
let ty = value.type_name();
Ok(lua
.coerce_string(value)?
.ok_or_else(|| Error::FromLuaConversionError {
from: ty,
to: "Box<str>",
message: Some("expected string or number".to_string()),
})?
.to_str()?
.to_owned()
.into_boxed_str())
}
}
impl<'lua> ToLua<'lua> for CString {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::String(lua.create_string(self.as_bytes())?))
@ -436,6 +458,26 @@ lua_convert_array! {
30 31 32
}
impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Box<[T]> {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Table(lua.create_sequence_from(self.into_vec())?))
}
}
impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Box<[T]> {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
if let Value::Table(table) = value {
table.sequence_values().collect()
} else {
Err(Error::FromLuaConversionError {
from: value.type_name(),
to: "Box<[T]>",
message: Some("expected table".to_string()),
})
}
}
}
impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Vec<T> {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Table(lua.create_sequence_from(self)?))

View file

@ -88,3 +88,27 @@ fn test_conv_cow() -> Result<()> {
Ok(())
}
#[test]
fn test_conv_boxed_str() -> Result<()> {
let lua = Lua::new();
let s = String::from("hello").into_boxed_str();
lua.globals().set("s", s.clone())?;
let s2: Box<str> = lua.globals().get("s")?;
assert!(s == s2);
Ok(())
}
#[test]
fn test_conv_boxed_slice() -> Result<()> {
let lua = Lua::new();
let v = vec![1, 2, 3].into_boxed_slice();
lua.globals().set("v", v.clone())?;
let v2: Box<[i32]> = lua.globals().get("v")?;
assert!(v == v2);
Ok(())
}