Skip to content

Commit 9045419

Browse files
committed
Strings optimizations: get access to bytes directly from ref thread.
1 parent fcd162f commit 9045419

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/string.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ use {
1313
use crate::error::{Error, Result};
1414
use crate::ffi;
1515
use crate::types::LuaRef;
16-
use crate::util::{assert_stack, StackGuard};
1716

1817
/// Handle to an internal Lua string.
1918
///
@@ -40,6 +39,7 @@ impl<'lua> String<'lua> {
4039
/// # Ok(())
4140
/// # }
4241
/// ```
42+
#[inline]
4343
pub fn to_str(&self) -> Result<&str> {
4444
str::from_utf8(self.as_bytes()).map_err(|e| Error::FromLuaConversionError {
4545
from: "string",
@@ -66,6 +66,7 @@ impl<'lua> String<'lua> {
6666
/// # Ok(())
6767
/// # }
6868
/// ```
69+
#[inline]
6970
pub fn to_string_lossy(&self) -> Cow<'_, str> {
7071
StdString::from_utf8_lossy(self.as_bytes())
7172
}
@@ -87,28 +88,25 @@ impl<'lua> String<'lua> {
8788
/// # Ok(())
8889
/// # }
8990
/// ```
91+
#[inline]
9092
pub fn as_bytes(&self) -> &[u8] {
9193
let nulled = self.as_bytes_with_nul();
9294
&nulled[..nulled.len() - 1]
9395
}
9496

9597
/// Get the bytes that make up this string, including the trailing nul byte.
9698
pub fn as_bytes_with_nul(&self) -> &[u8] {
97-
let lua = self.0.lua;
99+
let ref_thread = self.0.lua.ref_thread();
98100
unsafe {
99-
let _sg = StackGuard::new(lua.state);
100-
assert_stack(lua.state, 1);
101-
102-
lua.push_ref(&self.0);
103101
mlua_debug_assert!(
104-
ffi::lua_type(lua.state, -1) == ffi::LUA_TSTRING,
102+
ffi::lua_type(ref_thread, self.0.index) == ffi::LUA_TSTRING,
105103
"string ref is not string type"
106104
);
107105

108106
let mut size = 0;
109107
// This will not trigger a 'm' error, because the reference is guaranteed to be of
110108
// string type
111-
let data = ffi::lua_tolstring(lua.state, -1, &mut size);
109+
let data = ffi::lua_tolstring(ref_thread, self.0.index, &mut size);
112110

113111
slice::from_raw_parts(data as *const u8, size + 1)
114112
}
@@ -121,8 +119,8 @@ impl<'lua> String<'lua> {
121119
/// Typically this function is used only for hashing and debug information.
122120
#[inline]
123121
pub fn to_pointer(&self) -> *const c_void {
124-
let lua = self.0.lua;
125-
unsafe { ffi::lua_topointer(lua.ref_thread(), self.0.index) }
122+
let ref_thread = self.0.lua.ref_thread();
123+
unsafe { ffi::lua_topointer(ref_thread, self.0.index) }
126124
}
127125
}
128126

0 commit comments

Comments
 (0)