Allow arbitrary [u8] Lua strings

This commit is contained in:
kyren 2018-09-30 15:42:04 -04:00
parent 8810c36979
commit 167184ae76
3 changed files with 16 additions and 3 deletions

View File

@ -140,8 +140,10 @@ impl Lua {
.call(()) .call(())
} }
/// Pass a `&str` slice to Lua, creating and returning an interned Lua string. /// Create and return an interned Lua string. Lua strings can be arbitrary [u8] data including
pub fn create_string(&self, s: &str) -> Result<String> { /// embedded nulls, so in addition to `&str` and `&String`, you can also pass plain `&[u8]`
/// here.
pub fn create_string<S: ?Sized + AsRef<[u8]>>(&self, s: &S) -> Result<String> {
unsafe { unsafe {
let _sg = StackGuard::new(self.state); let _sg = StackGuard::new(self.state);
assert_stack(self.state, 4); assert_stack(self.state, 4);

View File

@ -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 // 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<S: ?Sized + AsRef<[u8]>>(
state: *mut ffi::lua_State,
s: &S,
) -> Result<()> {
protect_lua_closure(state, 0, 1, |state| { 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()); ffi::lua_pushlstring(state, s.as_ptr() as *const c_char, s.len());
}) })
} }

View File

@ -60,3 +60,10 @@ fn string_views() {
assert_eq!(empty.as_bytes_with_nul(), &[0]); assert_eq!(empty.as_bytes_with_nul(), &[0]);
assert_eq!(empty.as_bytes(), &[]); 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]);
}