Add String::wrap method to wrap arbitrary AsRef<[u8]>

This commit is contained in:
Alex Orlenko
2024-11-22 11:48:20 +00:00
parent 4891a6ac10
commit 7ce6b97da9
2 changed files with 37 additions and 0 deletions
+22
View File
@@ -7,7 +7,9 @@ use std::{cmp, fmt, slice, str};
use crate::error::{Error, Result};
use crate::state::Lua;
use crate::traits::IntoLua;
use crate::types::{LuaType, ValueRef};
use crate::value::Value;
#[cfg(feature = "serialize")]
use {
@@ -366,6 +368,26 @@ impl<'a> IntoIterator for BorrowedBytes<'a> {
}
}
pub(crate) struct WrappedString<F: FnOnce(&Lua) -> Result<String>>(F);
impl String {
/// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
///
/// This function uses [`Lua::create_string`] under the hood.
pub fn wrap(data: impl AsRef<[u8]>) -> impl IntoLua {
WrappedString(move |lua| lua.create_string(data))
}
}
impl<F> IntoLua for WrappedString<F>
where
F: FnOnce(&Lua) -> Result<String>,
{
fn into_lua(self, lua: &Lua) -> Result<Value> {
(self.0)(lua).map(Value::String)
}
}
impl LuaType for String {
const TYPE_ID: c_int = ffi::LUA_TSTRING;
}
+15
View File
@@ -128,3 +128,18 @@ fn test_string_display() -> Result<()> {
Ok(())
}
#[test]
fn test_string_wrap() -> Result<()> {
let lua = Lua::new();
let s = String::wrap("hello, world");
lua.globals().set("s", s)?;
assert_eq!(lua.globals().get::<String>("s")?, "hello, world");
let s2 = String::wrap("hello, world (owned)".to_string());
lua.globals().set("s2", s2)?;
assert_eq!(lua.globals().get::<String>("s2")?, "hello, world (owned)");
Ok(())
}