mlua/src/string.rs
kyren 601e9f4cac A lot of performance changes.
Okay, so this is kind of a mega-commit of a lot of performance related changes
to rlua, some of which are pretty complicated.

There are some small improvements here and there, but most of the benefits of
this change are from a few big changes.  The simplest big change is that there
is now `protect_lua` as well as `protect_lua_call`, which allows skipping a
lightuserdata parameter and some stack manipulation in some cases.  Second
simplest is the change to use Vec instead of VecDeque for MultiValue, and to
have MultiValue be used as a sort of "backwards-only" Vec so that ToLuaMulti /
FromLuaMulti still work correctly.

The most complex change, though, is a change to the way LuaRef works, so that
LuaRef can optionally point into the Lua stack instead of only registry values.
At state creation a set number of stack slots is reserved for the first N LuaRef
types (currently 16), and space for these are also allocated separately
allocated at callback time.  There is a huge breaking change here, which is that
now any LuaRef types MUST only be used with the Lua on which they were created,
and CANNOT be used with any other Lua callback instance.  This mostly will
affect people using LuaRef types from inside a scope callback, but hopefully in
those cases `Function::bind` will be a suitable replacement.  On the plus side,
the rules for LuaRef types are easier to state now.

There is probably more easy-ish perf on the table here, but here's the
preliminary results, based on my very limited benchmarks:

create table            time:   [314.13 ns 315.71 ns 317.44 ns]
                        change: [-36.154% -35.670% -35.205%] (p = 0.00 < 0.05)
create array 10         time:   [2.9731 us 2.9816 us 2.9901 us]
                        change: [-16.996% -16.600% -16.196%] (p = 0.00 < 0.05)
                        Performance has improved.
create string table 10  time:   [5.6904 us 5.7164 us 5.7411 us]
                        change: [-53.536% -53.309% -53.079%] (p = 0.00 < 0.05)
                        Performance has improved.
call add function 3 10  time:   [5.1134 us 5.1222 us 5.1320 us]
                        change: [-4.1095% -3.6910% -3.1781%] (p = 0.00 < 0.05)
                        Performance has improved.
call callback add 2 10  time:   [5.4408 us 5.4480 us 5.4560 us]
                        change: [-6.4203% -5.7780% -5.0013%] (p = 0.00 < 0.05)
                        Performance has improved.
call callback append 10 time:   [9.8243 us 9.8410 us 9.8586 us]
                        change: [-26.937% -26.702% -26.469%] (p = 0.00 < 0.05)
                        Performance has improved.
create registry 10      time:   [3.7005 us 3.7089 us 3.7174 us]
                        change: [-8.4965% -8.1042% -7.6926%] (p = 0.00 < 0.05)
                        Performance has improved.

I think that a lot of these benchmarks are too "easy", and most API usage is
going to be more like the 'create string table 10' benchmark, where there are a
lot of handles and tables and strings, so I think that 25%-50% improvement is a
good guess for most use cases.
2018-03-11 23:20:10 -04:00

113 lines
3.3 KiB
Rust

use std::{slice, str};
use ffi;
use error::{Error, Result};
use util::{check_stack, stack_guard};
use types::LuaRef;
/// Handle to an internal Lua string.
///
/// Unlike Rust strings, Lua strings may not be valid UTF-8.
#[derive(Clone, Debug)]
pub struct String<'lua>(pub(crate) LuaRef<'lua>);
impl<'lua> String<'lua> {
/// Get a `&str` slice if the Lua string is valid UTF-8.
///
/// # Examples
///
/// ```
/// # extern crate rlua;
/// # use rlua::{Lua, String, Result};
/// # fn try_main() -> Result<()> {
/// let lua = Lua::new();
/// let globals = lua.globals();
///
/// let version: String = globals.get("_VERSION")?;
/// assert!(version.to_str().unwrap().contains("Lua"));
///
/// let non_utf8: String = lua.eval(r#" "test\xff" "#, None)?;
/// assert!(non_utf8.to_str().is_err());
/// # Ok(())
/// # }
/// # fn main() {
/// # try_main().unwrap();
/// # }
/// ```
pub fn to_str(&self) -> Result<&str> {
str::from_utf8(self.as_bytes()).map_err(|e| Error::FromLuaConversionError {
from: "string",
to: "&str",
message: Some(e.to_string()),
})
}
/// Get the bytes that make up this string.
///
/// The returned slice will not contain the terminating nul byte, but will contain any nul
/// bytes embedded into the Lua string.
///
/// # Examples
///
/// ```
/// # extern crate rlua;
/// # use rlua::{Lua, String};
/// # fn main() {
/// let lua = Lua::new();
///
/// let non_utf8: String = lua.eval(r#" "test\xff" "#, None).unwrap();
/// assert!(non_utf8.to_str().is_err()); // oh no :(
/// assert_eq!(non_utf8.as_bytes(), &b"test\xff"[..]);
/// # }
/// ```
pub fn as_bytes(&self) -> &[u8] {
let nulled = self.as_bytes_with_nul();
&nulled[..nulled.len() - 1]
}
/// Get the bytes that make up this string, including the trailing nul byte.
pub fn as_bytes_with_nul(&self) -> &[u8] {
let lua = self.0.lua;
unsafe {
stack_guard(lua.state, || {
check_stack(lua.state, 1);
lua.push_ref(&self.0);
rlua_assert!(
ffi::lua_type(lua.state, -1) == ffi::LUA_TSTRING,
"string ref is not string type"
);
let mut size = 0;
// This will not trigger a 'm' error, because the reference is guaranteed to be of
// string type
let data = ffi::lua_tolstring(lua.state, -1, &mut size);
slice::from_raw_parts(data as *const u8, size + 1)
})
}
}
}
impl<'lua> AsRef<[u8]> for String<'lua> {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
// Lua strings are basically &[u8] slices, so implement PartialEq for anything resembling that.
//
// This makes our `String` comparable with `Vec<u8>`, `[u8]`, `&str`, `String` and `rlua::String`
// itself.
//
// The only downside is that this disallows a comparison with `Cow<str>`, as that only implements
// `AsRef<str>`, which collides with this impl. Requiring `AsRef<str>` would fix that, but limit us
// in other ways.
impl<'lua, T> PartialEq<T> for String<'lua>
where
T: AsRef<[u8]>,
{
fn eq(&self, other: &T) -> bool {
self.as_bytes() == other.as_ref()
}
}