Skip to content

Commit

Permalink
Add String::wrap method to wrap arbitrary AsRef<[u8]>
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Nov 22, 2024
1 parent 4891a6a commit 7ce6b97
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
Expand Down
15 changes: 15 additions & 0 deletions tests/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

0 comments on commit 7ce6b97

Please sign in to comment.