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;
}