mirror of
https://github.com/mlua-rs/mlua
synced 2026-06-08 16:05:43 +00:00
Add String::wrap method to wrap arbitrary AsRef<[u8]>
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user