From 7ce6b97da99aa833cf70add59bae278fa145955b Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Fri, 22 Nov 2024 11:48:20 +0000 Subject: [PATCH] Add `String::wrap` method to wrap arbitrary `AsRef<[u8]>` --- src/string.rs | 22 ++++++++++++++++++++++ tests/string.rs | 15 +++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/string.rs b/src/string.rs index 4424a8f4..f4730a90 100644 --- a/src/string.rs +++ b/src/string.rs @@ -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 Result>(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 IntoLua for WrappedString +where + F: FnOnce(&Lua) -> Result, +{ + fn into_lua(self, lua: &Lua) -> Result { + (self.0)(lua).map(Value::String) + } +} + impl LuaType for String { const TYPE_ID: c_int = ffi::LUA_TSTRING; } diff --git a/tests/string.rs b/tests/string.rs index 5192869d..1f849df9 100644 --- a/tests/string.rs +++ b/tests/string.rs @@ -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::("s")?, "hello, world"); + + let s2 = String::wrap("hello, world (owned)".to_string()); + lua.globals().set("s2", s2)?; + assert_eq!(lua.globals().get::("s2")?, "hello, world (owned)"); + + Ok(()) +}