From 167184ae76b37b53114f2818bbc48c83936a08f4 Mon Sep 17 00:00:00 2001 From: kyren Date: Sun, 30 Sep 2018 15:42:04 -0400 Subject: [PATCH] Allow arbitrary [u8] Lua strings --- src/lua.rs | 6 ++++-- src/util.rs | 6 +++++- tests/string.rs | 7 +++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/lua.rs b/src/lua.rs index c13eb2d..846ce3a 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -140,8 +140,10 @@ impl Lua { .call(()) } - /// Pass a `&str` slice to Lua, creating and returning an interned Lua string. - pub fn create_string(&self, s: &str) -> Result { + /// Create and return an interned Lua string. Lua strings can be arbitrary [u8] data including + /// embedded nulls, so in addition to `&str` and `&String`, you can also pass plain `&[u8]` + /// here. + pub fn create_string>(&self, s: &S) -> Result { unsafe { let _sg = StackGuard::new(self.state); assert_stack(self.state, 4); diff --git a/src/util.rs b/src/util.rs index 5723f33..544f9d7 100644 --- a/src/util.rs +++ b/src/util.rs @@ -220,8 +220,12 @@ pub unsafe fn pop_error(state: *mut ffi::lua_State, err_code: c_int) -> Error { } // Internally uses 4 stack spaces, does not call checkstack -pub unsafe fn push_string(state: *mut ffi::lua_State, s: &str) -> Result<()> { +pub unsafe fn push_string>( + state: *mut ffi::lua_State, + s: &S, +) -> Result<()> { protect_lua_closure(state, 0, 1, |state| { + let s = s.as_ref(); ffi::lua_pushlstring(state, s.as_ptr() as *const c_char, s.len()); }) } diff --git a/tests/string.rs b/tests/string.rs index f11f2cb..29c7593 100644 --- a/tests/string.rs +++ b/tests/string.rs @@ -60,3 +60,10 @@ fn string_views() { assert_eq!(empty.as_bytes_with_nul(), &[0]); assert_eq!(empty.as_bytes(), &[]); } + +#[test] +fn raw_string() { + let lua = Lua::new(); + let rs = lua.create_string(&[0, 1, 2, 3, 0, 1, 2, 3]).unwrap(); + assert_eq!(rs.as_bytes(), &[0, 1, 2, 3, 0, 1, 2, 3]); +}