Rename string::String to LuaString

This commit is contained in:
Alex Orlenko
2026-01-29 18:45:41 +00:00
parent c1ffd4e790
commit 2ace892613
26 changed files with 246 additions and 264 deletions
+27 -28
View File
@@ -4,7 +4,6 @@ use std::ffi::CString;
use std::io::Result as IoResult;
use std::panic::Location;
use std::path::{Path, PathBuf};
use std::string::String as StdString;
use crate::error::{Error, Result};
use crate::function::Function;
@@ -20,7 +19,7 @@ pub trait AsChunk {
/// Returns optional chunk name
///
/// See [`Chunk::set_name`] for possible name prefixes.
fn name(&self) -> Option<StdString> {
fn name(&self) -> Option<String> {
None
}
@@ -52,13 +51,13 @@ impl AsChunk for &str {
}
}
impl AsChunk for StdString {
impl AsChunk for String {
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>> {
Ok(Cow::Owned(self.clone().into_bytes()))
}
}
impl AsChunk for &StdString {
impl AsChunk for &String {
fn source<'a>(&self) -> IoResult<Cow<'a, [u8]>>
where
Self: 'a,
@@ -92,7 +91,7 @@ impl AsChunk for &Vec<u8> {
}
impl AsChunk for &Path {
fn name(&self) -> Option<StdString> {
fn name(&self) -> Option<String> {
Some(format!("@{}", self.display()))
}
@@ -102,7 +101,7 @@ impl AsChunk for &Path {
}
impl AsChunk for PathBuf {
fn name(&self) -> Option<StdString> {
fn name(&self) -> Option<String> {
Some(format!("@{}", self.display()))
}
@@ -112,7 +111,7 @@ impl AsChunk for PathBuf {
}
impl<C: AsChunk + ?Sized> AsChunk for Box<C> {
fn name(&self) -> Option<StdString> {
fn name(&self) -> Option<String> {
(**self).name()
}
@@ -136,7 +135,7 @@ impl<C: AsChunk + ?Sized> AsChunk for Box<C> {
#[must_use = "`Chunk`s do nothing unless one of `exec`, `eval`, `call`, or `into_function` are called on them"]
pub struct Chunk<'a> {
pub(crate) lua: WeakLua,
pub(crate) name: StdString,
pub(crate) name: String,
pub(crate) env: Result<Option<Table>>,
pub(crate) mode: Option<ChunkMode>,
pub(crate) source: IoResult<Cow<'a, [u8]>>,
@@ -160,7 +159,7 @@ pub enum CompileConstant {
Boolean(bool),
Number(crate::Number),
Vector(crate::Vector),
String(StdString),
String(String),
}
#[cfg(any(feature = "luau", doc))]
@@ -192,7 +191,7 @@ impl From<&str> for CompileConstant {
}
#[cfg(any(feature = "luau", doc))]
type LibraryMemberConstantMap = HashMap<(StdString, StdString), CompileConstant>;
type LibraryMemberConstantMap = HashMap<(String, String), CompileConstant>;
/// Luau compiler
#[cfg(any(feature = "luau", doc))]
@@ -203,14 +202,14 @@ pub struct Compiler {
debug_level: u8,
type_info_level: u8,
coverage_level: u8,
vector_lib: Option<StdString>,
vector_ctor: Option<StdString>,
vector_type: Option<StdString>,
mutable_globals: Vec<StdString>,
userdata_types: Vec<StdString>,
libraries_with_known_members: Vec<StdString>,
vector_lib: Option<String>,
vector_ctor: Option<String>,
vector_type: Option<String>,
mutable_globals: Vec<String>,
userdata_types: Vec<String>,
libraries_with_known_members: Vec<String>,
library_constants: Option<LibraryMemberConstantMap>,
disabled_builtins: Vec<StdString>,
disabled_builtins: Vec<String>,
}
#[cfg(any(feature = "luau", doc))]
@@ -294,7 +293,7 @@ impl Compiler {
/// To set the library and method name, use the `lib.ctor` format.
#[doc(hidden)]
#[must_use]
pub fn set_vector_ctor(mut self, ctor: impl Into<StdString>) -> Self {
pub fn set_vector_ctor(mut self, ctor: impl Into<String>) -> Self {
let ctor = ctor.into();
let lib_ctor = ctor.split_once('.');
self.vector_lib = lib_ctor.as_ref().map(|&(lib, _)| lib.to_owned());
@@ -307,7 +306,7 @@ impl Compiler {
/// Sets alternative vector type name for type tables, in addition to default type `vector`.
#[doc(hidden)]
#[must_use]
pub fn set_vector_type(mut self, r#type: impl Into<StdString>) -> Self {
pub fn set_vector_type(mut self, r#type: impl Into<String>) -> Self {
self.vector_type = Some(r#type.into());
self
}
@@ -316,7 +315,7 @@ impl Compiler {
///
/// It disables the import optimization for fields accessed through it.
#[must_use]
pub fn add_mutable_global(mut self, global: impl Into<StdString>) -> Self {
pub fn add_mutable_global(mut self, global: impl Into<String>) -> Self {
self.mutable_globals.push(global.into());
self
}
@@ -325,21 +324,21 @@ impl Compiler {
///
/// It disables the import optimization for fields accessed through these.
#[must_use]
pub fn set_mutable_globals<S: Into<StdString>>(mut self, globals: impl IntoIterator<Item = S>) -> Self {
pub fn set_mutable_globals<S: Into<String>>(mut self, globals: impl IntoIterator<Item = S>) -> Self {
self.mutable_globals = globals.into_iter().map(|s| s.into()).collect();
self
}
/// Adds a userdata type to the list that will be included in the type information.
#[must_use]
pub fn add_userdata_type(mut self, r#type: impl Into<StdString>) -> Self {
pub fn add_userdata_type(mut self, r#type: impl Into<String>) -> Self {
self.userdata_types.push(r#type.into());
self
}
/// Sets a list of userdata types that will be included in the type information.
#[must_use]
pub fn set_userdata_types<S: Into<StdString>>(mut self, types: impl IntoIterator<Item = S>) -> Self {
pub fn set_userdata_types<S: Into<String>>(mut self, types: impl IntoIterator<Item = S>) -> Self {
self.userdata_types = types.into_iter().map(|s| s.into()).collect();
self
}
@@ -373,14 +372,14 @@ impl Compiler {
/// Adds a builtin that should be disabled.
#[must_use]
pub fn add_disabled_builtin(mut self, builtin: impl Into<StdString>) -> Self {
pub fn add_disabled_builtin(mut self, builtin: impl Into<String>) -> Self {
self.disabled_builtins.push(builtin.into());
self
}
/// Sets a list of builtins that should be disabled.
#[must_use]
pub fn set_disabled_builtins<S: Into<StdString>>(
pub fn set_disabled_builtins<S: Into<String>>(
mut self,
builtins: impl IntoIterator<Item = S>,
) -> Self {
@@ -490,7 +489,7 @@ impl Compiler {
if bytecode.first() == Some(&0) {
// The rest of the bytecode is the error message starting with `:`
// See https://github.com/luau-lang/luau/blob/0.640/Compiler/src/Compiler.cpp#L4336
let message = StdString::from_utf8_lossy(&bytecode[2..]).into_owned();
let message = String::from_utf8_lossy(&bytecode[2..]).into_owned();
return Err(Error::SyntaxError {
incomplete_input: message.ends_with("<eof>"),
message,
@@ -513,7 +512,7 @@ impl Chunk<'_> {
/// - `@` - file path (when truncation is needed, the end of the file path is kept, as this is
/// more useful for identifying the file)
/// - `=` - custom chunk name (when truncation is needed, the beginning of the name is kept)
pub fn set_name(mut self, name: impl Into<StdString>) -> Self {
pub fn set_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
@@ -761,7 +760,7 @@ impl Chunk<'_> {
ChunkMode::Text
}
fn convert_name(name: StdString) -> Result<CString> {
fn convert_name(name: String) -> Result<CString> {
CString::new(name).map_err(|err| Error::runtime(format!("invalid name: {err}")))
}
+12 -13
View File
@@ -4,7 +4,6 @@ use std::ffi::{CStr, CString, OsStr, OsString};
use std::hash::{BuildHasher, Hash};
use std::os::raw::c_int;
use std::path::{Path, PathBuf};
use std::string::String as StdString;
use std::{mem, slice, str};
use bstr::{BStr, BString, ByteSlice, ByteVec};
@@ -13,7 +12,7 @@ use num_traits::cast;
use crate::error::{Error, Result};
use crate::function::Function;
use crate::state::{Lua, RawLua};
use crate::string::{BorrowedBytes, BorrowedStr, String};
use crate::string::{BorrowedBytes, BorrowedStr, LuaString};
use crate::table::Table;
use crate::thread::Thread;
use crate::traits::{FromLua, IntoLua, ShortTypeName as _};
@@ -47,14 +46,14 @@ impl FromLua for Value {
}
}
impl IntoLua for String {
impl IntoLua for LuaString {
#[inline]
fn into_lua(self, _: &Lua) -> Result<Value> {
Ok(Value::String(self))
}
}
impl IntoLua for &String {
impl IntoLua for &LuaString {
#[inline]
fn into_lua(self, _: &Lua) -> Result<Value> {
Ok(Value::String(self.clone()))
@@ -67,9 +66,9 @@ impl IntoLua for &String {
}
}
impl FromLua for String {
impl FromLua for LuaString {
#[inline]
fn from_lua(value: Value, lua: &Lua) -> Result<String> {
fn from_lua(value: Value, lua: &Lua) -> Result<LuaString> {
let ty = value.type_name();
lua.coerce_string(value)?
.ok_or_else(|| Error::FromLuaConversionError {
@@ -84,7 +83,7 @@ impl FromLua for String {
let type_id = ffi::lua_type(state, idx);
if type_id == ffi::LUA_TSTRING {
ffi::lua_xpush(state, lua.ref_thread(), idx);
return Ok(String(lua.pop_ref_thread()));
return Ok(LuaString(lua.pop_ref_thread()));
}
// Fallback to default
Self::from_lua(lua.stack_value(idx, Some(type_id)), lua.lua())
@@ -119,7 +118,7 @@ impl IntoLua for &BorrowedStr<'_> {
impl FromLua for BorrowedStr<'_> {
fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
let s = String::from_lua(value, lua)?;
let s = LuaString::from_lua(value, lua)?;
let BorrowedStr { buf, _lua, .. } = BorrowedStr::try_from(&s)?;
let buf = unsafe { mem::transmute::<&str, &'static str>(buf) };
let borrow = Cow::Owned(s);
@@ -127,7 +126,7 @@ impl FromLua for BorrowedStr<'_> {
}
unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
let s = String::from_stack(idx, lua)?;
let s = LuaString::from_stack(idx, lua)?;
let BorrowedStr { buf, _lua, .. } = BorrowedStr::try_from(&s)?;
let buf = unsafe { mem::transmute::<&str, &'static str>(buf) };
let borrow = Cow::Owned(s);
@@ -163,7 +162,7 @@ impl IntoLua for &BorrowedBytes<'_> {
impl FromLua for BorrowedBytes<'_> {
fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
let s = String::from_lua(value, lua)?;
let s = LuaString::from_lua(value, lua)?;
let BorrowedBytes { buf, _lua, .. } = BorrowedBytes::from(&s);
let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
let borrow = Cow::Owned(s);
@@ -171,7 +170,7 @@ impl FromLua for BorrowedBytes<'_> {
}
unsafe fn from_stack(idx: c_int, lua: &RawLua) -> Result<Self> {
let s = String::from_stack(idx, lua)?;
let s = LuaString::from_stack(idx, lua)?;
let BorrowedBytes { buf, _lua, .. } = BorrowedBytes::from(&s);
let buf = unsafe { mem::transmute::<&[u8], &'static [u8]>(buf) };
let borrow = Cow::Owned(s);
@@ -497,7 +496,7 @@ impl FromLua for crate::Buffer {
}
}
impl IntoLua for StdString {
impl IntoLua for String {
#[inline]
fn into_lua(self, lua: &Lua) -> Result<Value> {
#[cfg(feature = "lua55")]
@@ -519,7 +518,7 @@ impl IntoLua for StdString {
}
}
impl FromLua for StdString {
impl FromLua for String {
#[inline]
fn from_lua(value: Value, lua: &Lua) -> Result<Self> {
let ty = value.type_name();
+16 -17
View File
@@ -4,7 +4,6 @@ use std::io::Error as IoError;
use std::net::AddrParseError;
use std::result::Result as StdResult;
use std::str::Utf8Error;
use std::string::String as StdString;
use std::sync::Arc;
use crate::private::Sealed;
@@ -22,7 +21,7 @@ pub enum Error {
/// Syntax error while parsing Lua source code.
SyntaxError {
/// The error message as returned by Lua.
message: StdString,
message: String,
/// `true` if the error can likely be fixed by appending more input to the source code.
///
/// This is useful for implementing REPLs as they can query the user for more input if this
@@ -34,20 +33,20 @@ pub enum Error {
/// The Lua VM returns this error when a builtin operation is performed on incompatible types.
/// Among other things, this includes invoking operators on wrong types (such as calling or
/// indexing a `nil` value).
RuntimeError(StdString),
RuntimeError(String),
/// Lua memory error, aka `LUA_ERRMEM`
///
/// The Lua VM returns this error when the allocator does not return the requested memory, aka
/// it is an out-of-memory error.
MemoryError(StdString),
MemoryError(String),
/// Lua garbage collector error, aka `LUA_ERRGCMM`.
///
/// The Lua VM returns this error when there is an error running a `__gc` metamethod.
#[cfg(any(feature = "lua53", feature = "lua52", doc))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "lua53", feature = "lua52"))))]
GarbageCollectorError(StdString),
GarbageCollectorError(String),
/// Potentially unsafe action in safe mode.
SafetyError(StdString),
SafetyError(String),
/// Memory control is not available.
///
/// This error can only happen when Lua state was not created by us and does not have the
@@ -80,11 +79,11 @@ pub enum Error {
/// (which is stored in the corresponding field).
BadArgument {
/// Function that was called.
to: Option<StdString>,
to: Option<String>,
/// Argument position (usually starts from 1).
pos: usize,
/// Argument name.
name: Option<StdString>,
name: Option<String>,
/// Underlying error returned when converting argument to a Lua value.
cause: Arc<Error>,
},
@@ -95,7 +94,7 @@ pub enum Error {
/// Name of the Lua type that could not be created.
to: &'static str,
/// A message indicating why the conversion failed in more detail.
message: Option<StdString>,
message: Option<String>,
},
/// A Lua value could not be converted to the expected Rust type.
FromLuaConversionError {
@@ -104,7 +103,7 @@ pub enum Error {
/// Name of the Rust type that could not be created.
to: String,
/// A string containing more detailed error information.
message: Option<StdString>,
message: Option<String>,
},
/// [`Thread::resume`] was called on an unresumable coroutine.
///
@@ -154,17 +153,17 @@ pub enum Error {
/// A [`MetaMethod`] operation is restricted (typically for `__gc` or `__metatable`).
///
/// [`MetaMethod`]: crate::MetaMethod
MetaMethodRestricted(StdString),
MetaMethodRestricted(String),
/// A [`MetaMethod`] (eg. `__index` or `__newindex`) has invalid type.
///
/// [`MetaMethod`]: crate::MetaMethod
MetaMethodTypeError {
/// Name of the metamethod.
method: StdString,
method: String,
/// Passed value type.
type_name: &'static str,
/// A string containing more detailed error information.
message: Option<StdString>,
message: Option<String>,
},
/// A [`RegistryKey`] produced from a different Lua state was used.
///
@@ -173,7 +172,7 @@ pub enum Error {
/// A Rust callback returned `Err`, raising the contained `Error` as a Lua error.
CallbackError {
/// Lua call stack backtrace.
traceback: StdString,
traceback: String,
/// Original error returned by the Rust code.
cause: Arc<Error>,
},
@@ -185,11 +184,11 @@ pub enum Error {
/// Serialization error.
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
SerializeError(StdString),
SerializeError(String),
/// Deserialization error.
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
DeserializeError(StdString),
DeserializeError(String),
/// A custom error.
///
/// This can be used for returning user-defined errors from callbacks.
@@ -201,7 +200,7 @@ pub enum Error {
/// An error with additional context.
WithContext {
/// A string containing additional context.
context: StdString,
context: String,
/// Underlying error.
cause: Arc<Error>,
},
+1 -1
View File
@@ -107,7 +107,7 @@ pub use crate::multi::{MultiValue, Variadic};
pub use crate::scope::Scope;
pub use crate::state::{GCMode, Lua, LuaOptions, WeakLua};
pub use crate::stdlib::StdLib;
pub use crate::string::{BorrowedBytes, BorrowedStr, String};
pub use crate::string::{BorrowedBytes, BorrowedStr, LuaString, LuaString as String};
pub use crate::table::{Table, TablePairs, TableSequence};
pub use crate::thread::{Thread, ThreadStatus};
pub use crate::traits::{
+2 -2
View File
@@ -7,9 +7,9 @@ pub use crate::{
ExternalError as LuaExternalError, ExternalResult as LuaExternalResult, FromLua, FromLuaMulti,
Function as LuaFunction, FunctionInfo as LuaFunctionInfo, GCMode as LuaGCMode, Integer as LuaInteger,
IntoLua, IntoLuaMulti, LightUserData as LuaLightUserData, Lua, LuaNativeFn, LuaNativeFnMut, LuaOptions,
MetaMethod as LuaMetaMethod, MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber,
LuaString, MetaMethod as LuaMetaMethod, MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber,
ObjectLike as LuaObjectLike, RegistryKey as LuaRegistryKey, Result as LuaResult, StdLib as LuaStdLib,
String as LuaString, Table as LuaTable, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence,
Table as LuaTable, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence,
Thread as LuaThread, ThreadStatus as LuaThreadStatus, UserData as LuaUserData,
UserDataFields as LuaUserDataFields, UserDataMetatable as LuaUserDataMetatable,
UserDataMethods as LuaUserDataMethods, UserDataRef as LuaUserDataRef,
+2 -3
View File
@@ -4,7 +4,6 @@ use std::cell::RefCell;
use std::os::raw::c_void;
use std::rc::Rc;
use std::result::Result as StdResult;
use std::string::String as StdString;
use rustc_hash::FxHashSet;
use serde::de::{self, IntoDeserializer};
@@ -243,7 +242,7 @@ impl<'de> serde::Deserializer<'de> for Deserializer {
Value::Table(table) => {
let _guard = RecursionGuard::new(&table, &self.visited);
let mut iter = table.pairs::<StdString, Value>();
let mut iter = table.pairs::<String, Value>();
let (variant, value) = match iter.next() {
Some(v) => v?,
None => {
@@ -621,7 +620,7 @@ impl<'de> de::MapAccess<'de> for MapDeserializer<'_> {
}
struct EnumDeserializer {
variant: StdString,
variant: String,
value: Option<Value>,
options: Options,
visited: Rc<RefCell<FxHashSet<*const c_void>>>,
+8 -9
View File
@@ -15,7 +15,7 @@ use crate::memory::MemoryState;
use crate::multi::MultiValue;
use crate::scope::Scope;
use crate::stdlib::StdLib;
use crate::string::String;
use crate::string::LuaString;
use crate::table::Table;
use crate::thread::Thread;
use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
@@ -855,7 +855,6 @@ impl Lua {
{
use std::ffi::CStr;
use std::os::raw::{c_char, c_void};
use std::string::String as StdString;
unsafe extern "C-unwind" fn warn_proc(ud: *mut c_void, msg: *const c_char, tocont: c_int) {
let extra = ud as *mut ExtraData;
@@ -865,7 +864,7 @@ impl Lua {
if XRc::strong_count(&warn_callback) > 2 {
return Ok(());
}
let msg = StdString::from_utf8_lossy(CStr::from_ptr(msg).to_bytes());
let msg = String::from_utf8_lossy(CStr::from_ptr(msg).to_bytes());
warn_callback((*extra).lua(), &msg, tocont != 0)
});
}
@@ -936,7 +935,7 @@ impl Lua {
///
/// The `msg` parameter, if provided, is added at the beginning of the traceback.
/// The `level` parameter works the same way as in [`Lua::inspect_stack`].
pub fn traceback(&self, msg: Option<&str>, level: usize) -> Result<String> {
pub fn traceback(&self, msg: Option<&str>, level: usize) -> Result<LuaString> {
let lua = self.lock();
unsafe {
check_stack(lua.state(), 3)?;
@@ -948,7 +947,7 @@ impl Lua {
// `protect_lua` adds it's own call frame, so we need to increase level by 1
ffi::luaL_traceback(state, state, msg, (level + 1) as c_int);
})?;
Ok(String(lua.pop_ref()))
Ok(LuaString(lua.pop_ref()))
}
}
@@ -1248,7 +1247,7 @@ impl Lua {
/// Lua strings can be arbitrary `[u8]` data including embedded nulls, so in addition to `&str`
/// and `&String`, you can also pass plain `&[u8]` here.
#[inline]
pub fn create_string(&self, s: impl AsRef<[u8]>) -> Result<String> {
pub fn create_string(&self, s: impl AsRef<[u8]>) -> Result<LuaString> {
unsafe { self.lock().create_string(s.as_ref()) }
}
@@ -1259,7 +1258,7 @@ impl Lua {
#[cfg(feature = "lua55")]
#[cfg_attr(docsrs, doc(cfg(feature = "lua55")))]
#[inline]
pub fn create_external_string(&self, s: impl Into<Vec<u8>>) -> Result<String> {
pub fn create_external_string(&self, s: impl Into<Vec<u8>>) -> Result<LuaString> {
unsafe { self.lock().create_external_string(s.into()) }
}
@@ -1741,7 +1740,7 @@ impl Lua {
///
/// To succeed, the value must be a string (in which case this is a no-op), an integer, or a
/// number.
pub fn coerce_string(&self, v: Value) -> Result<Option<String>> {
pub fn coerce_string(&self, v: Value) -> Result<Option<LuaString>> {
Ok(match v {
Value::String(s) => Some(s),
v => unsafe {
@@ -1759,7 +1758,7 @@ impl Lua {
})?
};
if !res.is_null() {
Some(String(lua.pop_ref()))
Some(LuaString(lua.pop_ref()))
} else {
None
}
+8 -8
View File
@@ -13,7 +13,7 @@ use crate::function::Function;
use crate::memory::{ALLOCATOR, MemoryState};
use crate::state::util::callback_error_ext;
use crate::stdlib::StdLib;
use crate::string::String;
use crate::string::LuaString;
use crate::table::Table;
use crate::thread::Thread;
use crate::traits::IntoLua;
@@ -516,34 +516,34 @@ impl RawLua {
}
/// See [`Lua::create_string`]
pub(crate) unsafe fn create_string(&self, s: &[u8]) -> Result<String> {
pub(crate) unsafe fn create_string(&self, s: &[u8]) -> Result<LuaString> {
let state = self.state();
if self.unlikely_memory_error() {
push_string(state, s, false)?;
return Ok(String(self.pop_ref()));
return Ok(LuaString(self.pop_ref()));
}
let _sg = StackGuard::new(state);
check_stack(state, 3)?;
push_string(state, s, true)?;
Ok(String(self.pop_ref()))
Ok(LuaString(self.pop_ref()))
}
/// Creates an external string, that is, a string that uses memory not managed by Lua.
///
/// Modifies the input data to add `\0` terminator.
#[cfg(feature = "lua55")]
pub(crate) unsafe fn create_external_string(&self, bytes: Vec<u8>) -> Result<String> {
pub(crate) unsafe fn create_external_string(&self, bytes: Vec<u8>) -> Result<LuaString> {
let state = self.state();
if self.unlikely_memory_error() {
crate::util::push_external_string(state, bytes, false)?;
return Ok(String(self.pop_ref()));
return Ok(LuaString(self.pop_ref()));
}
let _sg = StackGuard::new(state);
check_stack(state, 3)?;
crate::util::push_external_string(state, bytes, true)?;
Ok(String(self.pop_ref()))
Ok(LuaString(self.pop_ref()))
}
#[cfg(feature = "luau")]
@@ -824,7 +824,7 @@ impl RawLua {
ffi::LUA_TSTRING => {
ffi::lua_xpush(state, self.ref_thread(), idx);
Value::String(String(self.pop_ref_thread()))
Value::String(LuaString(self.pop_ref_thread()))
}
ffi::LUA_TTABLE => {
+38 -39
View File
@@ -2,7 +2,6 @@ use std::borrow::{Borrow, Cow};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::os::raw::{c_int, c_void};
use std::string::String as StdString;
use std::{cmp, fmt, slice, str};
use crate::error::{Error, Result};
@@ -21,23 +20,23 @@ use {
///
/// Unlike Rust strings, Lua strings may not be valid UTF-8.
#[derive(Clone)]
pub struct String(pub(crate) ValueRef);
pub struct LuaString(pub(crate) ValueRef);
impl String {
impl LuaString {
/// Get a [`BorrowedStr`] if the Lua string is valid UTF-8.
///
/// # Examples
///
/// ```
/// # use mlua::{Lua, Result, String};
/// # use mlua::{Lua, LuaString, Result};
/// # fn main() -> Result<()> {
/// # let lua = Lua::new();
/// let globals = lua.globals();
///
/// let version: String = globals.get("_VERSION")?;
/// let version: LuaString = globals.get("_VERSION")?;
/// assert!(version.to_str()?.contains("Lua"));
///
/// let non_utf8: String = lua.load(r#" "test\255" "#).eval()?;
/// let non_utf8: LuaString = lua.load(r#" "test\255" "#).eval()?;
/// assert!(non_utf8.to_str().is_err());
/// # Ok(())
/// # }
@@ -47,11 +46,11 @@ impl String {
BorrowedStr::try_from(self)
}
/// Converts this string to a [`StdString`].
/// Converts this Lua string to a [`String`].
///
/// Any non-Unicode sequences are replaced with [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD].
///
/// This method returns [`StdString`] instead of [`Cow<'_, str>`] because lifetime cannot be
/// This method returns [`String`] instead of [`Cow<'_, str>`] because lifetime cannot be
/// bound to a weak Lua object.
///
/// [U+FFFD]: std::char::REPLACEMENT_CHARACTER
@@ -70,11 +69,11 @@ impl String {
/// # }
/// ```
#[inline]
pub fn to_string_lossy(&self) -> StdString {
StdString::from_utf8_lossy(&self.as_bytes()).into_owned()
pub fn to_string_lossy(&self) -> String {
String::from_utf8_lossy(&self.as_bytes()).into_owned()
}
/// Returns an object that implements [`Display`] for safely printing a Lua [`String`] that may
/// Returns an object that implements [`Display`] for safely printing a [`LuaString`] that may
/// contain non-Unicode data.
///
/// This may perform lossy conversion.
@@ -92,10 +91,10 @@ impl String {
/// # Examples
///
/// ```
/// # use mlua::{Lua, Result, String};
/// # use mlua::{Lua, LuaString, Result};
/// # fn main() -> Result<()> {
/// # let lua = Lua::new();
/// let non_utf8: String = lua.load(r#" "test\255" "#).eval()?;
/// let non_utf8: LuaString = lua.load(r#" "test\255" "#).eval()?;
/// assert!(non_utf8.to_str().is_err()); // oh no :(
/// assert_eq!(non_utf8.as_bytes(), &b"test\xff"[..]);
/// # Ok(())
@@ -135,7 +134,7 @@ impl String {
(slice, lua)
}
/// Converts this string to a generic C pointer.
/// Converts this Lua string to a generic C pointer.
///
/// There is no way to convert the pointer back to its original value.
///
@@ -146,7 +145,7 @@ impl String {
}
}
impl fmt::Debug for String {
impl fmt::Debug for LuaString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let bytes = self.as_bytes();
// Check if the string is valid utf8
@@ -162,12 +161,12 @@ impl fmt::Debug for String {
// Lua strings are basically `&[u8]` slices, so implement `PartialEq` for anything resembling that.
//
// This makes our `String` comparable with `Vec<u8>`, `[u8]`, `&str` and `String`.
// This makes our `LuaString` comparable with `Vec<u8>`, `[u8]`, `&str` and `String`.
//
// 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<T> PartialEq<T> for String
impl<T> PartialEq<T> for LuaString
where
T: AsRef<[u8]> + ?Sized,
{
@@ -176,43 +175,43 @@ where
}
}
impl PartialEq for String {
fn eq(&self, other: &String) -> bool {
impl PartialEq for LuaString {
fn eq(&self, other: &LuaString) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Eq for String {}
impl Eq for LuaString {}
impl<T> PartialOrd<T> for String
impl<T> PartialOrd<T> for LuaString
where
T: AsRef<[u8]> + ?Sized,
{
fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
self.as_bytes().partial_cmp(&other.as_ref())
<[u8]>::partial_cmp(&self.as_bytes(), other.as_ref())
}
}
impl PartialOrd for String {
fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
impl PartialOrd for LuaString {
fn partial_cmp(&self, other: &LuaString) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for String {
fn cmp(&self, other: &String) -> cmp::Ordering {
impl Ord for LuaString {
fn cmp(&self, other: &LuaString) -> cmp::Ordering {
self.as_bytes().cmp(&other.as_bytes())
}
}
impl Hash for String {
impl Hash for LuaString {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
#[cfg(feature = "serde")]
impl Serialize for String {
impl Serialize for LuaString {
fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
where
S: Serializer,
@@ -224,7 +223,7 @@ impl Serialize for String {
}
}
struct Display<'a>(&'a String);
struct Display<'a>(&'a LuaString);
impl fmt::Display for Display<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -237,7 +236,7 @@ impl fmt::Display for Display<'_> {
pub struct BorrowedStr<'a> {
// `buf` points to a readonly memory managed by Lua
pub(crate) buf: &'a str,
pub(crate) borrow: Cow<'a, String>,
pub(crate) borrow: Cow<'a, LuaString>,
pub(crate) _lua: Lua,
}
@@ -302,11 +301,11 @@ impl Ord for BorrowedStr<'_> {
}
}
impl<'a> TryFrom<&'a String> for BorrowedStr<'a> {
impl<'a> TryFrom<&'a LuaString> for BorrowedStr<'a> {
type Error = Error;
#[inline]
fn try_from(value: &'a String) -> Result<Self> {
fn try_from(value: &'a LuaString) -> Result<Self> {
let BorrowedBytes { buf, borrow, _lua } = BorrowedBytes::from(value);
let buf = str::from_utf8(buf).map_err(|e| Error::FromLuaConversionError {
from: "string",
@@ -321,7 +320,7 @@ impl<'a> TryFrom<&'a String> for BorrowedStr<'a> {
pub struct BorrowedBytes<'a> {
// `buf` points to a readonly memory managed by Lua
pub(crate) buf: &'a [u8],
pub(crate) borrow: Cow<'a, String>,
pub(crate) borrow: Cow<'a, LuaString>,
pub(crate) _lua: Lua,
}
@@ -389,9 +388,9 @@ impl<'a> IntoIterator for &'a BorrowedBytes<'_> {
}
}
impl<'a> From<&'a String> for BorrowedBytes<'a> {
impl<'a> From<&'a LuaString> for BorrowedBytes<'a> {
#[inline]
fn from(value: &'a String) -> Self {
fn from(value: &'a LuaString) -> Self {
let (buf, _lua) = unsafe { value.to_slice() };
let borrow = Cow::Borrowed(value);
Self { buf, borrow, _lua }
@@ -400,7 +399,7 @@ impl<'a> From<&'a String> for BorrowedBytes<'a> {
struct WrappedString<T: AsRef<[u8]>>(T);
impl String {
impl LuaString {
/// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
///
/// This function uses [`Lua::create_string`] under the hood.
@@ -415,7 +414,7 @@ impl<T: AsRef<[u8]>> IntoLua for WrappedString<T> {
}
}
impl LuaType for String {
impl LuaType for LuaString {
const TYPE_ID: c_int = ffi::LUA_TSTRING;
}
@@ -424,9 +423,9 @@ mod assertions {
use super::*;
#[cfg(not(feature = "send"))]
static_assertions::assert_not_impl_any!(String: Send);
static_assertions::assert_not_impl_any!(LuaString: Send);
#[cfg(feature = "send")]
static_assertions::assert_impl_all!(String: Send, Sync);
static_assertions::assert_impl_all!(LuaString: Send, Sync);
#[cfg(feature = "send")]
static_assertions::assert_impl_all!(BorrowedBytes: Send, Sync);
#[cfg(feature = "send")]
+3 -4
View File
@@ -2,7 +2,6 @@ use std::collections::HashSet;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::string::String as StdString;
use crate::error::{Error, Result};
use crate::function::Function;
@@ -1008,7 +1007,7 @@ impl ObjectLike for Table {
}
#[inline]
fn to_string(&self) -> Result<StdString> {
fn to_string(&self) -> Result<String> {
Value::Table(Table(self.0.clone())).to_string()
}
@@ -1098,7 +1097,7 @@ impl Serialize for SerializableTable<'_> {
seq.serialize_element(&SerializableValue::new(&value, options, Some(visited)))
.map_err(|err| {
serialize_err = Some(err);
Error::SerializeError(StdString::new())
Error::SerializeError(String::new())
})
});
convert_result(res, serialize_err)?;
@@ -1123,7 +1122,7 @@ impl Serialize for SerializableTable<'_> {
)
.map_err(|err| {
serialize_err = Some(err);
Error::SerializeError(StdString::new())
Error::SerializeError(String::new())
})
};
+2 -3
View File
@@ -1,5 +1,4 @@
use std::os::raw::c_int;
use std::string::String as StdString;
use std::sync::Arc;
use crate::error::{Error, Result};
@@ -236,7 +235,7 @@ pub trait ObjectLike: Sealed {
/// Converts the object to a string in a human-readable format.
///
/// This might invoke the `__tostring` metamethod.
fn to_string(&self) -> Result<StdString>;
fn to_string(&self) -> Result<String>;
/// Converts the object to a Lua value.
fn to_value(&self) -> Value;
@@ -339,7 +338,7 @@ impl_lua_native_fn!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
pub(crate) trait ShortTypeName {
#[inline(always)]
fn type_name() -> StdString {
fn type_name() -> String {
short_type_name::<Self>()
}
}
+30 -31
View File
@@ -3,12 +3,11 @@ use std::ffi::CStr;
use std::fmt;
use std::hash::Hash;
use std::os::raw::{c_char, c_void};
use std::string::String as StdString;
use crate::error::{Error, Result};
use crate::function::Function;
use crate::state::Lua;
use crate::string::String;
use crate::string::LuaString;
use crate::table::{Table, TablePairs};
use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
use crate::types::{MaybeSend, ValueRef};
@@ -185,7 +184,7 @@ impl PartialEq<MetaMethod> for &str {
}
}
impl PartialEq<MetaMethod> for StdString {
impl PartialEq<MetaMethod> for String {
fn eq(&self, other: &MetaMethod) -> bool {
self == other.name()
}
@@ -279,7 +278,7 @@ impl AsRef<str> for MetaMethod {
}
}
impl From<MetaMethod> for StdString {
impl From<MetaMethod> for String {
#[inline]
fn from(method: MetaMethod) -> Self {
method.name().to_owned()
@@ -295,7 +294,7 @@ pub trait UserDataMethods<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, the `__index` metamethod will
/// be used as a fall-back if no regular method is found.
fn add_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -306,7 +305,7 @@ pub trait UserDataMethods<T> {
/// Refer to [`add_method`] for more information about the implementation.
///
/// [`add_method`]: UserDataMethods::add_method
fn add_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -320,7 +319,7 @@ pub trait UserDataMethods<T> {
/// The method can be called only once per userdata instance, subsequent calls will result in a
/// [`Error::UserDataDestructed`] error.
#[doc(hidden)]
fn add_method_once<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_method_once<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(&Lua, T, A) -> Result<R> + MaybeSend + 'static,
@@ -342,7 +341,7 @@ pub trait UserDataMethods<T> {
/// [`add_method`]: UserDataMethods::add_method
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -357,7 +356,7 @@ pub trait UserDataMethods<T> {
/// [`add_method`]: UserDataMethods::add_method
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -375,7 +374,7 @@ pub trait UserDataMethods<T> {
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
#[doc(hidden)]
fn add_async_method_once<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_method_once<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, T, A) -> MR + MaybeSend + 'static,
@@ -398,7 +397,7 @@ pub trait UserDataMethods<T> {
/// The first argument will be a [`AnyUserData`] of type `T` if the method is called with Lua
/// method syntax: `my_userdata:my_method(arg1, arg2)`, or it is passed in as the first
/// argument: `my_userdata.my_method(my_userdata, arg1, arg2)`.
fn add_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -409,7 +408,7 @@ pub trait UserDataMethods<T> {
/// This is a version of [`add_function`] that accepts a `FnMut` argument.
///
/// [`add_function`]: UserDataMethods::add_function
fn add_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_function_mut<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -423,7 +422,7 @@ pub trait UserDataMethods<T> {
/// [`add_function`]: UserDataMethods::add_function
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
@@ -438,7 +437,7 @@ pub trait UserDataMethods<T> {
/// side has a metatable. To prevent this, use [`add_meta_function`].
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -452,7 +451,7 @@ pub trait UserDataMethods<T> {
/// side has a metatable. To prevent this, use [`add_meta_function`].
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -468,7 +467,7 @@ pub trait UserDataMethods<T> {
docsrs,
doc(cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau")))))
)]
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -484,7 +483,7 @@ pub trait UserDataMethods<T> {
/// [`add_meta_method_mut`]: UserDataMethods::add_meta_method_mut
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -497,7 +496,7 @@ pub trait UserDataMethods<T> {
/// Metamethods for binary operators can be triggered if either the left or right argument to
/// the binary operator has a metatable, so the first argument here is not necessarily a
/// userdata of type `T`.
fn add_meta_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_meta_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -508,7 +507,7 @@ pub trait UserDataMethods<T> {
/// This is a version of [`add_meta_function`] that accepts a `FnMut` argument.
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -524,7 +523,7 @@ pub trait UserDataMethods<T> {
docsrs,
doc(cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau")))))
)]
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
@@ -543,7 +542,7 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, it will
/// be used as a fall-back if no regular field or method are found.
fn add_field<V>(&mut self, name: impl Into<StdString>, value: V)
fn add_field<V>(&mut self, name: impl Into<String>, value: V)
where
V: IntoLua + 'static;
@@ -554,7 +553,7 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, the `__index` metamethod will
/// be used as a fall-back if no regular field or method are found.
fn add_field_method_get<M, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
R: IntoLua;
@@ -567,21 +566,21 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__newindex` metamethod, the `__newindex` metamethod
/// will be used as a fall-back if no regular field is found.
fn add_field_method_set<M, A>(&mut self, name: impl Into<StdString>, method: M)
fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
A: FromLua;
/// Add a regular field getter as a function which accepts a generic [`AnyUserData`] of type `T`
/// argument.
fn add_field_function_get<F, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
R: IntoLua;
/// Add a regular field setter as a function which accepts a generic [`AnyUserData`] of type `T`
/// first argument.
fn add_field_function_set<F, A>(&mut self, name: impl Into<StdString>, function: F)
fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, function: F)
where
F: FnMut(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
A: FromLua;
@@ -594,7 +593,7 @@ pub trait UserDataFields<T> {
///
/// `mlua` will trigger an error on an attempt to define a protected metamethod,
/// like `__gc` or `__metatable`.
fn add_meta_field<V>(&mut self, name: impl Into<StdString>, value: V)
fn add_meta_field<V>(&mut self, name: impl Into<String>, value: V)
where
V: IntoLua + 'static;
@@ -606,7 +605,7 @@ pub trait UserDataFields<T> {
///
/// `mlua` will trigger an error on an attempt to define a protected metamethod,
/// like `__gc` or `__metatable`.
fn add_meta_field_with<F, R>(&mut self, name: impl Into<StdString>, f: F)
fn add_meta_field_with<F, R>(&mut self, name: impl Into<String>, f: F)
where
F: FnOnce(&Lua) -> Result<R> + 'static,
R: IntoLua;
@@ -1022,7 +1021,7 @@ impl AnyUserData {
/// Returns a type name of this userdata (from a metatable field).
///
/// If no type name is set, returns `None`.
pub fn type_name(&self) -> Result<Option<StdString>> {
pub fn type_name(&self) -> Result<Option<String>> {
let lua = self.0.lua.lock();
let state = lua.state();
unsafe {
@@ -1039,7 +1038,7 @@ impl AnyUserData {
ffi::luaL_getmetafield(state, -1, MetaMethod::Type.as_cstr().as_ptr())
};
match name_type {
ffi::LUA_TSTRING => Ok(Some(String(lua.pop_ref()).to_str()?.to_owned())),
ffi::LUA_TSTRING => Ok(Some(LuaString(lua.pop_ref()).to_str()?.to_owned())),
_ => Ok(None),
}
}
@@ -1126,13 +1125,13 @@ impl UserDataMetatable {
/// It skips restricted metamethods, such as `__gc` or `__metatable`.
///
/// This struct is created by the [`UserDataMetatable::pairs`] method.
pub struct UserDataMetatablePairs<'a, V>(TablePairs<'a, StdString, V>);
pub struct UserDataMetatablePairs<'a, V>(TablePairs<'a, String, V>);
impl<V> Iterator for UserDataMetatablePairs<'_, V>
where
V: FromLua,
{
type Item = Result<(StdString, V)>;
type Item = Result<(String, V)>;
fn next(&mut self) -> Option<Self::Item> {
loop {
+1 -2
View File
@@ -1,4 +1,3 @@
use std::string::String as StdString;
use crate::Function;
use crate::error::{Error, Result};
@@ -88,7 +87,7 @@ impl ObjectLike for AnyUserData {
}
#[inline]
fn to_string(&self) -> Result<StdString> {
fn to_string(&self) -> Result<String> {
Value::UserData(self.clone()).to_string()
}
+23 -24
View File
@@ -4,7 +4,6 @@ use std::any::TypeId;
use std::cell::RefCell;
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::string::String as StdString;
use crate::error::{Error, Result};
use crate::state::{Lua, LuaGuard};
@@ -55,7 +54,7 @@ pub(crate) struct RawUserDataRegistry {
pub(crate) destructor: ffi::lua_CFunction,
pub(crate) type_id: Option<TypeId>,
pub(crate) type_name: StdString,
pub(crate) type_name: String,
#[cfg(feature = "luau")]
pub(crate) enable_namecall: bool,
@@ -382,12 +381,12 @@ impl<T> UserDataRegistry<T> {
}
// Returns function name for the type `T`, without the module path
fn get_function_name<T>(name: &str) -> StdString {
fn get_function_name<T>(name: &str) -> String {
format!("{}.{name}", short_type_name::<T>())
}
impl<T> UserDataFields<T> for UserDataRegistry<T> {
fn add_field<V>(&mut self, name: impl Into<StdString>, value: V)
fn add_field<V>(&mut self, name: impl Into<String>, value: V)
where
V: IntoLua + 'static,
{
@@ -395,7 +394,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.fields.push((name, value.into_lua(self.lua.lua())));
}
fn add_field_method_get<M, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_field_method_get<M, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
R: IntoLua,
@@ -405,7 +404,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.field_getters.push((name, callback));
}
fn add_field_method_set<M, A>(&mut self, name: impl Into<StdString>, method: M)
fn add_field_method_set<M, A>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
A: FromLua,
@@ -415,7 +414,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.field_setters.push((name, callback));
}
fn add_field_function_get<F, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_field_function_get<F, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
R: IntoLua,
@@ -425,7 +424,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.field_getters.push((name, callback));
}
fn add_field_function_set<F, A>(&mut self, name: impl Into<StdString>, mut function: F)
fn add_field_function_set<F, A>(&mut self, name: impl Into<String>, mut function: F)
where
F: FnMut(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
A: FromLua,
@@ -435,7 +434,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.field_setters.push((name, callback));
}
fn add_meta_field<V>(&mut self, name: impl Into<StdString>, value: V)
fn add_meta_field<V>(&mut self, name: impl Into<String>, value: V)
where
V: IntoLua + 'static,
{
@@ -445,7 +444,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
self.raw.meta_fields.push((name, field));
}
fn add_meta_field_with<F, R>(&mut self, name: impl Into<StdString>, f: F)
fn add_meta_field_with<F, R>(&mut self, name: impl Into<String>, f: F)
where
F: FnOnce(&Lua) -> Result<R> + 'static,
R: IntoLua,
@@ -458,7 +457,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
}
impl<T> UserDataMethods<T> for UserDataRegistry<T> {
fn add_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -469,7 +468,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.methods.push((name, callback));
}
fn add_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -481,7 +480,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(feature = "async")]
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -495,7 +494,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(feature = "async")]
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -508,7 +507,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.async_methods.push((name, callback));
}
fn add_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -519,7 +518,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.methods.push((name, callback));
}
fn add_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_function_mut<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -531,7 +530,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(feature = "async")]
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
@@ -543,7 +542,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.async_methods.push((name, callback));
}
fn add_meta_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_meta_method<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -554,7 +553,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.meta_methods.push((name, callback));
}
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<String>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -566,7 +565,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -580,7 +579,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<String>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -593,7 +592,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.async_meta_methods.push((name, callback));
}
fn add_meta_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_meta_function<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -604,7 +603,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
self.raw.meta_methods.push((name, callback));
}
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<String>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -616,7 +615,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<String>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
+14 -15
View File
@@ -1,14 +1,13 @@
use std::cmp::Ordering;
use std::collections::HashSet;
use std::os::raw::c_void;
use std::string::String as StdString;
use std::{fmt, ptr, str};
use num_traits::FromPrimitive;
use crate::error::{Error, Result};
use crate::function::Function;
use crate::string::{BorrowedStr, String};
use crate::string::{BorrowedStr, LuaString};
use crate::table::Table;
use crate::thread::Thread;
use crate::types::{Integer, LightUserData, Number, ValueRef};
@@ -50,7 +49,7 @@ pub enum Value {
/// An interned string, managed by Lua.
///
/// Unlike Rust strings, Lua strings may not be valid UTF-8.
String(String),
String(LuaString),
/// Reference to a Lua table.
Table(Table),
/// Reference to a Lua function (or closure).
@@ -129,7 +128,7 @@ impl Value {
#[inline]
pub fn to_pointer(&self) -> *const c_void {
match self {
Value::String(String(vref)) => {
Value::String(LuaString(vref)) => {
// In Lua < 5.4 (excluding Luau), string pointers are NULL
// Use alternative approach
let lua = vref.lua.lock();
@@ -151,8 +150,8 @@ impl Value {
///
/// This might invoke the `__tostring` metamethod for non-primitive types (eg. tables,
/// functions).
pub fn to_string(&self) -> Result<StdString> {
unsafe fn invoke_to_string(vref: &ValueRef) -> Result<StdString> {
pub fn to_string(&self) -> Result<String> {
unsafe fn invoke_to_string(vref: &ValueRef) -> Result<String> {
let lua = vref.lua.lock();
let state = lua.state();
let _guard = StackGuard::new(state);
@@ -162,7 +161,7 @@ impl Value {
protect_lua!(state, 1, 1, fn(state) {
ffi::luaL_tolstring(state, -1, ptr::null_mut());
})?;
Ok(String(lua.pop_ref()).to_str()?.to_string())
Ok(LuaString(lua.pop_ref()).to_str()?.to_string())
}
match self {
@@ -336,17 +335,17 @@ impl Value {
self.as_number()
}
/// Returns `true` if the value is a Lua [`String`].
/// Returns `true` if the value is a [`LuaString`].
#[inline]
pub fn is_string(&self) -> bool {
self.as_string().is_some()
}
/// Cast the value to Lua [`String`].
/// Cast the value to a [`LuaString`].
///
/// If the value is a Lua [`String`], returns it or `None` otherwise.
/// If the value is a [`LuaString`], returns it or `None` otherwise.
#[inline]
pub fn as_string(&self) -> Option<&String> {
pub fn as_string(&self) -> Option<&LuaString> {
match self {
Value::String(s) => Some(s),
_ => None,
@@ -355,7 +354,7 @@ impl Value {
/// Cast the value to [`BorrowedStr`].
///
/// If the value is a Lua [`String`], try to convert it to [`BorrowedStr`] or return `None`
/// If the value is a [`LuaString`], try to convert it to [`BorrowedStr`] or return `None`
/// otherwise.
#[deprecated(
since = "0.11.0",
@@ -366,15 +365,15 @@ impl Value {
self.as_string().and_then(|s| s.to_str().ok())
}
/// Cast the value to [`StdString`].
/// Cast the value to [`String`].
///
/// If the value is a Lua [`String`], converts it to [`StdString`] or returns `None` otherwise.
/// If the value is a [`LuaString`], converts it to [`String`] or returns `None` otherwise.
#[deprecated(
since = "0.11.0",
note = "This method does not follow Rust naming convention. Use `as_string().map(|s| s.to_string_lossy())` instead."
)]
#[inline]
pub fn as_string_lossy(&self) -> Option<StdString> {
pub fn as_string_lossy(&self) -> Option<String> {
self.as_string().map(|s| s.to_string_lossy())
}
+2 -3
View File
@@ -1,6 +1,5 @@
#![cfg(feature = "async")]
use std::string::String as StdString;
use std::sync::Arc;
use std::time::Duration;
@@ -40,7 +39,7 @@ async fn test_async_function() -> Result<()> {
async fn test_async_function_wrap() -> Result<()> {
let lua = Lua::new();
let f = Function::wrap_async(|s: StdString| async move {
let f = Function::wrap_async(|s: String| async move {
tokio::task::yield_now().await;
Ok(s)
});
@@ -68,7 +67,7 @@ async fn test_async_function_wrap() -> Result<()> {
async fn test_async_function_wrap_raw() -> Result<()> {
let lua = Lua::new();
let f = Function::wrap_raw_async(|s: StdString| async move {
let f = Function::wrap_raw_async(|s: String| async move {
tokio::task::yield_now().await;
s
});
+1 -1
View File
@@ -49,7 +49,7 @@ fn test_string_from_lua() -> Result<()> {
let lua = Lua::new();
// From stack
let f = lua.create_function(|_, s: mlua::String| Ok(s))?;
let f = lua.create_function(|_, s: mlua::LuaString| Ok(s))?;
let s = f.call::<String>("hello, world!")?;
assert_eq!(s, "hello, world!");
+2 -2
View File
@@ -1,4 +1,4 @@
use mlua::{Error, Function, Lua, Result, String, Table, Variadic};
use mlua::{Error, Function, Lua, LuaString, Result, Table, Variadic};
#[test]
fn test_function_call() -> Result<()> {
@@ -343,7 +343,7 @@ fn test_function_deep_clone() -> Result<()> {
fn test_function_wrap() -> Result<()> {
let lua = Lua::new();
let f = Function::wrap(|s: String, n| Ok(s.to_str().unwrap().repeat(n)));
let f = Function::wrap(|s: LuaString, n| Ok(s.to_str().unwrap().repeat(n)));
lua.globals().set("f", f)?;
lua.load(r#"assert(f("hello", 2) == "hellohello")"#)
.exec()
+2 -2
View File
@@ -1,4 +1,4 @@
use mlua::{Error, ExternalError, Integer, IntoLuaMulti, Lua, MultiValue, Result, String, Value, Variadic};
use mlua::{Error, ExternalError, Integer, IntoLuaMulti, Lua, LuaString, MultiValue, Result, Value, Variadic};
#[test]
fn test_result_conversions() -> Result<()> {
@@ -81,7 +81,7 @@ fn test_multivalue_by_ref() -> Result<()> {
Value::Boolean(true),
]);
let f = lua.create_function(|_, (i, s, b): (i32, String, bool)| {
let f = lua.create_function(|_, (i, s, b): (i32, LuaString, bool)| {
assert_eq!(i, 3);
assert_eq!(s.to_str()?, "hello");
assert_eq!(b, true);
+7 -8
View File
@@ -1,10 +1,9 @@
use std::cell::Cell;
use std::rc::Rc;
use std::string::String as StdString;
use std::sync::Arc;
use mlua::{
AnyUserData, Error, Function, Lua, MetaMethod, ObjectLike, Result, String, UserData, UserDataFields,
AnyUserData, Error, Function, Lua, LuaString, MetaMethod, ObjectLike, Result, UserData, UserDataFields,
UserDataMethods, UserDataRegistry,
};
@@ -437,15 +436,15 @@ fn test_scope_userdata_ref_mut() -> Result<()> {
fn test_scope_any_userdata() -> Result<()> {
let lua = Lua::new();
fn register(reg: &mut UserDataRegistry<&mut StdString>) {
reg.add_method_mut("push", |_, this, s: String| {
fn register(reg: &mut UserDataRegistry<&mut String>) {
reg.add_method_mut("push", |_, this, s: LuaString| {
this.push_str(&s.to_str()?);
Ok(())
});
reg.add_meta_method("__tostring", |_, data, ()| Ok((*data).clone()));
}
let mut data = StdString::from("foo");
let mut data = String::from("foo");
lua.scope(|scope| {
let ud = scope.create_any_userdata(&mut data, register)?;
lua.globals().set("ud", ud)?;
@@ -527,11 +526,11 @@ fn test_scope_any_userdata_ref_mut() -> Result<()> {
fn test_scope_destructors() -> Result<()> {
let lua = Lua::new();
lua.register_userdata_type::<Arc<StdString>>(|reg| {
lua.register_userdata_type::<Arc<String>>(|reg| {
reg.add_meta_method("__tostring", |_, data, ()| Ok(data.to_string()));
})?;
let arc_str = Arc::new(StdString::from("foo"));
let arc_str = Arc::new(String::from("foo"));
let ud = lua.create_any_userdata(arc_str.clone())?;
lua.scope(|scope| {
@@ -544,7 +543,7 @@ fn test_scope_destructors() -> Result<()> {
// Try destructing the userdata while it's borrowed
let ud = lua.create_any_userdata(arc_str.clone())?;
ud.borrow_scoped::<Arc<StdString>, _>(|arc_str| {
ud.borrow_scoped::<Arc<String>, _>(|arc_str| {
assert_eq!(arc_str.as_str(), "foo");
lua.scope(|scope| {
scope.add_destructor(|| {
+2 -3
View File
@@ -2,7 +2,6 @@
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::string::String as StdString;
use mlua::{AnyUserData, Error, Lua, ObjectLike, Result, UserData, UserDataMethods, UserDataRef};
use static_assertions::{assert_impl_all, assert_not_impl_all};
@@ -12,7 +11,7 @@ fn test_userdata_multithread_access_send_only() -> Result<()> {
let lua = Lua::new();
// This type is `Send` but not `Sync`.
struct MyUserData(StdString, PhantomData<UnsafeCell<()>>);
struct MyUserData(String, PhantomData<UnsafeCell<()>>);
assert_impl_all!(MyUserData: Send);
assert_not_impl_all!(MyUserData: Sync);
@@ -52,7 +51,7 @@ fn test_userdata_multithread_access_sync() -> Result<()> {
let lua = Lua::new();
// This type is `Send` and `Sync`.
struct MyUserData(StdString);
struct MyUserData(String);
assert_impl_all!(MyUserData: Send, Sync);
impl UserData for MyUserData {
+10 -10
View File
@@ -1,11 +1,11 @@
use std::borrow::Cow;
use std::collections::HashSet;
use mlua::{Lua, Result, String};
use mlua::{Lua, LuaString, Result};
#[test]
fn test_string_compare() {
fn with_str<F: FnOnce(String)>(s: &str, f: F) {
fn with_str<F: FnOnce(LuaString)>(s: &str, f: F) {
f(Lua::new().create_string(s).unwrap());
}
@@ -42,9 +42,9 @@ fn test_string_views() -> Result<()> {
.exec()?;
let globals = lua.globals();
let ok: String = globals.get("ok")?;
let err: String = globals.get("err")?;
let empty: String = globals.get("empty")?;
let ok: LuaString = globals.get("ok")?;
let err: LuaString = globals.get("err")?;
let empty: LuaString = globals.get("empty")?;
assert_eq!(ok.to_str()?, "null bytes are valid utf-8, wh\0 knew?");
assert_eq!(ok.to_string_lossy(), "null bytes are valid utf-8, wh\0 knew?");
@@ -74,7 +74,7 @@ fn test_string_from_bytes() -> Result<()> {
fn test_string_hash() -> Result<()> {
let lua = Lua::new();
let set: HashSet<String> = lua.load(r#"{"hello", "world", "abc", 321}"#).eval()?;
let set: HashSet<LuaString> = lua.load(r#"{"hello", "world", "abc", 321}"#).eval()?;
assert_eq!(set.len(), 4);
assert!(set.contains(&lua.create_string("hello")?));
assert!(set.contains(&lua.create_string("world")?));
@@ -133,13 +133,13 @@ fn test_string_display() -> Result<()> {
fn test_string_wrap() -> Result<()> {
let lua = Lua::new();
let s = String::wrap("hello, world");
let s = LuaString::wrap("hello, world");
lua.globals().set("s", s)?;
assert_eq!(lua.globals().get::<String>("s")?, "hello, world");
assert_eq!(lua.globals().get::<LuaString>("s")?, "hello, world");
let s2 = String::wrap("hello, world (owned)".to_string());
let s2 = LuaString::wrap("hello, world (owned)".to_string());
lua.globals().set("s2", s2)?;
assert_eq!(lua.globals().get::<String>("s2")?, "hello, world (owned)");
assert_eq!(lua.globals().get::<LuaString>("s2")?, "hello, world (owned)");
Ok(())
}
+13 -14
View File
@@ -2,12 +2,11 @@ use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use std::iter::FromIterator;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::string::String as StdString;
use std::sync::Arc;
use std::{error, f32, f64, fmt};
use mlua::{
ChunkMode, Error, ExternalError, Function, Lua, LuaOptions, Nil, Result, StdLib, String, Table, UserData,
ChunkMode, Error, ExternalError, Function, Lua, LuaOptions, Nil, Result, StdLib, Table, UserData,
Value, Variadic, ffi,
};
@@ -155,7 +154,7 @@ fn test_replace_globals() -> Result<()> {
globals.set("foo", "bar")?;
lua.set_globals(globals.clone())?;
let val = lua.load("return foo").eval::<StdString>()?;
let val = lua.load("return foo").eval::<String>()?;
assert_eq!(val, "bar");
// Updating globals in sandboxed Lua state is not allowed
@@ -398,7 +397,7 @@ fn test_error() -> Result<()> {
fn test_panic() -> Result<()> {
fn make_lua(options: LuaOptions) -> Result<Lua> {
let lua = Lua::new_with(StdLib::ALL_SAFE, options)?;
let rust_panic_function = lua.create_function(|_, msg: Option<StdString>| -> Result<()> {
let rust_panic_function = lua.create_function(|_, msg: Option<String>| -> Result<()> {
if let Some(msg) = msg {
panic!("{}", msg)
}
@@ -496,7 +495,7 @@ fn test_panic() -> Result<()> {
.exec()
}) {
Ok(r) => panic!("no panic was detected: {:?}", r),
Err(p) => assert!(*p.downcast::<StdString>().unwrap() == "rust panic from lua"),
Err(p) => assert!(*p.downcast::<String>().unwrap() == "rust panic from lua"),
}
// Test disabling `catch_rust_panics` option / xpcall correctness
@@ -520,7 +519,7 @@ fn test_panic() -> Result<()> {
.exec()
}) {
Ok(r) => panic!("no panic was detected: {:?}", r),
Err(p) => assert!(*p.downcast::<StdString>().unwrap() == "rust panic from lua"),
Err(p) => assert!(*p.downcast::<String>().unwrap() == "rust panic from lua"),
}
Ok(())
@@ -686,7 +685,7 @@ fn test_pcall_xpcall() -> Result<()> {
#[cfg(feature = "lua51")]
assert!(
globals
.get::<String>("xpcall_error")?
.get::<mlua::LuaString>("xpcall_error")?
.to_str()?
.ends_with(": testerror")
);
@@ -1073,7 +1072,7 @@ fn test_ref_stack_exhaustion() {
})) {
Ok(_) => panic!("no panic was detected"),
Err(p) => assert!(
p.downcast::<StdString>()
p.downcast::<String>()
.unwrap()
.starts_with("cannot create a Lua reference, out of auxiliary stack space")
),
@@ -1221,7 +1220,7 @@ fn test_context_thread_51() -> Result<()> {
fn test_jit_version() -> Result<()> {
let lua = Lua::new();
let jit: Table = lua.globals().get("jit")?;
assert!(jit.get::<String>("version")?.to_str()?.contains("LuaJIT"));
assert!(jit.get::<mlua::LuaString>("version")?.to_str()?.contains("LuaJIT"));
Ok(())
}
@@ -1321,7 +1320,7 @@ fn test_inspect_stack() -> Result<()> {
// Not inside any function
assert!(lua.inspect_stack(0, |_| ()).is_none());
let logline = lua.create_function(|lua, msg: StdString| {
let logline = lua.create_function(|lua, msg: String| {
let r = lua
.inspect_stack(1, |debug| {
let source = debug.source().short_src;
@@ -1425,7 +1424,7 @@ fn test_traceback() -> Result<()> {
assert!(traceback.contains("stack traceback:"));
// Test traceback inside a function
let get_traceback = lua.create_function(|lua, (msg, level): (Option<StdString>, usize)| {
let get_traceback = lua.create_function(|lua, (msg, level): (Option<String>, usize)| {
lua.traceback(msg.as_deref(), level)
})?;
lua.globals().set("get_traceback", get_traceback)?;
@@ -1507,10 +1506,10 @@ fn test_multi_states() -> Result<()> {
#[cfg(any(feature = "lua55", feature = "lua54"))]
fn test_warnings() -> Result<()> {
let lua = Lua::new();
lua.set_app_data::<Vec<(StdString, bool)>>(Vec::new());
lua.set_app_data::<Vec<(String, bool)>>(Vec::new());
lua.set_warning_function(|lua, msg, incomplete| {
lua.app_data_mut::<Vec<(StdString, bool)>>()
lua.app_data_mut::<Vec<(String, bool)>>()
.unwrap()
.push((msg.to_string(), incomplete));
Ok(())
@@ -1524,7 +1523,7 @@ fn test_warnings() -> Result<()> {
lua.remove_warning_function();
lua.warning("one more warning", false);
let messages = lua.app_data_ref::<Vec<(StdString, bool)>>().unwrap();
let messages = lua.app_data_ref::<Vec<(String, bool)>>().unwrap();
assert_eq!(
*messages,
vec![
+1 -1
View File
@@ -1,6 +1,6 @@
use std::os::raw::c_void;
use mlua::{Function, LightUserData, Lua, Number, Result, String as LuaString, Thread};
use mlua::{Function, LightUserData, Lua, LuaString, Number, Result, Thread};
#[test]
fn test_lightuserdata() -> Result<()> {
+16 -17
View File
@@ -1,13 +1,12 @@
use std::any::TypeId;
use std::collections::HashMap;
use std::string::String as StdString;
use std::sync::Arc;
#[cfg(any(feature = "lua55", feature = "lua54"))]
use std::sync::atomic::{AtomicI64, Ordering};
use mlua::{
AnyUserData, Error, ExternalError, Function, Lua, MetaMethod, Nil, ObjectLike, Result, String, UserData,
AnyUserData, Error, ExternalError, Function, Lua, LuaString, MetaMethod, Nil, ObjectLike, Result, UserData,
UserDataFields, UserDataMethods, UserDataRef, UserDataRegistry, Value, Variadic,
};
@@ -131,7 +130,7 @@ fn test_metamethods() -> Result<()> {
MetaMethod::Eq,
|_, (lhs, rhs): (UserDataRef<Self>, UserDataRef<Self>)| Ok(lhs.0 == rhs.0),
);
methods.add_meta_method(MetaMethod::Index, |_, data, index: String| {
methods.add_meta_method(MetaMethod::Index, |_, data, index: LuaString| {
if index.to_str()? == "inner" {
Ok(data.0)
} else {
@@ -492,8 +491,8 @@ fn test_user_values() -> Result<()> {
ud.set_nth_user_value(1, "hello")?;
ud.set_nth_user_value(2, "world")?;
ud.set_nth_user_value(65535, 321)?;
assert_eq!(ud.nth_user_value::<String>(1)?, "hello");
assert_eq!(ud.nth_user_value::<String>(2)?, "world");
assert_eq!(ud.nth_user_value::<LuaString>(1)?, "hello");
assert_eq!(ud.nth_user_value::<LuaString>(2)?, "world");
assert_eq!(ud.nth_user_value::<Value>(3)?, Value::Nil);
assert_eq!(ud.nth_user_value::<i32>(65535)?, 321);
@@ -583,8 +582,8 @@ fn test_fields() -> Result<()> {
});
// Use userdata "uservalue" storage
fields.add_field_function_get("uval", |_, ud| ud.user_value::<Option<String>>());
fields.add_field_function_set("uval", |_, ud, s: Option<String>| ud.set_user_value(s));
fields.add_field_function_get("uval", |_, ud| ud.user_value::<Option<LuaString>>());
fields.add_field_function_set("uval", |_, ud, s: Option<LuaString>| ud.set_user_value(s));
fields.add_meta_field(MetaMethod::Index, HashMap::from([("f", 321)]));
fields.add_meta_field_with(MetaMethod::NewIndex, |lua| {
@@ -631,7 +630,7 @@ fn test_fields() -> Result<()> {
}
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method(MetaMethod::Index, |_, _, name: StdString| match &*name {
methods.add_meta_method(MetaMethod::Index, |_, _, name: LuaString| match name.to_str()?.as_ref() {
"y" => Ok(Some(-1)),
_ => Ok(None),
});
@@ -660,7 +659,7 @@ fn test_metatable() -> Result<()> {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_function("my_type_name", |_, data: AnyUserData| {
let metatable = data.metatable()?;
metatable.get::<String>(MetaMethod::Type)
metatable.get::<LuaString>(MetaMethod::Type)
});
}
}
@@ -724,7 +723,7 @@ fn test_metatable() -> Result<()> {
let ud = lua.create_userdata(MyUserData3)?;
let metatable = ud.metatable()?;
assert_eq!(metatable.get::<String>(MetaMethod::Type)?.to_str()?, "CustomName");
assert_eq!(metatable.get::<LuaString>(MetaMethod::Type)?.to_str()?, "CustomName");
Ok(())
}
@@ -777,16 +776,16 @@ fn test_userdata_proxy() -> Result<()> {
fn test_any_userdata() -> Result<()> {
let lua = Lua::new();
lua.register_userdata_type::<StdString>(|reg| {
lua.register_userdata_type::<String>(|reg| {
reg.add_method("get", |_, this, ()| Ok(this.clone()));
reg.add_method_mut("concat", |_, this, s: String| {
reg.add_method_mut("concat", |_, this, s: LuaString| {
this.push_str(&s.to_string_lossy());
Ok(())
});
})?;
let ud = lua.create_any_userdata("hello".to_string())?;
assert_eq!(&*ud.borrow::<StdString>()?, "hello");
assert_eq!(&*ud.borrow::<String>()?, "hello");
lua.globals().set("ud", ud)?;
lua.load(
@@ -806,7 +805,7 @@ fn test_any_userdata() -> Result<()> {
fn test_any_userdata_wrap() -> Result<()> {
let lua = Lua::new();
lua.register_userdata_type::<StdString>(|reg| {
lua.register_userdata_type::<String>(|reg| {
reg.add_method("get", |_, this, ()| Ok(this.clone()));
})?;
@@ -858,7 +857,7 @@ fn test_userdata_object_like() -> Result<()> {
r => panic!("expected RuntimeError, got {r:?}"),
}
assert_eq!(ud.call::<String>(())?, "called");
assert_eq!(ud.call::<LuaString>(())?, "called");
ud.call_method::<()>("add", 2)?;
assert_eq!(ud.get::<u32>("n")?, 323);
@@ -1376,7 +1375,7 @@ fn test_userdata_namecall() -> Result<()> {
registry.add_method("method", |_, _, ()| Ok("method called"));
registry.add_field_method_get("field", |_, _| Ok("field value"));
registry.add_meta_method(MetaMethod::Index, |_, _, key: StdString| Ok(key));
registry.add_meta_method(MetaMethod::Index, |_, _, key: LuaString| Ok(key));
registry.enable_namecall();
}
@@ -1414,7 +1413,7 @@ fn test_userdata_get_path() -> Result<()> {
}
let ud = lua.create_userdata(MyUd)?;
assert_eq!(ud.get_path::<String>(".value")?, "userdata_value");
assert_eq!(ud.get_path::<LuaString>(".value")?, "userdata_value");
Ok(())
}
+3 -4
View File
@@ -1,7 +1,6 @@
use std::collections::HashMap;
use std::os::raw::c_void;
use std::ptr;
use std::string::String as StdString;
use mlua::{Error, LightUserData, Lua, MultiValue, Result, UserData, UserDataMethods, Value};
@@ -178,7 +177,7 @@ fn test_value_to_string() -> Result<()> {
assert!(thread.to_string()?.starts_with("thread:"));
assert_eq!(thread.type_name(), "thread");
lua.register_userdata_type::<StdString>(|reg| {
lua.register_userdata_type::<String>(|reg| {
reg.add_meta_method("__tostring", |_, this, ()| Ok(this.clone()));
})?;
let ud: Value = Value::UserData(lua.create_any_userdata(String::from("string userdata"))?);
@@ -213,9 +212,9 @@ fn test_value_to_string() -> Result<()> {
fn test_debug_format() -> Result<()> {
let lua = Lua::new();
lua.register_userdata_type::<HashMap<i32, StdString>>(|_| {})?;
lua.register_userdata_type::<HashMap<i32, String>>(|_| {})?;
let ud = lua
.create_any_userdata::<HashMap<i32, StdString>>(HashMap::new())
.create_any_userdata::<HashMap<i32, String>>(HashMap::new())
.map(Value::UserData)?;
assert!(format!("{ud:#?}").starts_with("HashMap<i32, String>:"));