Skip to content

Commit 7ce6b97

Browse files
committed
Add String::wrap method to wrap arbitrary AsRef<[u8]>
1 parent 4891a6a commit 7ce6b97

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/string.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ use std::{cmp, fmt, slice, str};
77

88
use crate::error::{Error, Result};
99
use crate::state::Lua;
10+
use crate::traits::IntoLua;
1011
use crate::types::{LuaType, ValueRef};
12+
use crate::value::Value;
1113

1214
#[cfg(feature = "serialize")]
1315
use {
@@ -366,6 +368,26 @@ impl<'a> IntoIterator for BorrowedBytes<'a> {
366368
}
367369
}
368370

371+
pub(crate) struct WrappedString<F: FnOnce(&Lua) -> Result<String>>(F);
372+
373+
impl String {
374+
/// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
375+
///
376+
/// This function uses [`Lua::create_string`] under the hood.
377+
pub fn wrap(data: impl AsRef<[u8]>) -> impl IntoLua {
378+
WrappedString(move |lua| lua.create_string(data))
379+
}
380+
}
381+
382+
impl<F> IntoLua for WrappedString<F>
383+
where
384+
F: FnOnce(&Lua) -> Result<String>,
385+
{
386+
fn into_lua(self, lua: &Lua) -> Result<Value> {
387+
(self.0)(lua).map(Value::String)
388+
}
389+
}
390+
369391
impl LuaType for String {
370392
const TYPE_ID: c_int = ffi::LUA_TSTRING;
371393
}

tests/string.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,3 +128,18 @@ fn test_string_display() -> Result<()> {
128128

129129
Ok(())
130130
}
131+
132+
#[test]
133+
fn test_string_wrap() -> Result<()> {
134+
let lua = Lua::new();
135+
136+
let s = String::wrap("hello, world");
137+
lua.globals().set("s", s)?;
138+
assert_eq!(lua.globals().get::<String>("s")?, "hello, world");
139+
140+
let s2 = String::wrap("hello, world (owned)".to_string());
141+
lua.globals().set("s2", s2)?;
142+
assert_eq!(lua.globals().get::<String>("s2")?, "hello, world (owned)");
143+
144+
Ok(())
145+
}

0 commit comments

Comments
 (0)