Allow arbitrary [u8] Lua strings
This commit is contained in:
parent
8810c36979
commit
167184ae76
|
@ -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<String> {
|
||||
/// 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<S: ?Sized + AsRef<[u8]>>(&self, s: &S) -> Result<String> {
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(self.state);
|
||||
assert_stack(self.state, 4);
|
||||
|
|
|
@ -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<S: ?Sized + AsRef<[u8]>>(
|
||||
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());
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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]);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue