From b4892c228c7a4448ec490ee7257c1a53a52eef0f Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Wed, 10 Jul 2024 22:46:02 +0100 Subject: [PATCH] Add rustfmt.toml --- benches/benchmark.rs | 15 +---- examples/async_http_server.rs | 3 +- examples/async_tcp_server.rs | 8 +-- examples/guided_tour.rs | 12 +--- examples/serialize.rs | 9 ++- mlua-sys/src/lib.rs | 5 +- mlua-sys/src/lua51/compat.rs | 31 ++-------- mlua-sys/src/lua51/lauxlib.rs | 7 +-- mlua-sys/src/lua51/lua.rs | 7 +-- mlua-sys/src/lua52/compat.rs | 21 +------ mlua-sys/src/lua52/lauxlib.rs | 25 ++------ mlua-sys/src/lua52/lua.rs | 22 +------ mlua-sys/src/lua53/compat.rs | 7 +-- mlua-sys/src/lua53/lauxlib.rs | 25 ++------ mlua-sys/src/lua53/lua.rs | 10 +--- mlua-sys/src/lua54/lauxlib.rs | 25 ++------ mlua-sys/src/lua54/lua.rs | 20 ++----- mlua-sys/src/luau/compat.rs | 42 +++---------- mlua-sys/src/luau/lauxlib.rs | 4 +- mlua-sys/src/luau/lua.rs | 36 ++---------- mlua-sys/src/macros.rs | 3 +- mlua_derive/src/from_lua.rs | 4 +- mlua_derive/src/token.rs | 17 ++---- rustfmt.toml | 4 ++ src/chunk.rs | 15 ++--- src/conversion.rs | 53 ++++++++--------- src/error.rs | 3 +- src/function.rs | 28 ++++----- src/hook.rs | 23 ++------ src/lib.rs | 27 ++++----- src/luau/mod.rs | 5 +- src/luau/package.rs | 9 ++- src/macros.rs | 3 +- src/multi.rs | 10 +--- src/prelude.rs | 25 ++++---- src/serde/de.rs | 25 ++------ src/serde/mod.rs | 6 +- src/serde/ser.rs | 18 ++---- src/state.rs | 107 ++++++++++++++++------------------ src/state/raw.rs | 78 ++++++------------------- src/state/util.rs | 10 +--- src/stdlib.rs | 7 +-- src/table.rs | 10 ++-- src/thread.rs | 5 +- src/types.rs | 3 +- src/types/app_data.rs | 8 +-- src/userdata.rs | 44 ++++++-------- src/userdata/cell.rs | 7 +-- src/userdata/ext.rs | 6 +- src/userdata/registry.rs | 15 ++--- src/util/mod.rs | 51 +++++----------- src/util/short_names.rs | 20 ++----- src/value.rs | 23 +++----- tests/async.rs | 40 +++++-------- tests/chunk.rs | 3 +- tests/conversion.rs | 8 +-- tests/error.rs | 14 ++--- tests/function.rs | 8 +-- tests/hooks.rs | 36 ++++-------- tests/luau.rs | 13 ++--- tests/memory.rs | 7 +-- tests/serde.rs | 14 ++--- tests/static.rs | 19 +++--- tests/string.rs | 14 +---- tests/table.rs | 35 +++-------- tests/tests.rs | 101 ++++++++------------------------ tests/userdata.rs | 72 +++++++---------------- tests/value.rs | 17 ++---- 68 files changed, 423 insertions(+), 984 deletions(-) create mode 100644 rustfmt.toml diff --git a/benches/benchmark.rs b/benches/benchmark.rs index b0a0fbb4..da67f1d5 100644 --- a/benches/benchmark.rs +++ b/benches/benchmark.rs @@ -183,9 +183,7 @@ fn function_call_concat(c: &mut Criterion) { let lua = Lua::new(); let concat = lua - .create_function(|_, (a, b): (LuaString, LuaString)| { - Ok(format!("{}{}", a.to_str()?, b.to_str()?)) - }) + .create_function(|_, (a, b): (LuaString, LuaString)| Ok(format!("{}{}", a.to_str()?, b.to_str()?))) .unwrap(); let i = AtomicUsize::new(0); @@ -383,17 +381,10 @@ fn userdata_async_call_method(c: &mut Criterion) { b.to_async(rt).iter_batched( || { collect_gc_twice(&lua); - ( - method.clone(), - ud.clone(), - i.fetch_add(1, Ordering::Relaxed), - ) + (method.clone(), ud.clone(), i.fetch_add(1, Ordering::Relaxed)) }, |(method, ud, i)| async move { - assert_eq!( - method.call_async::<_, usize>((ud, i)).await.unwrap(), - 123 + i - ); + assert_eq!(method.call_async::<_, usize>((ud, i)).await.unwrap(), 123 + i); }, BatchSize::SmallInput, ); diff --git a/examples/async_http_server.rs b/examples/async_http_server.rs index 7da84905..030006fb 100644 --- a/examples/async_http_server.rs +++ b/examples/async_http_server.rs @@ -4,7 +4,8 @@ use std::net::SocketAddr; use std::rc::Rc; use futures::future::LocalBoxFuture; -use http_body_util::{combinators::BoxBody, BodyExt as _, Empty, Full}; +use http_body_util::combinators::BoxBody; +use http_body_util::{BodyExt as _, Empty, Full}; use hyper::body::{Bytes, Incoming}; use hyper::{Request, Response}; use hyper_util::rt::TokioIo; diff --git a/examples/async_tcp_server.rs b/examples/async_tcp_server.rs index edc41493..a6b65f7c 100644 --- a/examples/async_tcp_server.rs +++ b/examples/async_tcp_server.rs @@ -12,9 +12,7 @@ struct LuaTcpStream(TcpStream); impl UserData for LuaTcpStream { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { - methods.add_method("peer_addr", |_, this, ()| { - Ok(this.0.peer_addr()?.to_string()) - }); + methods.add_method("peer_addr", |_, this, ()| Ok(this.0.peer_addr()?.to_string())); methods.add_async_method_mut("read", |lua, this, size| async move { let mut buf = vec![0; size]; @@ -53,9 +51,7 @@ async fn run_server(lua: Lua, handler: RegistryKey) -> io::Result<()> { let lua = lua.clone(); let handler = handler.clone(); task::spawn_local(async move { - let handler: Function = lua - .registry_value(&handler) - .expect("cannot get Lua handler"); + let handler: Function = lua.registry_value(&handler).expect("cannot get Lua handler"); let stream = LuaTcpStream(stream); if let Err(err) = handler.call_async::<_, ()>(stream).await { diff --git a/examples/guided_tour.rs b/examples/guided_tour.rs index 60ba1596..2a84d34a 100644 --- a/examples/guided_tour.rs +++ b/examples/guided_tour.rs @@ -1,9 +1,7 @@ use std::f32; use std::iter::FromIterator; -use mlua::{ - chunk, FromLua, Function, Lua, MetaMethod, Result, UserData, UserDataMethods, Value, Variadic, -}; +use mlua::{chunk, FromLua, Function, Lua, MetaMethod, Result, UserData, UserDataMethods, Value, Variadic}; fn main() -> Result<()> { // You can create a new Lua state with `Lua::new()`. This loads the default Lua std library @@ -179,13 +177,7 @@ fn main() -> Result<()> { let vec2_constructor = lua.create_function(|_, (x, y): (f32, f32)| Ok(Vec2(x, y)))?; globals.set("vec2", vec2_constructor)?; - assert!( - (lua.load("(vec2(1, 2) + vec2(2, 2)):magnitude()") - .eval::()? - - 5.0) - .abs() - < f32::EPSILON - ); + assert!((lua.load("(vec2(1, 2) + vec2(2, 2)):magnitude()").eval::()? - 5.0).abs() < f32::EPSILON); // Normally, Rust types passed to `Lua` must be `'static`, because there is no way to be // sure of their lifetime inside the Lua state. There is, however, a limited way to lift this diff --git a/examples/serialize.rs b/examples/serialize.rs index 7c9ae69e..fff968c4 100644 --- a/examples/serialize.rs +++ b/examples/serialize.rs @@ -28,9 +28,14 @@ fn main() -> Result<()> { let globals = lua.globals(); // Create Car struct from a Lua table - let car: Car = lua.from_value(lua.load(r#" + let car: Car = lua.from_value( + lua.load( + r#" {active = true, model = "Volkswagen Golf", transmission = "Automatic", engine = {v = 1499, kw = 90}} - "#).eval()?)?; + "#, + ) + .eval()?, + )?; // Set it as (serializable) userdata globals.set("null", lua.null())?; diff --git a/mlua-sys/src/lib.rs b/mlua-sys/src/lib.rs index 0e73ea73..629dfd88 100644 --- a/mlua-sys/src/lib.rs +++ b/mlua-sys/src/lib.rs @@ -54,10 +54,7 @@ pub const LUA_TRACEBACK_STACK: c_int = 11; target_arch = "sparc", target_arch = "wasm32", target_arch = "hexagon", - all( - target_arch = "riscv32", - not(any(target_os = "espidf", target_os = "zkvm")) - ), + all(target_arch = "riscv32", not(any(target_os = "espidf", target_os = "zkvm"))), all(target_arch = "xtensa", not(target_os = "espidf")), ))] #[doc(hidden)] diff --git a/mlua-sys/src/lua51/compat.rs b/mlua-sys/src/lua51/compat.rs index 890ba3be..942bb4da 100644 --- a/mlua-sys/src/lua51/compat.rs +++ b/mlua-sys/src/lua51/compat.rs @@ -2,9 +2,8 @@ //! //! Based on github.com/keplerproject/lua-compat-5.3 -use std::mem; use std::os::raw::{c_char, c_int, c_void}; -use std::ptr; +use std::{mem, ptr}; use super::lauxlib::*; use super::lua::*; @@ -328,12 +327,7 @@ pub unsafe fn lua_setuservalue(L: *mut lua_State, idx: c_int) { } #[inline(always)] -pub unsafe fn lua_dump( - L: *mut lua_State, - writer: lua_Writer, - data: *mut c_void, - _strip: c_int, -) -> c_int { +pub unsafe fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, _strip: c_int) -> c_int { lua_dump_(L, writer, data) } @@ -365,12 +359,7 @@ pub unsafe fn lua_pushglobaltable(L: *mut lua_State) { } #[inline(always)] -pub unsafe fn lua_resume( - L: *mut lua_State, - _from: *mut lua_State, - narg: c_int, - nres: *mut c_int, -) -> c_int { +pub unsafe fn lua_resume(L: *mut lua_State, _from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int { let ret = lua_resume_(L, narg); if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) { *nres = lua_gettop(L); @@ -446,12 +435,7 @@ pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer { res } -pub unsafe fn luaL_traceback( - L: *mut lua_State, - L1: *mut lua_State, - msg: *const c_char, - mut level: c_int, -) { +pub unsafe fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, mut level: c_int) { let mut ar: lua_Debug = mem::zeroed(); let top = lua_gettop(L); let numlevels = compat53_countlevels(L1); @@ -543,12 +527,7 @@ pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_ch 0 } -pub unsafe fn luaL_requiref( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, -) { +pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) { luaL_checkstack(L, 3, cstr!("not enough stack slots available")); luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED")); if lua_getfield(L, -1, modname) == LUA_TNIL { diff --git a/mlua-sys/src/lua51/lauxlib.rs b/mlua-sys/src/lua51/lauxlib.rs index 1565d3f1..54238858 100644 --- a/mlua-sys/src/lua51/lauxlib.rs +++ b/mlua-sys/src/lua51/lauxlib.rs @@ -63,12 +63,7 @@ extern "C-unwind" { pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int); pub fn luaL_loadfile(L: *mut lua_State, filename: *const c_char) -> c_int; - pub fn luaL_loadbuffer( - L: *mut lua_State, - buff: *const c_char, - sz: usize, - name: *const c_char, - ) -> c_int; + pub fn luaL_loadbuffer(L: *mut lua_State, buff: *const c_char, sz: usize, name: *const c_char) -> c_int; pub fn luaL_loadstring(L: *mut lua_State, s: *const c_char) -> c_int; pub fn luaL_newstate() -> *mut lua_State; diff --git a/mlua-sys/src/lua51/lua.rs b/mlua-sys/src/lua51/lua.rs index 7103a72b..f222b383 100644 --- a/mlua-sys/src/lua51/lua.rs +++ b/mlua-sys/src/lua51/lua.rs @@ -379,12 +379,7 @@ extern "C-unwind" { pub fn lua_getupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char; pub fn lua_setupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char; - pub fn lua_sethook( - L: *mut lua_State, - func: Option, - mask: c_int, - count: c_int, - ) -> c_int; + pub fn lua_sethook(L: *mut lua_State, func: Option, mask: c_int, count: c_int) -> c_int; pub fn lua_gethook(L: *mut lua_State) -> Option; pub fn lua_gethookmask(L: *mut lua_State) -> c_int; pub fn lua_gethookcount(L: *mut lua_State) -> c_int; diff --git a/mlua-sys/src/lua52/compat.rs b/mlua-sys/src/lua52/compat.rs index 49dcc7bc..32f321dd 100644 --- a/mlua-sys/src/lua52/compat.rs +++ b/mlua-sys/src/lua52/compat.rs @@ -157,22 +157,12 @@ pub unsafe fn lua_rawseti(L: *mut lua_State, idx: c_int, n: lua_Integer) { } #[inline(always)] -pub unsafe fn lua_dump( - L: *mut lua_State, - writer: lua_Writer, - data: *mut c_void, - _strip: c_int, -) -> c_int { +pub unsafe fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, _strip: c_int) -> c_int { lua_dump_(L, writer, data) } #[inline(always)] -pub unsafe fn lua_resume( - L: *mut lua_State, - from: *mut lua_State, - narg: c_int, - nres: *mut c_int, -) -> c_int { +pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int { let ret = lua_resume_(L, from, narg); if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) { *nres = lua_gettop(L); @@ -240,12 +230,7 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, mut idx: c_int, len: *mut usize) lua_tolstring(L, -1, len) } -pub unsafe fn luaL_requiref( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, -) { +pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) { luaL_checkstack(L, 3, cstr!("not enough stack slots available")); luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED")); if lua_getfield(L, -1, modname) == LUA_TNIL { diff --git a/mlua-sys/src/lua52/lauxlib.rs b/mlua-sys/src/lua52/lauxlib.rs index 570023dc..d5cdf664 100644 --- a/mlua-sys/src/lua52/lauxlib.rs +++ b/mlua-sys/src/lua52/lauxlib.rs @@ -25,12 +25,8 @@ extern "C-unwind" { pub fn luaL_tolstring_(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char; pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int; pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char; - pub fn luaL_optlstring( - L: *mut lua_State, - arg: c_int, - def: *const c_char, - l: *mut usize, - ) -> *const c_char; + pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize) + -> *const c_char; pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number; pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number; pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer; @@ -71,8 +67,7 @@ extern "C-unwind" { pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int; pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int); - pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) - -> c_int; + pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int; } #[inline(always)] @@ -109,12 +104,7 @@ extern "C-unwind" { pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int); #[link_name = "luaL_requiref"] - pub fn luaL_requiref_( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, - ); + pub fn luaL_requiref_(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int); } // @@ -173,12 +163,7 @@ pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) { // luaL_opt would be implemented here but it is undocumented, so it's omitted #[inline(always)] -pub unsafe fn luaL_loadbuffer( - L: *mut lua_State, - s: *const c_char, - sz: usize, - n: *const c_char, -) -> c_int { +pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int { luaL_loadbufferx(L, s, sz, n, ptr::null()) } diff --git a/mlua-sys/src/lua52/lua.rs b/mlua-sys/src/lua52/lua.rs index c52bc9f2..6714611d 100644 --- a/mlua-sys/src/lua52/lua.rs +++ b/mlua-sys/src/lua52/lua.rs @@ -222,13 +222,7 @@ extern "C-unwind" { // // 'load' and 'call' functions (load and run Lua code) // - pub fn lua_callk( - L: *mut lua_State, - nargs: c_int, - nresults: c_int, - ctx: c_int, - k: Option, - ); + pub fn lua_callk(L: *mut lua_State, nargs: c_int, nresults: c_int, ctx: c_int, k: Option); pub fn lua_pcallk( L: *mut lua_State, nargs: c_int, @@ -266,12 +260,7 @@ extern "C-unwind" { // // Coroutine functions // - pub fn lua_yieldk( - L: *mut lua_State, - nresults: c_int, - ctx: c_int, - k: Option, - ) -> c_int; + pub fn lua_yieldk(L: *mut lua_State, nresults: c_int, ctx: c_int, k: Option) -> c_int; #[link_name = "lua_resume"] pub fn lua_resume_(L: *mut lua_State, from: *mut lua_State, narg: c_int) -> c_int; pub fn lua_status(L: *mut lua_State) -> c_int; @@ -471,12 +460,7 @@ extern "C-unwind" { pub fn lua_upvalueid(L: *mut lua_State, fidx: c_int, n: c_int) -> *mut c_void; pub fn lua_upvaluejoin(L: *mut lua_State, fidx1: c_int, n1: c_int, fidx2: c_int, n2: c_int); - pub fn lua_sethook( - L: *mut lua_State, - func: Option, - mask: c_int, - count: c_int, - ) -> c_int; + pub fn lua_sethook(L: *mut lua_State, func: Option, mask: c_int, count: c_int) -> c_int; pub fn lua_gethook(L: *mut lua_State) -> Option; pub fn lua_gethookmask(L: *mut lua_State) -> c_int; pub fn lua_gethookcount(L: *mut lua_State) -> c_int; diff --git a/mlua-sys/src/lua53/compat.rs b/mlua-sys/src/lua53/compat.rs index 71d8b5e2..5ea404f1 100644 --- a/mlua-sys/src/lua53/compat.rs +++ b/mlua-sys/src/lua53/compat.rs @@ -5,12 +5,7 @@ use std::os::raw::c_int; use super::lua::*; #[inline(always)] -pub unsafe fn lua_resume( - L: *mut lua_State, - from: *mut lua_State, - narg: c_int, - nres: *mut c_int, -) -> c_int { +pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int { let ret = lua_resume_(L, from, narg); if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) { *nres = lua_gettop(L); diff --git a/mlua-sys/src/lua53/lauxlib.rs b/mlua-sys/src/lua53/lauxlib.rs index 258ab301..7c851ac1 100644 --- a/mlua-sys/src/lua53/lauxlib.rs +++ b/mlua-sys/src/lua53/lauxlib.rs @@ -30,12 +30,8 @@ extern "C-unwind" { pub fn luaL_tolstring_(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char; pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int; pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char; - pub fn luaL_optlstring( - L: *mut lua_State, - arg: c_int, - def: *const c_char, - l: *mut usize, - ) -> *const c_char; + pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize) + -> *const c_char; pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number; pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number; pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer; @@ -73,8 +69,7 @@ extern "C-unwind" { pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int; pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int); - pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) - -> c_int; + pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int; } #[inline(always)] @@ -110,12 +105,7 @@ extern "C-unwind" { pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int); - pub fn luaL_requiref( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, - ); + pub fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int); } // @@ -179,12 +169,7 @@ pub unsafe fn luaL_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> // luaL_opt would be implemented here but it is undocumented, so it's omitted #[inline(always)] -pub unsafe fn luaL_loadbuffer( - L: *mut lua_State, - s: *const c_char, - sz: usize, - n: *const c_char, -) -> c_int { +pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int { luaL_loadbufferx(L, s, sz, n, ptr::null()) } diff --git a/mlua-sys/src/lua53/lua.rs b/mlua-sys/src/lua53/lua.rs index 24dbba20..47010f5d 100644 --- a/mlua-sys/src/lua53/lua.rs +++ b/mlua-sys/src/lua53/lua.rs @@ -1,9 +1,8 @@ //! Contains definitions from `lua.h`. use std::marker::{PhantomData, PhantomPinned}; -use std::mem; use std::os::raw::{c_char, c_double, c_int, c_uchar, c_void}; -use std::ptr; +use std::{mem, ptr}; // Mark for precompiled code (`Lua`) pub const LUA_SIGNATURE: &[u8] = b"\x1bLua"; @@ -251,12 +250,7 @@ extern "C-unwind" { mode: *const c_char, ) -> c_int; - pub fn lua_dump( - L: *mut lua_State, - writer: lua_Writer, - data: *mut c_void, - strip: c_int, - ) -> c_int; + pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, strip: c_int) -> c_int; } #[inline(always)] diff --git a/mlua-sys/src/lua54/lauxlib.rs b/mlua-sys/src/lua54/lauxlib.rs index 5be2ba6b..b4873baa 100644 --- a/mlua-sys/src/lua54/lauxlib.rs +++ b/mlua-sys/src/lua54/lauxlib.rs @@ -29,12 +29,8 @@ extern "C-unwind" { pub fn luaL_tolstring(L: *mut lua_State, idx: c_int, len: *mut usize) -> *const c_char; pub fn luaL_argerror(L: *mut lua_State, arg: c_int, extramsg: *const c_char) -> c_int; pub fn luaL_checklstring(L: *mut lua_State, arg: c_int, l: *mut usize) -> *const c_char; - pub fn luaL_optlstring( - L: *mut lua_State, - arg: c_int, - def: *const c_char, - l: *mut usize, - ) -> *const c_char; + pub fn luaL_optlstring(L: *mut lua_State, arg: c_int, def: *const c_char, l: *mut usize) + -> *const c_char; pub fn luaL_checknumber(L: *mut lua_State, arg: c_int) -> lua_Number; pub fn luaL_optnumber(L: *mut lua_State, arg: c_int, def: lua_Number) -> lua_Number; pub fn luaL_checkinteger(L: *mut lua_State, arg: c_int) -> lua_Integer; @@ -72,8 +68,7 @@ extern "C-unwind" { pub fn luaL_ref(L: *mut lua_State, t: c_int) -> c_int; pub fn luaL_unref(L: *mut lua_State, t: c_int, r#ref: c_int); - pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) - -> c_int; + pub fn luaL_loadfilex(L: *mut lua_State, filename: *const c_char, mode: *const c_char) -> c_int; } #[inline(always)] @@ -111,12 +106,7 @@ extern "C-unwind" { pub fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, level: c_int); - pub fn luaL_requiref( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, - ); + pub fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int); } // @@ -175,12 +165,7 @@ pub unsafe fn luaL_getmetatable(L: *mut lua_State, n: *const c_char) { // luaL_opt would be implemented here but it is undocumented, so it's omitted #[inline(always)] -pub unsafe fn luaL_loadbuffer( - L: *mut lua_State, - s: *const c_char, - sz: usize, - n: *const c_char, -) -> c_int { +pub unsafe fn luaL_loadbuffer(L: *mut lua_State, s: *const c_char, sz: usize, n: *const c_char) -> c_int { luaL_loadbufferx(L, s, sz, n, ptr::null()) } diff --git a/mlua-sys/src/lua54/lua.rs b/mlua-sys/src/lua54/lua.rs index f628e69b..796bec7f 100644 --- a/mlua-sys/src/lua54/lua.rs +++ b/mlua-sys/src/lua54/lua.rs @@ -1,9 +1,8 @@ //! Contains definitions from `lua.h`. use std::marker::{PhantomData, PhantomPinned}; -use std::mem; use std::os::raw::{c_char, c_double, c_int, c_uchar, c_ushort, c_void}; -use std::ptr; +use std::{mem, ptr}; // Mark for precompiled code (`Lua`) pub const LUA_SIGNATURE: &[u8] = b"\x1bLua"; @@ -101,8 +100,7 @@ pub type lua_Alloc = unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void; /// Type for warning functions -pub type lua_WarnFunction = - unsafe extern "C-unwind" fn(ud: *mut c_void, msg: *const c_char, tocont: c_int); +pub type lua_WarnFunction = unsafe extern "C-unwind" fn(ud: *mut c_void, msg: *const c_char, tocont: c_int); #[cfg_attr(all(windows, raw_dylib), link(name = "lua54", kind = "raw-dylib"))] extern "C-unwind" { @@ -266,12 +264,7 @@ extern "C-unwind" { mode: *const c_char, ) -> c_int; - pub fn lua_dump( - L: *mut lua_State, - writer: lua_Writer, - data: *mut c_void, - strip: c_int, - ) -> c_int; + pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut c_void, strip: c_int) -> c_int; } #[inline(always)] @@ -295,12 +288,7 @@ extern "C-unwind" { ctx: lua_KContext, k: Option, ) -> c_int; - pub fn lua_resume( - L: *mut lua_State, - from: *mut lua_State, - narg: c_int, - nres: *mut c_int, - ) -> c_int; + pub fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int; pub fn lua_status(L: *mut lua_State) -> c_int; pub fn lua_isyieldable(L: *mut lua_State) -> c_int; } diff --git a/mlua-sys/src/luau/compat.rs b/mlua-sys/src/luau/compat.rs index 98fa9c90..47ec5b6d 100644 --- a/mlua-sys/src/luau/compat.rs +++ b/mlua-sys/src/luau/compat.rs @@ -3,9 +3,8 @@ //! Based on github.com/keplerproject/lua-compat-5.3 use std::ffi::CStr; -use std::mem; use std::os::raw::{c_char, c_int, c_void}; -use std::ptr; +use std::{mem, ptr}; use super::lauxlib::*; use super::lua::*; @@ -53,11 +52,7 @@ unsafe fn compat53_findfield(L: *mut lua_State, objidx: c_int, level: c_int) -> 0 // not found } -unsafe fn compat53_pushglobalfuncname( - L: *mut lua_State, - level: c_int, - ar: *mut lua_Debug, -) -> c_int { +unsafe fn compat53_pushglobalfuncname(L: *mut lua_State, level: c_int, ar: *mut lua_Debug) -> c_int { let top = lua_gettop(L); // push function lua_getinfo(L, level, cstr!("f"), ar); @@ -281,12 +276,7 @@ pub unsafe fn lua_pushglobaltable(L: *mut lua_State) { } #[inline(always)] -pub unsafe fn lua_resume( - L: *mut lua_State, - from: *mut lua_State, - narg: c_int, - nres: *mut c_int, -) -> c_int { +pub unsafe fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int, nres: *mut c_int) -> c_int { let ret = lua_resume_(L, from, narg); if (ret == LUA_OK || ret == LUA_YIELD) && !(nres.is_null()) { *nres = lua_gettop(L); @@ -345,18 +335,10 @@ pub unsafe fn luaL_loadbufferx( if !mode.is_null() { let modeb = CStr::from_ptr(mode).to_bytes(); if !chunk_is_text && !modeb.contains(&b'b') { - lua_pushfstring( - L, - cstr!("attempt to load a binary chunk (mode is '%s')"), - mode, - ); + lua_pushfstring(L, cstr!("attempt to load a binary chunk (mode is '%s')"), mode); return LUA_ERRSYNTAX; } else if chunk_is_text && !modeb.contains(&b't') { - lua_pushfstring( - L, - cstr!("attempt to load a text chunk (mode is '%s')"), - mode, - ); + lua_pushfstring(L, cstr!("attempt to load a text chunk (mode is '%s')"), mode); return LUA_ERRSYNTAX; } } @@ -397,12 +379,7 @@ pub unsafe fn luaL_len(L: *mut lua_State, idx: c_int) -> lua_Integer { res } -pub unsafe fn luaL_traceback( - L: *mut lua_State, - L1: *mut lua_State, - msg: *const c_char, - mut level: c_int, -) { +pub unsafe fn luaL_traceback(L: *mut lua_State, L1: *mut lua_State, msg: *const c_char, mut level: c_int) { let mut ar: lua_Debug = mem::zeroed(); let top = lua_gettop(L); let numlevels = lua_stackdepth(L); @@ -494,12 +471,7 @@ pub unsafe fn luaL_getsubtable(L: *mut lua_State, idx: c_int, fname: *const c_ch 0 } -pub unsafe fn luaL_requiref( - L: *mut lua_State, - modname: *const c_char, - openf: lua_CFunction, - glb: c_int, -) { +pub unsafe fn luaL_requiref(L: *mut lua_State, modname: *const c_char, openf: lua_CFunction, glb: c_int) { luaL_checkstack(L, 3, cstr!("not enough stack slots available")); luaL_getsubtable(L, LUA_REGISTRYINDEX, cstr!("_LOADED")); if lua_getfield(L, -1, modname) == LUA_TNIL { diff --git a/mlua-sys/src/luau/lauxlib.rs b/mlua-sys/src/luau/lauxlib.rs index 9f4384c0..284cd3f2 100644 --- a/mlua-sys/src/luau/lauxlib.rs +++ b/mlua-sys/src/luau/lauxlib.rs @@ -3,9 +3,7 @@ use std::os::raw::{c_char, c_float, c_int, c_void}; use std::ptr; -use super::lua::{ - self, lua_CFunction, lua_Integer, lua_Number, lua_State, lua_Unsigned, LUA_REGISTRYINDEX, -}; +use super::lua::{self, lua_CFunction, lua_Integer, lua_Number, lua_State, lua_Unsigned, LUA_REGISTRYINDEX}; #[repr(C)] pub struct luaL_Reg { diff --git a/mlua-sys/src/luau/lua.rs b/mlua-sys/src/luau/lua.rs index cc2e6012..540dee46 100644 --- a/mlua-sys/src/luau/lua.rs +++ b/mlua-sys/src/luau/lua.rs @@ -84,12 +84,8 @@ pub type lua_Udestructor = unsafe extern "C-unwind" fn(*mut c_void); pub type lua_Destructor = unsafe extern "C-unwind" fn(L: *mut lua_State, *mut c_void); /// Type for memory-allocation functions. -pub type lua_Alloc = unsafe extern "C-unwind" fn( - ud: *mut c_void, - ptr: *mut c_void, - osize: usize, - nsize: usize, -) -> *mut c_void; +pub type lua_Alloc = + unsafe extern "C-unwind" fn(ud: *mut c_void, ptr: *mut c_void, osize: usize, nsize: usize) -> *mut c_void; /// Returns Luau release version (eg. `0.xxx`). pub const fn luau_version() -> Option<&'static str> { @@ -426,12 +422,7 @@ pub unsafe fn lua_pushcclosure(L: *mut lua_State, f: lua_CFunction, nup: c_int) } #[inline(always)] -pub unsafe fn lua_pushcclosured( - L: *mut lua_State, - f: lua_CFunction, - debugname: *const c_char, - nup: c_int, -) { +pub unsafe fn lua_pushcclosured(L: *mut lua_State, f: lua_CFunction, debugname: *const c_char, nup: c_int) { lua_pushcclosurek(L, f, debugname, nup, None) } @@ -476,12 +467,7 @@ pub type lua_Coverage = unsafe extern "C-unwind" fn( extern "C-unwind" { pub fn lua_stackdepth(L: *mut lua_State) -> c_int; - pub fn lua_getinfo( - L: *mut lua_State, - level: c_int, - what: *const c_char, - ar: *mut lua_Debug, - ) -> c_int; + pub fn lua_getinfo(L: *mut lua_State, level: c_int, what: *const c_char, ar: *mut lua_Debug) -> c_int; pub fn lua_getargument(L: *mut lua_State, level: c_int, n: c_int) -> c_int; pub fn lua_getlocal(L: *mut lua_State, level: c_int, n: c_int) -> *const c_char; pub fn lua_setlocal(L: *mut lua_State, level: c_int, n: c_int) -> *const c_char; @@ -489,19 +475,9 @@ extern "C-unwind" { pub fn lua_setupvalue(L: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char; pub fn lua_singlestep(L: *mut lua_State, enabled: c_int); - pub fn lua_breakpoint( - L: *mut lua_State, - funcindex: c_int, - line: c_int, - enabled: c_int, - ) -> c_int; + pub fn lua_breakpoint(L: *mut lua_State, funcindex: c_int, line: c_int, enabled: c_int) -> c_int; - pub fn lua_getcoverage( - L: *mut lua_State, - funcindex: c_int, - context: *mut c_void, - callback: lua_Coverage, - ); + pub fn lua_getcoverage(L: *mut lua_State, funcindex: c_int, context: *mut c_void, callback: lua_Coverage); pub fn lua_debugtrace(L: *mut lua_State) -> *const c_char; } diff --git a/mlua-sys/src/macros.rs b/mlua-sys/src/macros.rs index df79a79f..263b4e76 100644 --- a/mlua-sys/src/macros.rs +++ b/mlua-sys/src/macros.rs @@ -1,7 +1,6 @@ #[allow(unused_macros)] macro_rules! cstr { ($s:expr) => { - concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] - as *const ::std::os::raw::c_char + concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] as *const ::std::os::raw::c_char }; } diff --git a/mlua_derive/src/from_lua.rs b/mlua_derive/src/from_lua.rs index 8d0b6836..dfbb6746 100644 --- a/mlua_derive/src/from_lua.rs +++ b/mlua_derive/src/from_lua.rs @@ -3,9 +3,7 @@ use quote::quote; use syn::{parse_macro_input, DeriveInput}; pub fn from_lua(input: TokenStream) -> TokenStream { - let DeriveInput { - ident, generics, .. - } = parse_macro_input!(input as DeriveInput); + let DeriveInput { ident, generics, .. } = parse_macro_input!(input as DeriveInput); let ident_str = ident.to_string(); let (impl_generics, ty_generics, _) = generics.split_for_impl(); diff --git a/mlua_derive/src/token.rs b/mlua_derive/src/token.rs index 9ef10d7a..19f3f05f 100644 --- a/mlua_derive/src/token.rs +++ b/mlua_derive/src/token.rs @@ -1,8 +1,6 @@ -use std::{ - cmp::{Eq, PartialEq}, - fmt::{self, Display, Formatter}, - vec::IntoIter, -}; +use std::cmp::{Eq, PartialEq}; +use std::fmt::{self, Display, Formatter}; +use std::vec::IntoIter; use itertools::Itertools; use once_cell::sync::Lazy; @@ -47,10 +45,7 @@ fn span_pos(span: &Span) -> (Pos, Pos) { return fallback_span_pos(span); } - ( - Pos::new(start.line, start.column), - Pos::new(end.line, end.column), - ) + (Pos::new(start.line, start.column), Pos::new(end.line, end.column)) } fn parse_pos(span: &Span) -> Option<(usize, usize)> { @@ -79,9 +74,7 @@ fn parse_pos(span: &Span) -> Option<(usize, usize)> { fn fallback_span_pos(span: &Span) -> (Pos, Pos) { let (start, end) = match parse_pos(span) { Some(v) => v, - None => proc_macro_error::abort_call_site!( - "Cannot retrieve span information; please use nightly" - ), + None => proc_macro_error::abort_call_site!("Cannot retrieve span information; please use nightly"), }; (Pos::new(1, start), Pos::new(1, end)) } diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..ac702a58 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,4 @@ +imports_granularity = "Module" +max_width = 110 +comment_width = 100 +wrap_comments = true diff --git a/src/chunk.rs b/src/chunk.rs index a7d7812e..b1c74b3d 100644 --- a/src/chunk.rs +++ b/src/chunk.rs @@ -299,8 +299,8 @@ impl<'a> Chunk<'a> { /// Sets the environment of the loaded chunk to the given value. /// - /// In Lua >=5.2 main chunks always have exactly one upvalue, and this upvalue is used as the `_ENV` - /// variable inside the chunk. By default this value is set to the global environment. + /// In Lua >=5.2 main chunks always have exactly one upvalue, and this upvalue is used as the + /// `_ENV` variable inside the chunk. By default this value is set to the global environment. /// /// Calling this method changes the `_ENV` upvalue to the value provided, and variables inside /// the chunk will refer to the given environment rather than the global one. @@ -450,19 +450,12 @@ impl<'a> Chunk<'a> { if self.detect_mode() == ChunkMode::Text { #[cfg(feature = "luau")] { - let data = self - .compiler - .get_or_insert_with(Default::default) - .compile(source); + let data = self.compiler.get_or_insert_with(Default::default).compile(source); self.source = Ok(Cow::Owned(data)); self.mode = Some(ChunkMode::Binary); } #[cfg(not(feature = "luau"))] - if let Ok(func) = self - .lua - .lock() - .load_chunk(None, None, None, source.as_ref()) - { + if let Ok(func) = self.lua.lock().load_chunk(None, None, None, source.as_ref()) { let data = func.dump(false); self.source = Ok(Cow::Owned(data)); self.mode = Some(ChunkMode::Binary); diff --git a/src/conversion.rs b/src/conversion.rs index 2defef3c..72c9fbbc 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -389,13 +389,13 @@ impl FromLua for StdString { let mut size = 0; let data = ffi::lua_tolstring(state, idx, &mut size); let bytes = slice::from_raw_parts(data as *const u8, size); - return str::from_utf8(bytes).map(|s| s.to_owned()).map_err(|e| { - Error::FromLuaConversionError { + return str::from_utf8(bytes) + .map(|s| s.to_owned()) + .map_err(|e| Error::FromLuaConversionError { from: "string", to: "String", message: Some(e.to_string()), - } - }); + }); } // Fallback to default Self::from_lua(lua.stack_value(idx), lua.lua()) @@ -603,15 +603,16 @@ macro_rules! lua_convert_int { if let Some(i) = lua.coerce_integer(value.clone())? { cast(i) } else { - cast(lua.coerce_number(value)?.ok_or_else(|| { - Error::FromLuaConversionError { - from: ty, - to: stringify!($x), - message: Some( - "expected number or string coercible to number".to_string(), - ), - } - })?) + cast( + lua.coerce_number(value)? + .ok_or_else(|| Error::FromLuaConversionError { + from: ty, + to: stringify!($x), + message: Some( + "expected number or string coercible to number".to_string(), + ), + })?, + ) } } }) @@ -684,9 +685,7 @@ where { #[inline] fn into_lua(self, lua: &Lua) -> Result { - Ok(Value::Table( - lua.create_sequence_from(self.iter().cloned())?, - )) + Ok(Value::Table(lua.create_sequence_from(self.iter().cloned())?)) } } @@ -819,9 +818,9 @@ impl FromLua for BTreeMap { impl IntoLua for HashSet { #[inline] fn into_lua(self, lua: &Lua) -> Result { - Ok(Value::Table(lua.create_table_from( - self.into_iter().map(|val| (val, true)), - )?)) + Ok(Value::Table( + lua.create_table_from(self.into_iter().map(|val| (val, true)))?, + )) } } @@ -830,10 +829,7 @@ impl FromLua for HashSet fn from_lua(value: Value, _: &Lua) -> Result { match value { Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(), - Value::Table(table) => table - .pairs::() - .map(|res| res.map(|(k, _)| k)) - .collect(), + Value::Table(table) => table.pairs::().map(|res| res.map(|(k, _)| k)).collect(), _ => Err(Error::FromLuaConversionError { from: value.type_name(), to: "HashSet", @@ -846,9 +842,9 @@ impl FromLua for HashSet impl IntoLua for BTreeSet { #[inline] fn into_lua(self, lua: &Lua) -> Result { - Ok(Value::Table(lua.create_table_from( - self.into_iter().map(|val| (val, true)), - )?)) + Ok(Value::Table( + lua.create_table_from(self.into_iter().map(|val| (val, true)))?, + )) } } @@ -857,10 +853,7 @@ impl FromLua for BTreeSet { fn from_lua(value: Value, _: &Lua) -> Result { match value { Value::Table(table) if table.raw_len() > 0 => table.sequence_values().collect(), - Value::Table(table) => table - .pairs::() - .map(|res| res.map(|(k, _)| k)) - .collect(), + Value::Table(table) => table.pairs::().map(|res| res.map(|(k, _)| k)).collect(), _ => Err(Error::FromLuaConversionError { from: value.type_name(), to: "BTreeSet", diff --git a/src/error.rs b/src/error.rs index 8c563c28..b1635c49 100644 --- a/src/error.rs +++ b/src/error.rs @@ -324,7 +324,8 @@ impl StdError for Error { // An error type with a source error should either return that error via source or // include that source's error message in its own Display output, but never both. // https://blog.rust-lang.org/inside-rust/2021/07/01/What-the-error-handling-project-group-is-working-towards.html - // Given that we include source to fmt::Display implementation for `CallbackError`, this call returns nothing. + // Given that we include source to fmt::Display implementation for `CallbackError`, this call + // returns nothing. Error::CallbackError { .. } => None, Error::ExternalError(ref err) => err.source(), Error::WithContext { ref cause, .. } => match cause.as_ref() { diff --git a/src/function.rs b/src/function.rs index 3495236a..adbf9410 100644 --- a/src/function.rs +++ b/src/function.rs @@ -1,16 +1,13 @@ use std::cell::RefCell; -use std::mem; use std::os::raw::{c_int, c_void}; -use std::ptr; -use std::slice; +use std::{mem, ptr, slice}; use crate::error::{Error, Result}; use crate::state::Lua; use crate::table::Table; use crate::types::{Callback, MaybeSend, ValueRef}; use crate::util::{ - assert_stack, check_stack, linenumber_to_usize, pop_error, ptr_to_lossy_str, ptr_to_str, - StackGuard, + assert_stack, check_stack, linenumber_to_usize, pop_error, ptr_to_lossy_str, ptr_to_str, StackGuard, }; use crate::value::{FromLuaMulti, IntoLua, IntoLuaMulti, Value}; @@ -37,7 +34,8 @@ pub struct FunctionInfo { /// /// Always `None` for Luau. pub name_what: Option<&'static str>, - /// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is the main part of a chunk. + /// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is + /// the main part of a chunk. pub what: &'static str, /// Source of the chunk that created the function. pub source: Option, @@ -426,8 +424,8 @@ impl Function { /// Retrieves recorded coverage information about this Lua function including inner calls. /// - /// This function takes a callback as an argument and calls it providing [`CoverageInfo`] snapshot - /// per each executed inner function. + /// This function takes a callback as an argument and calls it providing [`CoverageInfo`] + /// snapshot per each executed inner function. /// /// Recording of coverage information is controlled by [`Compiler::set_coverage_level`] option. /// @@ -522,7 +520,8 @@ pub(crate) struct WrappedFunction(pub(crate) Callback<'static>); pub(crate) struct WrappedAsyncFunction(pub(crate) AsyncCallback<'static>); impl Function { - /// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`] trait. + /// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`] + /// trait. #[inline] pub fn wrap(func: F) -> impl IntoLua where @@ -546,15 +545,14 @@ impl Function { { let func = RefCell::new(func); WrappedFunction(Box::new(move |lua, nargs| unsafe { - let mut func = func - .try_borrow_mut() - .map_err(|_| Error::RecursiveMutCallback)?; + let mut func = func.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?; let args = A::from_stack_args(nargs, 1, None, lua)?; func(lua.lua(), args)?.push_into_stack_multi(lua) })) } - /// Wraps a Rust async function or closure, returning an opaque type that implements [`IntoLua`] trait. + /// Wraps a Rust async function or closure, returning an opaque type that implements [`IntoLua`] + /// trait. #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] pub fn wrap_async(func: F) -> impl IntoLua @@ -588,9 +586,7 @@ impl IntoLua for WrappedFunction { impl IntoLua for WrappedAsyncFunction { #[inline] fn into_lua(self, lua: &Lua) -> Result { - lua.lock() - .create_async_callback(self.0) - .map(Value::Function) + lua.lock().create_async_callback(self.0).map(Value::Function) } } diff --git a/src/hook.rs b/src/hook.rs index 37f4b1e8..0d327445 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -55,11 +55,7 @@ impl<'a> Debug<'a> { } } - pub(crate) fn new_owned( - guard: ReentrantMutexGuard<'a, RawLua>, - _level: c_int, - ar: lua_Debug, - ) -> Self { + pub(crate) fn new_owned(guard: ReentrantMutexGuard<'a, RawLua>, _level: c_int, ar: lua_Debug) -> Self { Debug { lua: EitherLua::Owned(guard), ar: ActivationRecord::Owned(UnsafeCell::new(ar)), @@ -259,7 +255,8 @@ pub struct DebugSource<'a> { pub line_defined: Option, /// The line number where the definition of the function ends (not set by Luau). pub last_line_defined: Option, - /// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is the main part of a chunk. + /// A string `Lua` if the function is a Lua function, `C` if it is a C function, `main` if it is + /// the main part of a chunk. pub what: &'static str, } @@ -267,20 +264,10 @@ pub struct DebugSource<'a> { pub struct DebugStack { pub num_ups: i32, /// Requires `feature = "lua54/lua53/lua52/luau"` - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] pub num_params: i32, /// Requires `feature = "lua54/lua53/lua52/luau"` - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] pub is_vararg: bool, } diff --git a/src/lib.rs b/src/lib.rs index ee8d51b6..5491ecc3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,9 +27,9 @@ //! //! # Serde support //! -//! The [`LuaSerdeExt`] trait implemented for [`Lua`] allows conversion from Rust types to Lua values -//! and vice versa using serde. Any user defined data type that implements [`serde::Serialize`] or -//! [`serde::Deserialize`] can be converted. +//! The [`LuaSerdeExt`] trait implemented for [`Lua`] allows conversion from Rust types to Lua +//! values and vice versa using serde. Any user defined data type that implements +//! [`serde::Serialize`] or [`serde::Deserialize`] can be converted. //! For convenience, additional functionality to handle `NULL` values and arrays is provided. //! //! The [`Value`] enum implements [`serde::Serialize`] trait to support serializing Lua values @@ -40,14 +40,14 @@ //! # Async/await support //! //! The [`create_async_function`] allows creating non-blocking functions that returns [`Future`]. -//! Lua code with async capabilities can be executed by [`call_async`] family of functions or polling -//! [`AsyncThread`] using any runtime (eg. Tokio). +//! Lua code with async capabilities can be executed by [`call_async`] family of functions or +//! polling [`AsyncThread`] using any runtime (eg. Tokio). //! //! Requires `feature = "async"`. //! //! # `Send` requirement -//! By default `mlua` is `!Send`. This can be changed by enabling `feature = "send"` that adds `Send` requirement -//! to [`Function`]s and [`UserData`]. +//! By default `mlua` is `!Send`. This can be changed by enabling `feature = "send"` that adds +//! `Send` requirement to [`Function`]s and [`UserData`]. //! //! [Lua programming language]: https://www.lua.org/ //! [`Lua`]: crate::Lua @@ -116,8 +116,8 @@ pub use crate::table::{Table, TableExt, TablePairs, TableSequence}; pub use crate::thread::{Thread, ThreadStatus}; pub use crate::types::{AppDataRef, AppDataRefMut, Integer, LightUserData, Number, RegistryKey}; pub use crate::userdata::{ - AnyUserData, AnyUserDataExt, MetaMethod, UserData, UserDataFields, UserDataMetatable, - UserDataMethods, UserDataRef, UserDataRefMut, UserDataRegistry, + AnyUserData, AnyUserDataExt, MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods, + UserDataRef, UserDataRefMut, UserDataRegistry, }; pub use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, MultiValue, Nil, Value}; @@ -137,9 +137,7 @@ pub use crate::thread::AsyncThread; #[cfg(feature = "serialize")] #[doc(inline)] -pub use crate::serde::{ - de::Options as DeserializeOptions, ser::Options as SerializeOptions, LuaSerdeExt, -}; +pub use crate::serde::{de::Options as DeserializeOptions, ser::Options as SerializeOptions, LuaSerdeExt}; #[cfg(feature = "serialize")] #[cfg_attr(docsrs, doc(cfg(feature = "serialize")))] @@ -190,8 +188,8 @@ extern crate mlua_derive; /// /// Other minor limitations: /// -/// - Certain escape codes in string literals don't work. -/// (Specifically: `\a`, `\b`, `\f`, `\v`, `\123` (octal escape codes), `\u`, and `\U`). +/// - Certain escape codes in string literals don't work. (Specifically: `\a`, `\b`, `\f`, `\v`, +/// `\123` (octal escape codes), `\u`, and `\U`). /// /// These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`. /// @@ -255,7 +253,6 @@ pub use mlua_derive::FromLua; /// ... /// } /// ``` -/// #[cfg(any(feature = "module", docsrs))] #[cfg_attr(docsrs, doc(cfg(feature = "module")))] pub use mlua_derive::lua_module; diff --git a/src/luau/mod.rs b/src/luau/mod.rs index 139860b8..75d1a767 100644 --- a/src/luau/mod.rs +++ b/src/luau/mod.rs @@ -10,10 +10,7 @@ impl Lua { pub(crate) unsafe fn configure_luau(&self) -> Result<()> { let globals = self.globals(); - globals.raw_set( - "collectgarbage", - self.create_c_function(lua_collectgarbage)?, - )?; + globals.raw_set("collectgarbage", self.create_c_function(lua_collectgarbage)?)?; globals.raw_set("vector", self.create_c_function(lua_vector)?)?; // Set `_VERSION` global to include version number diff --git a/src/luau/package.rs b/src/luau/package.rs index cf3fe0ab..23e78c81 100644 --- a/src/luau/package.rs +++ b/src/luau/package.rs @@ -225,14 +225,13 @@ fn dylib_loader(lua: &Lua, modname: StdString) -> Result { let search_cpath = package.get::<_, StdString>("cpath").unwrap_or_default(); let find_symbol = |lib: &Library| unsafe { - if let Ok(entry) = lib.get::(format!("luaopen_{modname}\0").as_bytes()) - { + if let Ok(entry) = lib.get::(format!("luaopen_{modname}\0").as_bytes()) { return lua.create_c_function(*entry).map(Value::Function); } // Try all in one mode - if let Ok(entry) = lib.get::( - format!("luaopen_{}\0", modname.replace('.', "_")).as_bytes(), - ) { + if let Ok(entry) = + lib.get::(format!("luaopen_{}\0", modname.replace('.', "_")).as_bytes()) + { return lua.create_c_function(*entry).map(Value::Function); } "cannot find module entrypoint".into_lua(lua) diff --git a/src/macros.rs b/src/macros.rs index b3c991ba..5c487efb 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -10,8 +10,7 @@ macro_rules! bug_msg { macro_rules! cstr { ($s:expr) => { - concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] - as *const ::std::os::raw::c_char + concat!($s, "\0") as *const str as *const [::std::os::raw::c_char] as *const ::std::os::raw::c_char }; } diff --git a/src/multi.rs b/src/multi.rs index 4f0c6632..443c2658 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -4,8 +4,7 @@ use std::os::raw::c_int; use std::result::Result as StdResult; use crate::error::Result; -use crate::state::Lua; -use crate::state::RawLua; +use crate::state::{Lua, RawLua}; use crate::util::check_stack; use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, MultiValue, Nil}; @@ -82,12 +81,7 @@ impl FromLuaMulti for T { } #[inline] - unsafe fn from_stack_args( - nargs: c_int, - i: usize, - to: Option<&str>, - lua: &RawLua, - ) -> Result { + unsafe fn from_stack_args(nargs: c_int, i: usize, to: Option<&str>, lua: &RawLua) -> Result { if nargs == 0 { return T::from_lua_arg(Nil, i, to, lua.lua()); } diff --git a/src/prelude.rs b/src/prelude.rs index c2929f79..b6168657 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -2,19 +2,17 @@ #[doc(no_inline)] pub use crate::{ - AnyUserData as LuaAnyUserData, AnyUserDataExt as LuaAnyUserDataExt, Chunk as LuaChunk, - Error as LuaError, ErrorContext as LuaErrorContext, 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, LuaOptions, MetaMethod as LuaMetaMethod, - MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber, RegistryKey as LuaRegistryKey, - Result as LuaResult, StdLib as LuaStdLib, String as LuaString, Table as LuaTable, - TableExt as LuaTableExt, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence, - Thread as LuaThread, ThreadStatus as LuaThreadStatus, UserData as LuaUserData, - UserDataFields as LuaUserDataFields, UserDataMetatable as LuaUserDataMetatable, + AnyUserData as LuaAnyUserData, AnyUserDataExt as LuaAnyUserDataExt, Chunk as LuaChunk, Error as LuaError, + ErrorContext as LuaErrorContext, 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, LuaOptions, + MetaMethod as LuaMetaMethod, MultiValue as LuaMultiValue, Nil as LuaNil, Number as LuaNumber, + RegistryKey as LuaRegistryKey, Result as LuaResult, StdLib as LuaStdLib, String as LuaString, + Table as LuaTable, TableExt as LuaTableExt, 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, - UserDataRefMut as LuaUserDataRefMut, UserDataRegistry as LuaUserDataRegistry, - Value as LuaValue, + UserDataRefMut as LuaUserDataRefMut, UserDataRegistry as LuaUserDataRegistry, Value as LuaValue, }; #[cfg(not(feature = "luau"))] @@ -32,6 +30,5 @@ pub use crate::AsyncThread as LuaAsyncThread; #[cfg(feature = "serialize")] #[doc(no_inline)] pub use crate::{ - DeserializeOptions as LuaDeserializeOptions, LuaSerdeExt, - SerializeOptions as LuaSerializeOptions, + DeserializeOptions as LuaDeserializeOptions, LuaSerdeExt, SerializeOptions as LuaSerializeOptions, }; diff --git a/src/serde/de.rs b/src/serde/de.rs index 542180f8..9c36c87e 100644 --- a/src/serde/de.rs +++ b/src/serde/de.rs @@ -108,11 +108,7 @@ impl Deserializer { } } - fn from_parts( - value: Value, - options: Options, - visited: Rc>>, - ) -> Self { + fn from_parts(value: Value, options: Options, visited: Rc>>) -> Self { Deserializer { value, options, @@ -267,10 +263,7 @@ impl<'de> serde::Deserializer<'de> for Deserializer { if deserializer.seq.count() == 0 { Ok(seq) } else { - Err(de::Error::invalid_length( - len, - &"fewer elements in the table", - )) + Err(de::Error::invalid_length(len, &"fewer elements in the table")) } } Value::UserData(ud) if ud.is_serializable() => { @@ -292,12 +285,7 @@ impl<'de> serde::Deserializer<'de> for Deserializer { } #[inline] - fn deserialize_tuple_struct( - self, - _name: &'static str, - _len: usize, - visitor: V, - ) -> Result + fn deserialize_tuple_struct(self, _name: &'static str, _len: usize, visitor: V) -> Result where V: de::Visitor<'de>, { @@ -454,8 +442,7 @@ impl<'de> de::SeqAccess<'de> for VecDeserializer { Some(&n) => { self.next += 1; let visited = Rc::clone(&self.visited); - let deserializer = - Deserializer::from_parts(Value::Number(n as _), self.options, visited); + let deserializer = Deserializer::from_parts(Value::Number(n as _), self.options, visited); seed.deserialize(deserializer).map(Some) } None => Ok(None), @@ -616,9 +603,7 @@ impl<'de> de::VariantAccess<'de> for VariantDeserializer { T: de::DeserializeSeed<'de>, { match self.value { - Some(value) => { - seed.deserialize(Deserializer::from_parts(value, self.options, self.visited)) - } + Some(value) => seed.deserialize(Deserializer::from_parts(value, self.options, self.visited)), None => Err(de::Error::invalid_type( de::Unexpected::UnitVariant, &"newtype variant", diff --git a/src/serde/mod.rs b/src/serde/mod.rs index dee3a81e..599960ed 100644 --- a/src/serde/mod.rs +++ b/src/serde/mod.rs @@ -2,7 +2,8 @@ use std::os::raw::c_void; -use serde::{de::DeserializeOwned, ser::Serialize}; +use serde::de::DeserializeOwned; +use serde::ser::Serialize; use crate::error::Result; use crate::private::Sealed; @@ -189,8 +190,7 @@ pub trait LuaSerdeExt: Sealed { /// } /// ``` #[allow(clippy::wrong_self_convention)] - fn from_value_with(&self, value: Value, options: de::Options) - -> Result; + fn from_value_with(&self, value: Value, options: de::Options) -> Result; } impl LuaSerdeExt for Lua { diff --git a/src/serde/ser.rs b/src/serde/ser.rs index 315308cf..0267db78 100644 --- a/src/serde/ser.rs +++ b/src/serde/ser.rs @@ -96,8 +96,8 @@ impl Options { /// Sets [`detect_serde_json_arbitrary_precision`] option. /// - /// This option is used to serialize `serde_json::Number` with arbitrary precision to a Lua number. - /// Otherwise it will be serialized as an object (what serde does). + /// This option is used to serialize `serde_json::Number` with arbitrary precision to a Lua + /// number. Otherwise it will be serialized as an object (what serde does). /// /// This option is disabled by default. /// @@ -264,11 +264,7 @@ impl<'a> ser::Serializer for Serializer<'a> { } #[inline] - fn serialize_tuple_struct( - self, - name: &'static str, - len: usize, - ) -> Result { + fn serialize_tuple_struct(self, name: &'static str, len: usize) -> Result { #[cfg(feature = "luau")] if name == "Vector" && len == crate::types::Vector::SIZE { return Ok(SerializeSeq::new_vector(self.lua, self.options)); @@ -454,8 +450,7 @@ impl ser::SerializeTupleVariant for SerializeTupleVariant<'_> { where T: Serialize + ?Sized, { - self.table - .raw_push(self.lua.to_value_with(value, self.options)?) + self.table.raw_push(self.lua.to_value_with(value, self.options)?) } fn end(self) -> Result { @@ -489,10 +484,7 @@ impl ser::SerializeMap for SerializeMap<'_> { where T: Serialize + ?Sized, { - let key = mlua_expect!( - self.key.take(), - "serialize_value called before serialize_key" - ); + let key = mlua_expect!(self.key.take(), "serialize_value called before serialize_key"); let value = self.lua.to_value_with(value, self.options)?; self.table.raw_set(key, value) } diff --git a/src/state.rs b/src/state.rs index 2cba49f8..8eae6639 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,14 +1,12 @@ use std::any::TypeId; use std::cell::RefCell; // use std::collections::VecDeque; -use std::fmt; use std::marker::PhantomData; use std::ops::Deref; use std::os::raw::{c_int, c_void}; use std::panic::Location; -use std::rc::Rc; use std::result::Result as StdResult; -use std::{mem, ptr}; +use std::{fmt, mem, ptr}; use crate::chunk::{AsChunk, Chunk}; use crate::error::{Error, Result}; @@ -352,8 +350,9 @@ impl Lua { /// of the program's life. /// /// Dropping the returned reference will cause a memory leak. If this is not acceptable, - /// the reference should first be wrapped with the [`Lua::from_static`] function producing a `Lua`. - /// This `Lua` object can then be dropped which will properly release the allocated memory. + /// the reference should first be wrapped with the [`Lua::from_static`] function producing a + /// `Lua`. This `Lua` object can then be dropped which will properly release the allocated + /// memory. /// /// [`Lua::from_static`]: #method.from_static /// @@ -366,7 +365,8 @@ impl Lua { /// Constructs a `Lua` from a static reference to it. /// /// # Safety - /// This function is unsafe because improper use may lead to memory problems or undefined behavior. + /// This function is unsafe because improper use may lead to memory problems or undefined + /// behavior. /// /// FIXME: remove #[doc(hidden)] @@ -424,8 +424,8 @@ impl Lua { /// - Set all libraries to read-only /// - Set all builtin metatables to read-only /// - Set globals to read-only (and activates safeenv) - /// - Setup local environment table that performs writes locally and proxies reads - /// to the global environment. + /// - Setup local environment table that performs writes locally and proxies reads to the global + /// environment. /// /// # Examples /// @@ -482,7 +482,8 @@ impl Lua { /// erroring once an instruction limit has been reached. /// /// This method sets a hook function for the current thread of this Lua instance. - /// If you want to set a hook function for another thread (coroutine), use [`Thread::set_hook()`] instead. + /// If you want to set a hook function for another thread (coroutine), use + /// [`Thread::set_hook()`] instead. /// /// Please note you cannot have more than one hook function set at a time for this Lua instance. /// @@ -548,8 +549,8 @@ impl Lua { /// /// The provided interrupt function can error, and this error will be propagated through /// the Luau code that was executing at the time the interrupt was triggered. - /// Also this can be used to implement continuous execution limits by instructing Luau VM to yield - /// by returning [`VmState::Yield`]. + /// Also this can be used to implement continuous execution limits by instructing Luau VM to + /// yield by returning [`VmState::Yield`]. /// /// This is similar to [`Lua::set_hook`] but in more simplified form. /// @@ -589,6 +590,8 @@ impl Lua { where F: Fn(&Lua) -> Result + MaybeSend + 'static, { + use std::rc::Rc; + unsafe extern "C-unwind" fn interrupt_proc(state: *mut ffi::lua_State, gc: c_int) { if gc >= 0 { // We don't support GC interrupts since they cannot survive Lua exceptions @@ -597,8 +600,7 @@ impl Lua { let extra = ExtraData::get(state); let result = callback_error_ext(state, extra, move |_| { let interrupt_cb = (*extra).interrupt_callback.clone(); - let interrupt_cb = - mlua_expect!(interrupt_cb, "no interrupt callback set in interrupt_proc"); + let interrupt_cb = mlua_expect!(interrupt_cb, "no interrupt callback set in interrupt_proc"); if Rc::strong_count(&interrupt_cb) > 2 { return Ok(VmState::Continue); // Don't allow recursion } @@ -704,9 +706,10 @@ impl Lua { /// Gets information about the interpreter runtime stack. /// - /// This function returns [`Debug`] structure that can be used to get information about the function - /// executing at a given level. Level `0` is the current running function, whereas level `n+1` is the - /// function that has called level `n` (except for tail calls, which do not count in the stack). + /// This function returns [`Debug`] structure that can be used to get information about the + /// function executing at a given level. Level `0` is the current running function, whereas + /// level `n+1` is the function that has called level `n` (except for tail calls, which do + /// not count in the stack). /// /// [`Debug`]: crate::hook::Debug pub fn inspect_stack(&self, level: usize) -> Option { @@ -762,12 +765,7 @@ impl Lua { /// Returns true if the garbage collector is currently running automatically. /// /// Requires `feature = "lua54/lua53/lua52/luau"` - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] pub fn gc_is_running(&self) -> bool { let lua = self.lock(); unsafe { ffi::lua_gc(lua.main_state, ffi::LUA_GCISRUNNING, 0) != 0 } @@ -887,8 +885,7 @@ impl Lua { } #[cfg(feature = "lua54")] - let prev_mode = - unsafe { ffi::lua_gc(state, ffi::LUA_GCINC, pause, step_multiplier, step_size) }; + let prev_mode = unsafe { ffi::lua_gc(state, ffi::LUA_GCINC, pause, step_multiplier, step_size) }; #[cfg(feature = "lua54")] match prev_mode { ffi::LUA_GCINC => GCMode::Incremental, @@ -910,8 +907,7 @@ impl Lua { pub fn gc_gen(&self, minor_multiplier: c_int, major_multiplier: c_int) -> GCMode { let lua = self.lock(); let state = lua.main_state; - let prev_mode = - unsafe { ffi::lua_gc(state, ffi::LUA_GCGEN, minor_multiplier, major_multiplier) }; + let prev_mode = unsafe { ffi::lua_gc(state, ffi::LUA_GCGEN, minor_multiplier, major_multiplier) }; match prev_mode { ffi::LUA_GCGEN => GCMode::Generational, ffi::LUA_GCINC => GCMode::Incremental, @@ -1074,8 +1070,8 @@ impl Lua { /// intermediate Lua code. /// /// If the function returns `Ok`, the contained value will be converted to one or more Lua - /// values. For details on Rust-to-Lua conversions, refer to the [`IntoLua`] and [`IntoLuaMulti`] - /// traits. + /// values. For details on Rust-to-Lua conversions, refer to the [`IntoLua`] and + /// [`IntoLuaMulti`] traits. /// /// # Examples /// @@ -1137,9 +1133,7 @@ impl Lua { { let func = RefCell::new(func); self.create_function(move |lua, args| { - (*func - .try_borrow_mut() - .map_err(|_| Error::RecursiveMutCallback)?)(lua, args) + (*func.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?)(lua, args) }) } @@ -1158,10 +1152,10 @@ impl Lua { /// While executing the function Rust will poll Future and if the result is not ready, call /// `yield()` passing internal representation of a `Poll::Pending` value. /// - /// The function must be called inside Lua coroutine ([`Thread`]) to be able to suspend its execution. - /// An executor should be used to poll [`AsyncThread`] and mlua will take a provided Waker - /// in that case. Otherwise noop waker will be used if try to call the function outside of Rust - /// executors. + /// The function must be called inside Lua coroutine ([`Thread`]) to be able to suspend its + /// execution. An executor should be used to poll [`AsyncThread`] and mlua will take a + /// provided Waker in that case. Otherwise noop waker will be used if try to call the + /// function outside of Rust executors. /// /// The family of `call_async()` functions takes care about creating [`Thread`]. /// @@ -1277,10 +1271,7 @@ impl Lua { /// Registers a custom Rust type in Lua to use in userdata objects. /// /// This methods provides a way to add fields or methods to userdata objects of a type `T`. - pub fn register_userdata_type( - &self, - f: impl FnOnce(&mut UserDataRegistry), - ) -> Result<()> { + pub fn register_userdata_type(&self, f: impl FnOnce(&mut UserDataRegistry)) -> Result<()> { let mut registry = UserDataRegistry::new(); f(&mut registry); @@ -1376,8 +1367,9 @@ impl Lua { } } - /// Returns a handle to the active `Thread`. For calls to `Lua` this will be the main Lua thread, - /// for parameters given to a callback, this will be whatever Lua thread called the callback. + /// Returns a handle to the active `Thread`. For calls to `Lua` this will be the main Lua + /// thread, for parameters given to a callback, this will be whatever Lua thread called the + /// callback. pub fn current_thread(&self) -> Thread { let lua = self.lock(); let state = lua.state(); @@ -1645,9 +1637,9 @@ impl Lua { /// Removes a value from the Lua registry. /// /// You may call this function to manually remove a value placed in the registry with - /// [`Lua::create_registry_value`]. In addition to manual [`RegistryKey`] removal, you can also call - /// [`Lua::expire_registry_values`] to automatically remove values from the registry whose - /// [`RegistryKey`]s have been dropped. + /// [`Lua::create_registry_value`]. In addition to manual [`RegistryKey`] removal, you can also + /// call [`Lua::expire_registry_values`] to automatically remove values from the registry + /// whose [`RegistryKey`]s have been dropped. pub fn remove_registry_value(&self, key: RegistryKey) -> Result<()> { let lua = self.lock(); if !lua.owns_registry_value(&key) { @@ -1700,8 +1692,8 @@ impl Lua { Ok(()) } - /// Returns true if the given [`RegistryKey`] was created by a [`Lua`] which shares the underlying - /// main state with this [`Lua`] instance. + /// Returns true if the given [`RegistryKey`] was created by a [`Lua`] which shares the + /// underlying main state with this [`Lua`] instance. /// /// Other than this, methods that accept a [`RegistryKey`] will return /// [`Error::MismatchedRegistryKey`] if passed a [`RegistryKey`] that was not created with a @@ -1713,9 +1705,9 @@ impl Lua { /// Remove any registry values whose [`RegistryKey`]s have all been dropped. /// - /// Unlike normal handle values, [`RegistryKey`]s do not automatically remove themselves on Drop, - /// but you can call this method to remove any unreachable registry values not manually removed - /// by [`Lua::remove_registry_value`]. + /// Unlike normal handle values, [`RegistryKey`]s do not automatically remove themselves on + /// Drop, but you can call this method to remove any unreachable registry values not + /// manually removed by [`Lua::remove_registry_value`]. pub fn expire_registry_values(&self) { let lua = self.lock(); let state = lua.state(); @@ -1730,8 +1722,8 @@ impl Lua { /// Sets or replaces an application data object of type `T`. /// - /// Application data could be accessed at any time by using [`Lua::app_data_ref`] or [`Lua::app_data_mut`] - /// methods where `T` is the data type. + /// Application data could be accessed at any time by using [`Lua::app_data_ref`] or + /// [`Lua::app_data_mut`] methods where `T` is the data type. /// /// # Panics /// @@ -1770,7 +1762,8 @@ impl Lua { /// Returns: /// - `Ok(Some(old_data))` if the data object of type `T` was successfully replaced. /// - `Ok(None)` if the data object of type `T` was successfully inserted. - /// - `Err(data)` if the data object of type `T` was not inserted because the container is currently borrowed. + /// - `Err(data)` if the data object of type `T` was not inserted because the container is + /// currently borrowed. /// /// See [`Lua::set_app_data()`] for examples. pub fn try_set_app_data(&self, data: T) -> StdResult, T> { @@ -1779,12 +1772,13 @@ impl Lua { extra.app_data.try_insert(data) } - /// Gets a reference to an application data object stored by [`Lua::set_app_data()`] of type `T`. + /// Gets a reference to an application data object stored by [`Lua::set_app_data()`] of type + /// `T`. /// /// # Panics /// - /// Panics if the data object of type `T` is currently mutably borrowed. Multiple immutable reads - /// can be taken out at the same time. + /// Panics if the data object of type `T` is currently mutably borrowed. Multiple immutable + /// reads can be taken out at the same time. #[track_caller] pub fn app_data_ref(&self) -> Option> { let guard = self.lock_arc(); @@ -1792,7 +1786,8 @@ impl Lua { extra.app_data.borrow(Some(guard)) } - /// Gets a mutable reference to an application data object stored by [`Lua::set_app_data()`] of type `T`. + /// Gets a mutable reference to an application data object stored by [`Lua::set_app_data()`] of + /// type `T`. /// /// # Panics /// diff --git a/src/state/raw.rs b/src/state/raw.rs index 860a108c..1f05266b 100644 --- a/src/state/raw.rs +++ b/src/state/raw.rs @@ -18,15 +18,15 @@ use crate::string::String; use crate::table::Table; use crate::thread::Thread; use crate::types::{ - AppDataRef, AppDataRefMut, Callback, CallbackUpvalue, DestructedUserdata, Integer, - LightUserData, MaybeSend, ReentrantMutex, RegistryKey, SubtypeId, ValueRef, XRc, + AppDataRef, AppDataRefMut, Callback, CallbackUpvalue, DestructedUserdata, Integer, LightUserData, + MaybeSend, ReentrantMutex, RegistryKey, SubtypeId, ValueRef, XRc, }; use crate::userdata::{AnyUserData, MetaMethod, UserData, UserDataRegistry, UserDataVariant}; use crate::util::{ assert_stack, check_stack, get_destructed_userdata_metatable, get_gc_userdata, get_main_state, get_userdata, init_error_registry, init_gc_metatable, init_userdata_metatable, pop_error, - push_gc_userdata, push_string, push_table, rawset_field, safe_pcall, safe_xpcall, - short_type_name, StackGuard, WrappedFailure, + push_gc_userdata, push_string, push_table, rawset_field, safe_pcall, safe_xpcall, short_type_name, + StackGuard, WrappedFailure, }; use crate::value::{FromLuaMulti, IntoLua, MultiValue, Nil, Value}; @@ -220,9 +220,7 @@ impl RawLua { rawlua } - pub(super) unsafe fn try_from_ptr( - state: *mut ffi::lua_State, - ) -> Option>> { + pub(super) unsafe fn try_from_ptr(state: *mut ffi::lua_State) -> Option>> { match ExtraData::get(state) { extra if extra.is_null() => None, extra => Some(XRc::clone(&(*extra).lua().0)), @@ -261,10 +259,7 @@ impl RawLua { // If `package` library loaded into a safe lua state then disable C modules let curr_libs = (*self.extra.get()).libs; if is_safe && (curr_libs ^ (curr_libs | libs)).contains(StdLib::PACKAGE) { - mlua_expect!( - self.lua().disable_c_modules(), - "Error during disabling C modules" - ); + mlua_expect!(self.lua().disable_c_modules(), "Error during disabling C modules"); } unsafe { (*self.extra.get()).libs |= libs }; @@ -273,10 +268,7 @@ impl RawLua { /// See [`Lua::try_set_app_data`] #[inline] - pub(crate) fn try_set_app_data( - &self, - data: T, - ) -> StdResult, T> { + pub(crate) fn try_set_app_data(&self, data: T) -> StdResult, T> { let extra = unsafe { &*self.extra.get() }; extra.app_data.try_insert(data) } @@ -400,11 +392,7 @@ impl RawLua { } /// See [`Lua::create_table_with_capacity`] - pub(crate) unsafe fn create_table_with_capacity( - &self, - narr: usize, - nrec: usize, - ) -> Result { + pub(crate) unsafe fn create_table_with_capacity(&self, narr: usize, nrec: usize) -> Result
{ if self.unlikely_memory_error() { push_table(self.ref_thread(), narr, nrec, false)?; return Ok(Table(self.pop_ref_thread())); @@ -587,9 +575,7 @@ impl RawLua { ffi::LUA_TBOOLEAN => Value::Boolean(ffi::lua_toboolean(state, idx) != 0), - ffi::LUA_TLIGHTUSERDATA => { - Value::LightUserData(LightUserData(ffi::lua_touserdata(state, idx))) - } + ffi::LUA_TLIGHTUSERDATA => Value::LightUserData(LightUserData(ffi::lua_touserdata(state, idx))), #[cfg(any(feature = "lua54", feature = "lua53"))] ffi::LUA_TNUMBER => { @@ -600,12 +586,7 @@ impl RawLua { } } - #[cfg(any( - feature = "lua52", - feature = "lua51", - feature = "luajit", - feature = "luau" - ))] + #[cfg(any(feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))] ffi::LUA_TNUMBER => { use crate::types::Number; @@ -770,10 +751,7 @@ impl RawLua { }) } - pub(crate) unsafe fn make_any_userdata( - &self, - data: UserDataVariant, - ) -> Result + pub(crate) unsafe fn make_any_userdata(&self, data: UserDataVariant) -> Result where T: 'static, { @@ -806,12 +784,7 @@ impl RawLua { #[cfg(not(feature = "lua54"))] crate::util::push_userdata(state, data, protect)?; #[cfg(feature = "lua54")] - crate::util::push_userdata_uv( - state, - data, - crate::userdata::USER_VALUE_MAXSLOT as c_int, - protect, - )?; + crate::util::push_userdata_uv(state, data, crate::userdata::USER_VALUE_MAXSLOT as c_int, protect)?; ffi::lua_replace(state, -3); ffi::lua_setmetatable(state, -2); @@ -950,7 +923,8 @@ impl RawLua { ffi::lua_pop(state, 1); // All done } ffi::LUA_TNIL => { - rawset_field(state, metatable_index, "__index")?; // Set the new table as `__index` + // Set the new table as `__index` + rawset_field(state, metatable_index, "__index")?; } _ => { methods_index = Some(ffi::lua_absindex(state, -1)); @@ -963,10 +937,7 @@ impl RawLua { let extra_init = None; #[cfg(not(feature = "luau"))] let extra_init: Option Result<()>> = Some(|state| { - ffi::lua_pushcfunction( - state, - crate::util::userdata_destructor::>, - ); + ffi::lua_pushcfunction(state, crate::util::userdata_destructor::>); rawset_field(state, -2, "__gc") }); @@ -1024,10 +995,7 @@ impl RawLua { // Returns `TypeId` for the userdata ref, checking that it's registered and not destructed. // // Returns `None` if the userdata is registered but non-static. - pub(crate) unsafe fn get_userdata_ref_type_id( - &self, - vref: &ValueRef, - ) -> Result> { + pub(crate) unsafe fn get_userdata_ref_type_id(&self, vref: &ValueRef) -> Result> { self.get_userdata_type_id_inner(self.ref_thread(), vref.index) } @@ -1123,12 +1091,7 @@ impl RawLua { #[cfg(feature = "async")] pub(crate) fn create_async_callback(&self, func: AsyncCallback) -> Result { - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] unsafe { if !(*self.extra.get()).libs.contains(StdLib::COROUTINE) { load_from_std_lib(self.main_state, StdLib::COROUTINE)?; @@ -1322,12 +1285,7 @@ unsafe fn load_from_std_lib(state: *mut ffi::lua_State, libs: StdLib) -> Result< #[cfg(feature = "luajit")] let _gc_guard = GcGuard::new(state); - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] { if libs.contains(StdLib::COROUTINE) { requiref(state, ffi::LUA_COLIBNAME, ffi::luaopen_coroutine, 1)?; diff --git a/src/state/util.rs b/src/state/util.rs index 8c6a66b1..c1d64921 100644 --- a/src/state/util.rs +++ b/src/state/util.rs @@ -63,11 +63,7 @@ where } } - unsafe fn r#use( - &self, - state: *mut ffi::lua_State, - extra: *mut ExtraData, - ) -> *mut WrappedFailure { + unsafe fn r#use(&self, state: *mut ffi::lua_State, extra: *mut ExtraData) -> *mut WrappedFailure { let ref_thread = (*extra).ref_thread; match *self { PreallocatedFailure::New(ud) => { @@ -176,9 +172,7 @@ pub(super) unsafe fn ref_stack_pop(extra: *mut ExtraData) -> c_int { let top = extra.ref_stack_top; // It is a user error to create enough references to exhaust the Lua max stack size for // the ref thread. - panic!( - "cannot create a Lua reference, out of auxiliary stack space (used {top} slots)" - ); + panic!("cannot create a Lua reference, out of auxiliary stack space (used {top} slots)"); } extra.ref_stack_size += inc; } diff --git a/src/stdlib.rs b/src/stdlib.rs index e3630d44..c71d1497 100644 --- a/src/stdlib.rs +++ b/src/stdlib.rs @@ -8,12 +8,7 @@ impl StdLib { /// [`coroutine`](https://www.lua.org/manual/5.4/manual.html#6.2) library /// /// Requires `feature = "lua54/lua53/lua52/luau"` - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] pub const COROUTINE: StdLib = StdLib(1); /// [`table`](https://www.lua.org/manual/5.4/manual.html#6.6) library diff --git a/src/table.rs b/src/table.rs index 478da12e..7f32d64e 100644 --- a/src/table.rs +++ b/src/table.rs @@ -272,8 +272,8 @@ impl Table { } } - /// Inserts element value at position `idx` to the table, shifting up the elements from `table[idx]`. - /// The worst case complexity is O(n), where n is the table length. + /// Inserts element value at position `idx` to the table, shifting up the elements from + /// `table[idx]`. The worst case complexity is O(n), where n is the table length. pub fn raw_insert(&self, idx: Integer, value: V) -> Result<()> { let size = self.raw_len() as Integer; if idx < 1 || idx > size + 1 { @@ -878,7 +878,8 @@ where pub trait TableExt: Sealed { /// Calls the table as function assuming it has `__call` metamethod. /// - /// The metamethod is called with the table as its first argument, followed by the passed arguments. + /// The metamethod is called with the table as its first argument, followed by the passed + /// arguments. fn call(&self, args: A) -> Result where A: IntoLuaMulti, @@ -886,7 +887,8 @@ pub trait TableExt: Sealed { /// Asynchronously calls the table as function assuming it has `__call` metamethod. /// - /// The metamethod is called with the table as its first argument, followed by the passed arguments. + /// The metamethod is called with the table as its first argument, followed by the passed + /// arguments. #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] fn call_async(&self, args: A) -> impl Future> diff --git a/src/thread.rs b/src/thread.rs index db654963..af11f4ed 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -161,10 +161,7 @@ impl Thread { return Err(pop_error(thread_state, ret)); } check_stack(state, 3)?; - protect_lua!(state, 0, 1, |state| error_traceback_thread( - state, - thread_state - ))?; + protect_lua!(state, 0, 1, |state| error_traceback_thread(state, thread_state))?; return Err(pop_error(state, ret)); } diff --git a/src/types.rs b/src/types.rs index abd88af2..e09aca8d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -189,7 +189,8 @@ pub(crate) struct DestructedUserdata; /// /// This is a handle to a value stored inside the Lua registry. It is not automatically /// garbage collected on Drop, but it can be removed with [`Lua::remove_registry_value`], -/// and instances not manually removed can be garbage collected with [`Lua::expire_registry_values`]. +/// and instances not manually removed can be garbage collected with +/// [`Lua::expire_registry_values`]. /// /// Be warned, If you place this into Lua via a [`UserData`] type or a rust callback, it is *very /// easy* to accidentally cause reference cycles that the Lua garbage collector cannot resolve. diff --git a/src/types/app_data.rs b/src/types/app_data.rs index 3b6a4ab0..35cde1a0 100644 --- a/src/types/app_data.rs +++ b/src/types/app_data.rs @@ -6,9 +6,8 @@ use std::result::Result as StdResult; use rustc_hash::FxHashMap; -use crate::state::LuaGuard; - use super::MaybeSend; +use crate::state::LuaGuard; #[cfg(not(feature = "send"))] type Container = UnsafeCell>>>; @@ -56,10 +55,7 @@ impl AppData { } #[track_caller] - pub(crate) fn borrow_mut( - &self, - guard: Option, - ) -> Option> { + pub(crate) fn borrow_mut(&self, guard: Option) -> Option> { let data = unsafe { &*self.container.get() } .get(&TypeId::of::())? .borrow_mut(); diff --git a/src/userdata.rs b/src/userdata.rs index 855d4d55..fdb3f499 100644 --- a/src/userdata.rs +++ b/src/userdata.rs @@ -107,12 +107,7 @@ pub enum MetaMethod { /// This is not an operator, but it will be called by the built-in `pairs` function. /// /// Requires `feature = "lua54/lua53/lua52"` - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52", - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52",))] Pairs, /// The `__ipairs` metamethod. /// @@ -148,7 +143,8 @@ pub enum MetaMethod { Close, /// The `__name`/`__type` metafield. /// - /// This is not a function, but it's value can be used by `tostring` and `typeof` built-in functions. + /// This is not a function, but it's value can be used by `tostring` and `typeof` built-in + /// functions. #[doc(hidden)] Type, } @@ -208,12 +204,7 @@ impl MetaMethod { MetaMethod::Call => "__call", MetaMethod::ToString => "__tostring", - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] MetaMethod::Pairs => "__pairs", #[cfg(any(feature = "lua52", feature = "luajit52"))] MetaMethod::IPairs => "__ipairs", @@ -480,8 +471,8 @@ pub trait UserDataFields<'a, T> { /// Add a regular field getter as a method which accepts a `&T` as the parameter. /// - /// Regular field getters are implemented by overriding the `__index` metamethod and returning the - /// accessed field. This allows them to be used with the expected `userdata.field` syntax. + /// Regular field getters are implemented by overriding the `__index` metamethod and returning + /// the accessed field. This allows them to be used with the expected `userdata.field` syntax. /// /// 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. @@ -492,11 +483,12 @@ pub trait UserDataFields<'a, T> { /// Add a regular field setter as a method which accepts a `&mut T` as the first parameter. /// - /// Regular field setters are implemented by overriding the `__newindex` metamethod and setting the - /// accessed field. This allows them to be used with the expected `userdata.field = value` syntax. + /// Regular field setters are implemented by overriding the `__newindex` metamethod and setting + /// the accessed field. This allows them to be used with the expected `userdata.field = value` + /// syntax. /// - /// 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. + /// 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(&mut self, name: impl ToString, method: M) where M: FnMut(&'a Lua, &mut T, A) -> Result<()> + MaybeSend + 'static, @@ -577,8 +569,8 @@ pub trait UserDataFields<'a, T> { /// # } /// ``` /// -/// Custom fields, methods and operators can be provided by implementing `add_fields` or `add_methods` -/// (refer to [`UserDataFields`] and [`UserDataMethods`] for more information): +/// Custom fields, methods and operators can be provided by implementing `add_fields` or +/// `add_methods` (refer to [`UserDataFields`] and [`UserDataMethods`] for more information): /// /// ``` /// # use mlua::{Lua, MetaMethod, Result, UserData, UserDataFields, UserDataMethods}; @@ -686,7 +678,8 @@ impl AnyUserData { } /// Takes the value out of this userdata. - /// Sets the special "destructed" metatable that prevents any further operations with this userdata. + /// Sets the special "destructed" metatable that prevents any further operations with this + /// userdata. /// /// Keeps associated user values unchanged (they will be collected by Lua's GC). pub fn take(&self) -> Result { @@ -1005,7 +998,8 @@ impl AnyUserData { Ok(false) } - /// Returns `true` if this `AnyUserData` is serializable (eg. was created using `create_ser_userdata`). + /// Returns `true` if this `AnyUserData` is serializable (eg. was created using + /// `create_ser_userdata`). #[cfg(feature = "serialize")] pub(crate) fn is_serializable(&self) -> bool { let lua = self.0.lua.lock(); @@ -1079,8 +1073,8 @@ impl UserDataMetatable { /// /// If the value is `Nil`, this will effectively remove the `key`. /// Access to restricted metamethods such as `__gc` or `__metatable` will cause an error. - /// Setting `__index` or `__newindex` metamethods is also restricted because their values are cached - /// for `mlua` internal usage. + /// Setting `__index` or `__newindex` metamethods is also restricted because their values are + /// cached for `mlua` internal usage. pub fn set(&self, key: impl AsRef, value: V) -> Result<()> { let key = MetaMethod::validate(key.as_ref())?; // `__index` and `__newindex` cannot be changed in runtime, because values are cached diff --git a/src/userdata/cell.rs b/src/userdata/cell.rs index 2ad4eb11..61d87e2d 100644 --- a/src/userdata/cell.rs +++ b/src/userdata/cell.rs @@ -9,8 +9,7 @@ use std::rc::Rc; use serde::ser::{Serialize, Serializer}; use crate::error::{Error, Result}; -use crate::state::RawLua; -use crate::state::{Lua, LuaGuard}; +use crate::state::{Lua, LuaGuard, RawLua}; use crate::userdata::AnyUserData; use crate::util::get_userdata; use crate::value::{FromLua, Value}; @@ -111,9 +110,7 @@ impl UserDataVariant { impl Serialize for UserDataVariant<()> { fn serialize(&self, serializer: S) -> std::result::Result { match self { - UserDataVariant::Default(_) => { - Err(serde::ser::Error::custom("cannot serialize ")) - } + UserDataVariant::Default(_) => Err(serde::ser::Error::custom("cannot serialize ")), UserDataVariant::Serializable(inner) => unsafe { let _ = self.try_borrow().map_err(serde::ser::Error::custom)?; (*inner.value.get()).serialize(serializer) diff --git a/src/userdata/ext.rs b/src/userdata/ext.rs index fd07192c..2156b5ef 100644 --- a/src/userdata/ext.rs +++ b/src/userdata/ext.rs @@ -16,7 +16,8 @@ pub trait AnyUserDataExt: Sealed { /// Calls the userdata as a function assuming it has `__call` metamethod. /// - /// The metamethod is called with the userdata as its first argument, followed by the passed arguments. + /// The metamethod is called with the userdata as its first argument, followed by the passed + /// arguments. fn call(&self, args: A) -> Result where A: IntoLuaMulti, @@ -24,7 +25,8 @@ pub trait AnyUserDataExt: Sealed { /// Asynchronously calls the userdata as a function assuming it has `__call` metamethod. /// - /// The metamethod is called with the userdata as its first argument, followed by the passed arguments. + /// The metamethod is called with the userdata as its first argument, followed by the passed + /// arguments. #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] fn call_async(&self, args: A) -> impl Future> diff --git a/src/userdata/registry.rs b/src/userdata/registry.rs index 90282c10..eb6c02f2 100644 --- a/src/userdata/registry.rs +++ b/src/userdata/registry.rs @@ -106,9 +106,7 @@ impl<'a, T: 'static> UserDataRegistry<'a, T> { let method = RefCell::new(method); Box::new(move |rawlua, nargs| unsafe { - let mut method = method - .try_borrow_mut() - .map_err(|_| Error::RecursiveMutCallback)?; + let mut method = method.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?; if nargs == 0 { let err = Error::from_lua_conversion("missing argument", "userdata", None); try_self_arg!(Err(err)); @@ -142,9 +140,7 @@ impl<'a, T: 'static> UserDataRegistry<'a, T> { ($res:expr) => { match $res { Ok(res) => res, - Err(err) => { - return Box::pin(future::ready(Err(Error::bad_self_argument(&name, err)))) - } + Err(err) => return Box::pin(future::ready(Err(Error::bad_self_argument(&name, err)))), } }; } @@ -189,9 +185,7 @@ impl<'a, T: 'static> UserDataRegistry<'a, T> { ($res:expr) => { match $res { Ok(res) => res, - Err(err) => { - return Box::pin(future::ready(Err(Error::bad_self_argument(&name, err)))) - } + Err(err) => return Box::pin(future::ready(Err(Error::bad_self_argument(&name, err)))), } }; } @@ -345,8 +339,7 @@ impl<'a, T: 'static> UserDataFields<'a, T> for UserDataRegistry<'a, T> { A: FromLua, { let name = name.to_string(); - let callback = - Self::box_function_mut(&name, move |lua, (data, val)| function(lua, data, val)); + let callback = Self::box_function_mut(&name, move |lua, (data, val)| function(lua, data, val)); self.field_setters.push((name, callback)); } diff --git a/src/util/mod.rs b/src/util/mod.rs index 966a919a..e682d836 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -45,10 +45,7 @@ pub unsafe fn assert_stack(state: *mut ffi::lua_State, amount: c_int) { // TODO: This should only be triggered when there is a logic error in `mlua`. In the future, // when there is a way to be confident about stack safety and test it, this could be enabled // only when `cfg!(debug_assertions)` is true. - mlua_assert!( - ffi::lua_checkstack(state, amount) != 0, - "out of stack space" - ); + mlua_assert!(ffi::lua_checkstack(state, amount) != 0, "out of stack space"); } // Checks that Lua has enough free stack space and returns `Error::StackError` on failure. @@ -101,8 +98,8 @@ impl Drop for StackGuard { // Call a function that calls into the Lua API and may trigger a Lua error (longjmp) in a safe way. // Wraps the inner function in a call to `lua_pcall`, so the inner function only has access to a // limited lua stack. `nargs` is the same as the the parameter to `lua_pcall`, and `nresults` is -// always `LUA_MULTRET`. Provided function must *not* panic, and since it will generally be lonjmping, -// should not contain any values that implements Drop. +// always `LUA_MULTRET`. Provided function must *not* panic, and since it will generally be +// longjmping, should not contain any values that implements Drop. // Internally uses 2 extra stack spaces, and does not call checkstack. pub unsafe fn protect_lua_call( state: *mut ffi::lua_State, @@ -133,8 +130,8 @@ pub unsafe fn protect_lua_call( // Wraps the inner function in a call to `lua_pcall`, so the inner function only has access to a // limited lua stack. `nargs` and `nresults` are similar to the parameters of `lua_pcall`, but the // given function return type is not the return value count, instead the inner function return -// values are assumed to match the `nresults` param. Provided function must *not* panic, and since it -// will generally be lonjmping, should not contain any values that implements Drop. +// values are assumed to match the `nresults` param. Provided function must *not* panic, and since +// it will generally be longjmping, should not contain any values that implements Drop. // Internally uses 3 extra stack spaces, and does not call checkstack. pub unsafe fn protect_lua_closure( state: *mut ffi::lua_State, @@ -232,8 +229,7 @@ pub unsafe fn pop_error(state: *mut ffi::lua_State, err_code: c_int) -> Error { Error::SyntaxError { // This seems terrible, but as far as I can tell, this is exactly what the // stock Lua REPL does. - incomplete_input: err_string.ends_with("") - || err_string.ends_with("''"), + incomplete_input: err_string.ends_with("") || err_string.ends_with("''"), message: err_string, } } @@ -283,12 +279,7 @@ pub unsafe fn push_buffer(state: *mut ffi::lua_State, b: &[u8], protect: bool) - // Uses 3 stack spaces, does not call checkstack. #[inline] -pub unsafe fn push_table( - state: *mut ffi::lua_State, - narr: usize, - nrec: usize, - protect: bool, -) -> Result<()> { +pub unsafe fn push_table(state: *mut ffi::lua_State, narr: usize, nrec: usize, protect: bool) -> Result<()> { let narr: c_int = narr.try_into().unwrap_or(c_int::MAX); let nrec: c_int = nrec.try_into().unwrap_or(c_int::MAX); if protect { @@ -380,11 +371,7 @@ pub unsafe fn take_userdata(state: *mut ffi::lua_State) -> T { // Pushes the userdata and attaches a metatable with __gc method. // Internally uses 3 stack spaces, does not call checkstack. -pub unsafe fn push_gc_userdata( - state: *mut ffi::lua_State, - t: T, - protect: bool, -) -> Result<()> { +pub unsafe fn push_gc_userdata(state: *mut ffi::lua_State, t: T, protect: bool) -> Result<()> { push_userdata(state, t, protect)?; get_gc_metatable::(state); ffi::lua_setmetatable(state, -2); @@ -556,12 +543,12 @@ pub unsafe fn init_userdata_metatable_newindex(state: *mut ffi::lua_State) -> Re }) } -// Populates the given table with the appropriate members to be a userdata metatable for the given type. -// This function takes the given table at the `metatable` index, and adds an appropriate `__gc` member -// to it for the given type and a `__metatable` entry to protect the table from script access. -// The function also, if given a `field_getters` or `methods` tables, will create an `__index` metamethod -// (capturing previous one) to lookup in `field_getters` first, then `methods` and falling back to the -// captured `__index` if no matches found. +// Populates the given table with the appropriate members to be a userdata metatable for the given +// type. This function takes the given table at the `metatable` index, and adds an appropriate +// `__gc` member to it for the given type and a `__metatable` entry to protect the table from script +// access. The function also, if given a `field_getters` or `methods` tables, will create an +// `__index` metamethod (capturing previous one) to lookup in `field_getters` first, then `methods` +// and falling back to the captured `__index` if no matches found. // The same is also applicable for `__newindex` metamethod and `field_setters` table. // Internally uses 9 stack spaces and does not call checkstack. pub unsafe fn init_userdata_metatable( @@ -873,8 +860,7 @@ pub unsafe fn init_gc_metatable( pub unsafe fn get_gc_metatable(state: *mut ffi::lua_State) { let type_id = TypeId::of::(); - let ref_addr = - mlua_expect!(METATABLE_CACHE.get(&type_id), "gc metatable does not exist") as *const u8; + let ref_addr = mlua_expect!(METATABLE_CACHE.get(&type_id), "gc metatable does not exist") as *const u8; ffi::lua_rawgetp(state, ffi::LUA_REGISTRYINDEX, ref_addr as *const c_void); } @@ -979,12 +965,7 @@ pub unsafe fn init_error_registry(state: *mut ffi::lua_State) -> Result<()> { "__newindex", "__call", "__tostring", - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] "__pairs", #[cfg(any(feature = "lua53", feature = "lua52", feature = "luajit52"))] "__ipairs", diff --git a/src/util/short_names.rs b/src/util/short_names.rs index 55713ec0..22623ed1 100644 --- a/src/util/short_names.rs +++ b/src/util/short_names.rs @@ -25,22 +25,17 @@ pub(crate) fn short_type_name() -> String { // Collapse everything up to the next special character, // then skip over it - if let Some(special_character_index) = rest_of_string - .find(|c: char| [' ', '<', '>', '(', ')', '[', ']', ',', ';'].contains(&c)) + if let Some(special_character_index) = + rest_of_string.find(|c: char| [' ', '<', '>', '(', ')', '[', ']', ',', ';'].contains(&c)) { - let segment_to_collapse = rest_of_string - .get(0..special_character_index) - .unwrap_or_default(); + let segment_to_collapse = rest_of_string.get(0..special_character_index).unwrap_or_default(); parsed_name += collapse_type_name(segment_to_collapse); // Insert the special character - let special_character = - &rest_of_string[special_character_index..=special_character_index]; + let special_character = &rest_of_string[special_character_index..=special_character_index]; parsed_name.push_str(special_character); match special_character { - ">" | ")" | "]" - if rest_of_string[special_character_index + 1..].starts_with("::") => - { + ">" | ")" | "]" if rest_of_string[special_character_index + 1..].starts_with("::") => { parsed_name.push_str("::"); // Move the index past the "::" index += special_character_index + 3; @@ -77,9 +72,6 @@ mod tests { short_type_name::>>(), "HashMap>" ); - assert_eq!( - short_type_name:: i32>(), - "dyn Fn(i32) -> i32" - ); + assert_eq!(short_type_name:: i32>(), "dyn Fn(i32) -> i32"); } } diff --git a/src/value.rs b/src/value.rs index 82dc8951..dd2289d3 100644 --- a/src/value.rs +++ b/src/value.rs @@ -116,8 +116,8 @@ impl Value { /// Converts the value to a generic C pointer. /// - /// The value can be a userdata, a table, a thread, a string, or a function; otherwise it returns NULL. - /// Different objects will give different pointers. + /// The value can be a userdata, a table, a thread, a string, or a function; otherwise it + /// returns NULL. Different objects will give different pointers. /// There is no way to convert the pointer back to its original value. /// /// Typically this function is used only for hashing and debug information. @@ -136,7 +136,8 @@ impl Value { /// Converts the value to a string. /// - /// If the value has a metatable with a `__tostring` method, then it will be called to get the result. + /// If the value has a metatable with a `__tostring` method, then it will be called to get the + /// result. pub fn to_string(&self) -> Result { match self { Value::Nil => Ok("nil".to_string()), @@ -814,10 +815,7 @@ impl MultiValue { } #[inline] - pub(crate) fn extend_from_values( - &mut self, - iter: impl IntoIterator>, - ) -> Result<()> { + pub(crate) fn extend_from_values(&mut self, iter: impl IntoIterator>) -> Result<()> { for value in iter { self.push_back(value?); } @@ -860,8 +858,8 @@ impl<'a> IntoIterator for &'a MultiValue { /// Trait for types convertible to any number of Lua values. /// -/// This is a generalization of `IntoLua`, allowing any number of resulting Lua values instead of just -/// one. Any type that implements `IntoLua` will automatically implement this trait. +/// This is a generalization of `IntoLua`, allowing any number of resulting Lua values instead of +/// just one. Any type that implements `IntoLua` will automatically implement this trait. pub trait IntoLuaMulti: Sized { /// Performs the conversion. fn into_lua_multi(self, lua: &Lua) -> Result; @@ -926,12 +924,7 @@ pub trait FromLuaMulti: Sized { /// Same as `from_lua_args` but for a number of values in the Lua stack. #[doc(hidden)] #[inline] - unsafe fn from_stack_args( - nargs: c_int, - i: usize, - to: Option<&str>, - lua: &RawLua, - ) -> Result { + unsafe fn from_stack_args(nargs: c_int, i: usize, to: Option<&str>, lua: &RawLua) -> Result { let _ = (i, to); Self::from_stack_multi(nargs, lua) } diff --git a/tests/async.rs b/tests/async.rs index 0fda52ff..782075ee 100644 --- a/tests/async.rs +++ b/tests/async.rs @@ -6,8 +6,8 @@ use std::time::Duration; use futures_util::stream::TryStreamExt; use mlua::{ - AnyUserDataExt, Error, Function, Lua, LuaOptions, MultiValue, Result, StdLib, Table, TableExt, - UserData, UserDataMethods, Value, + AnyUserDataExt, Error, Function, Lua, LuaOptions, MultiValue, Result, StdLib, Table, TableExt, UserData, + UserDataMethods, Value, }; #[cfg(not(target_arch = "wasm32"))] @@ -25,8 +25,7 @@ async fn sleep_ms(_ms: u64) { async fn test_async_function() -> Result<()> { let lua = Lua::new(); - let f = lua - .create_async_function(|_lua, (a, b, c): (i64, i64, i64)| async move { Ok((a + b) * c) })?; + let f = lua.create_async_function(|_lua, (a, b, c): (i64, i64, i64)| async move { Ok((a + b) * c) })?; lua.globals().set("f", f)?; let res: i64 = lua.load("f(1, 2, 3)").eval_async().await?; @@ -75,9 +74,7 @@ async fn test_async_call() -> Result<()> { match hello.call::<_, ()>("alex") { Err(Error::RuntimeError(_)) => {} - _ => panic!( - "non-async executing async function must fail on the yield stage with RuntimeError" - ), + _ => panic!("non-async executing async function must fail on the yield stage with RuntimeError"), }; assert_eq!(hello.call_async::<_, String>("alex").await?, "hello, alex!"); @@ -342,15 +339,9 @@ async fn test_async_table() -> Result<()> { })?; table.set("sleep", sleep)?; - assert_eq!( - table.call_async_method::<_, i64>("get_value", ()).await?, - 10 - ); + assert_eq!(table.call_async_method::<_, i64>("get_value", ()).await?, 10); table.call_async_method("set_value", 15).await?; - assert_eq!( - table.call_async_method::<_, i64>("get_value", ()).await?, - 15 - ); + assert_eq!(table.call_async_method::<_, i64>("get_value", ()).await?, 15); assert_eq!( table.call_async_function::<_, String>("sleep", 7).await?, "elapsed:7ms" @@ -411,17 +402,14 @@ async fn test_async_userdata() -> Result<()> { }); #[cfg(not(any(feature = "lua51", feature = "luau")))] - methods.add_async_meta_method( - mlua::MetaMethod::Index, - |_, data, key: String| async move { - sleep_ms(10).await; - match key.as_str() { - "ms" => Ok(Some(data.0 as f64)), - "s" => Ok(Some((data.0 as f64) / 1000.0)), - _ => Ok(None), - } - }, - ); + methods.add_async_meta_method(mlua::MetaMethod::Index, |_, data, key: String| async move { + sleep_ms(10).await; + match key.as_str() { + "ms" => Ok(Some(data.0 as f64)), + "s" => Ok(Some((data.0 as f64) / 1000.0)), + _ => Ok(None), + } + }); #[cfg(not(any(feature = "lua51", feature = "luau")))] methods.add_async_meta_method_mut( diff --git a/tests/chunk.rs b/tests/chunk.rs index a797064e..31e55a24 100644 --- a/tests/chunk.rs +++ b/tests/chunk.rs @@ -1,5 +1,4 @@ -use std::fs; -use std::io; +use std::{fs, io}; use mlua::{Lua, Result}; diff --git a/tests/conversion.rs b/tests/conversion.rs index a0e0b383..709b0ba8 100644 --- a/tests/conversion.rs +++ b/tests/conversion.rs @@ -5,8 +5,7 @@ use std::ffi::{CStr, CString}; use bstr::BString; use maplit::{btreemap, btreeset, hashmap, hashset}; use mlua::{ - AnyUserData, Error, Function, IntoLua, Lua, RegistryKey, Result, Table, Thread, UserDataRef, - Value, + AnyUserData, Error, Function, IntoLua, Lua, RegistryKey, Result, Table, Thread, UserDataRef, Value, }; #[test] @@ -142,10 +141,7 @@ fn test_registry_value_into_lua() -> Result<()> { // Check non-owned registry key let lua2 = Lua::new(); let r2 = lua2.create_registry_value("abc")?; - assert!(matches!( - f.call::<_, ()>(&r2), - Err(Error::MismatchedRegistryKey) - )); + assert!(matches!(f.call::<_, ()>(&r2), Err(Error::MismatchedRegistryKey))); Ok(()) } diff --git a/tests/error.rs b/tests/error.rs index 0bd224a4..5bfd9485 100644 --- a/tests/error.rs +++ b/tests/error.rs @@ -6,9 +6,8 @@ use mlua::{Error, ErrorContext, Lua, Result}; fn test_error_context() -> Result<()> { let lua = Lua::new(); - let func = lua.create_function(|_, ()| { - Err::<(), _>(Error::runtime("runtime error")).context("some context") - })?; + let func = + lua.create_function(|_, ()| Err::<(), _>(Error::runtime("runtime error")).context("some context"))?; lua.globals().set("func", func)?; let msg = lua @@ -33,12 +32,9 @@ fn test_error_context() -> Result<()> { // Rewrite context message and test `downcast_ref` let func3 = lua.create_function(|_, ()| { - Err::<(), _>(Error::external(io::Error::new( - io::ErrorKind::Other, - "other", - ))) - .context("some context") - .context("some new context") + Err::<(), _>(Error::external(io::Error::new(io::ErrorKind::Other, "other"))) + .context("some context") + .context("some new context") })?; let res = func3.call::<_, ()>(()).err().unwrap(); let Error::CallbackError { cause, .. } = &res else { diff --git a/tests/function.rs b/tests/function.rs index c7596bed..26d40e1f 100644 --- a/tests/function.rs +++ b/tests/function.rs @@ -43,10 +43,7 @@ fn test_bind() -> Result<()> { concat = concat.bind("bar")?; concat = concat.bind(("baz", "baf"))?; assert_eq!(concat.call::<_, String>(())?, "foobarbazbaf"); - assert_eq!( - concat.call::<_, String>(("hi", "wut"))?, - "foobarbazbafhiwut" - ); + assert_eq!(concat.call::<_, String>(("hi", "wut"))?, "foobarbazbafhiwut"); let mut concat2 = globals.get::<_, Function>("concat")?; concat2 = concat2.bind(())?; @@ -271,8 +268,7 @@ fn test_function_wrap() -> Result<()> { let lua = Lua::new(); - lua.globals() - .set("f", Function::wrap(|_, s: String| Ok(s)))?; + lua.globals().set("f", Function::wrap(|_, s: String| Ok(s)))?; lua.load(r#"assert(f("hello") == "hello")"#).exec().unwrap(); let mut _i = false; diff --git a/tests/hooks.rs b/tests/hooks.rs index d2049085..4186339b 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -75,15 +75,9 @@ fn test_function_calls() -> Result<()> { let output = output.lock().unwrap(); if cfg!(feature = "luajit") && lua.load("jit.version_num").eval::()? >= 20100 { - assert_eq!( - *output, - vec![(None, "main"), (Some("len".to_string()), "Lua")] - ); + assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "Lua")]); } else { - assert_eq!( - *output, - vec![(None, "main"), (Some("len".to_string()), "C")] - ); + assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "C")]); } Ok(()) @@ -97,10 +91,7 @@ fn test_error_within_hook() -> Result<()> { Err(Error::runtime("Something happened in there!")) }); - let err = lua - .load("x = 1") - .exec() - .expect_err("panic didn't propagate"); + let err = lua.load("x = 1").exec().expect_err("panic didn't propagate"); match err { Error::CallbackError { cause, .. } => match cause.deref() { @@ -153,14 +144,9 @@ fn test_limit_execution_instructions() -> Result<()> { fn test_hook_removal() -> Result<()> { let lua = Lua::new(); - lua.set_hook( - HookTriggers::new().every_nth_instruction(1), - |_lua, _debug| { - Err(Error::runtime( - "this hook should've been removed by this time", - )) - }, - ); + lua.set_hook(HookTriggers::new().every_nth_instruction(1), |_lua, _debug| { + Err(Error::runtime("this hook should've been removed by this time")) + }); assert!(lua.load("local x = 1").exec().is_err()); lua.remove_hook(); @@ -189,9 +175,10 @@ fn test_hook_swap_within_hook() -> Result<()> { .set_hook(HookTriggers::EVERY_LINE, move |lua, _debug| { lua.globals().set("ok", 1i64)?; TL_LUA.with(|tl| { - tl.borrow().as_ref().unwrap().set_hook( - HookTriggers::EVERY_LINE, - move |lua, _debug| { + tl.borrow() + .as_ref() + .unwrap() + .set_hook(HookTriggers::EVERY_LINE, move |lua, _debug| { lua.load( r#" if ok ~= nil then @@ -205,8 +192,7 @@ fn test_hook_swap_within_hook() -> Result<()> { tl.borrow().as_ref().unwrap().remove_hook(); }); Ok(()) - }, - ) + }) }); Ok(()) }) diff --git a/tests/luau.rs b/tests/luau.rs index 29af6cf2..db22c27a 100644 --- a/tests/luau.rs +++ b/tests/luau.rs @@ -7,17 +7,14 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use mlua::{ - Compiler, CoverageInfo, Error, Lua, LuaOptions, Result, StdLib, Table, ThreadStatus, Value, - Vector, VmState, + Compiler, CoverageInfo, Error, Lua, LuaOptions, Result, StdLib, Table, ThreadStatus, Value, Vector, + VmState, }; #[test] fn test_version() -> Result<()> { let lua = Lua::new(); - assert!(lua - .globals() - .get::<_, String>("_VERSION")? - .starts_with("Luau 0.")); + assert!(lua.globals().get::<_, String>("_VERSION")?.starts_with("Luau 0.")); Ok(()) } @@ -189,9 +186,7 @@ fn test_vector_metatable() -> Result<()> { lua.set_vector_metatable(Some(vector_mt.clone())); lua.globals().set("Vector3", vector_mt)?; - let compiler = Compiler::new() - .set_vector_lib("Vector3") - .set_vector_ctor("new"); + let compiler = Compiler::new().set_vector_lib("Vector3").set_vector_ctor("new"); // Test vector methods (fastcall) lua.load( diff --git a/tests/memory.rs b/tests/memory.rs index 0f9e8d04..77016b80 100644 --- a/tests/memory.rs +++ b/tests/memory.rs @@ -68,12 +68,7 @@ fn test_gc_control() -> Result<()> { assert_eq!(lua.gc_inc(0, 0, 0), GCMode::Generational); } - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luau" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luau"))] { assert!(lua.gc_is_running()); lua.gc_stop(); diff --git a/tests/serde.rs b/tests/serde.rs index 5dc4bd8f..f4bd67a9 100644 --- a/tests/serde.rs +++ b/tests/serde.rs @@ -4,8 +4,8 @@ use std::collections::HashMap; use std::error::Error as StdError; use mlua::{ - DeserializeOptions, Error, ExternalResult, Lua, LuaSerdeExt, Result as LuaResult, - SerializeOptions, UserData, Value, + DeserializeOptions, Error, ExternalResult, Lua, LuaSerdeExt, Result as LuaResult, SerializeOptions, + UserData, Value, }; use serde::{Deserialize, Serialize}; @@ -395,10 +395,7 @@ fn test_to_value_with_options() -> Result<(), Box> { unit: (), unitstruct: UnitStruct, }; - let data2 = lua.to_value_with( - &mydata, - SerializeOptions::new().serialize_none_to_null(false), - )?; + let data2 = lua.to_value_with(&mydata, SerializeOptions::new().serialize_none_to_null(false))?; globals.set("data2", data2)?; lua.load( r#" @@ -410,10 +407,7 @@ fn test_to_value_with_options() -> Result<(), Box> { .exec()?; // serialize_unit_to_null - let data3 = lua.to_value_with( - &mydata, - SerializeOptions::new().serialize_unit_to_null(false), - )?; + let data3 = lua.to_value_with(&mydata, SerializeOptions::new().serialize_unit_to_null(false))?; globals.set("data3", data3)?; lua.load( r#" diff --git a/tests/static.rs b/tests/static.rs index 7f6e0289..059f4ee8 100644 --- a/tests/static.rs +++ b/tests/static.rs @@ -83,16 +83,15 @@ async fn test_static_async() -> Result<()> { tokio::task::yield_now().await; } - let timer = - lua.create_async_function(|_, (i, n, f): (u64, u64, mlua::Function)| async move { - tokio::task::spawn_local(async move { - for _ in 0..n { - tokio::task::spawn_local(f.call_async::<(), ()>(())); - sleep_ms(i).await; - } - }); - Ok(()) - })?; + let timer = lua.create_async_function(|_, (i, n, f): (u64, u64, mlua::Function)| async move { + tokio::task::spawn_local(async move { + for _ in 0..n { + tokio::task::spawn_local(f.call_async::<(), ()>(())); + sleep_ms(i).await; + } + }); + Ok(()) + })?; lua.globals().set("timer", timer)?; { diff --git a/tests/string.rs b/tests/string.rs index 289e3ea7..3421c9cf 100644 --- a/tests/string.rs +++ b/tests/string.rs @@ -15,9 +15,7 @@ fn test_string_compare() { with_str("teststring", |t| assert_eq!(t, b"teststring".to_vec())); // Vec with_str("teststring", |t| assert_eq!(t, "teststring".to_string())); // String with_str("teststring", |t| assert_eq!(t, t)); // mlua::String - with_str("teststring", |t| { - assert_eq!(t, Cow::from(b"teststring".as_ref())) - }); // Cow (borrowed) + with_str("teststring", |t| assert_eq!(t, Cow::from(b"teststring".as_ref()))); // Cow (borrowed) with_str("bla", |t| assert_eq!(t, Cow::from(b"bla".to_vec()))); // Cow (owned) } @@ -40,14 +38,8 @@ fn test_string_views() -> Result<()> { let empty: String = 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?" - ); - assert_eq!( - ok.as_bytes(), - &b"null bytes are valid utf-8, wh\0 knew?"[..] - ); + assert_eq!(ok.to_string_lossy(), "null bytes are valid utf-8, wh\0 knew?"); + assert_eq!(ok.as_bytes(), &b"null bytes are valid utf-8, wh\0 knew?"[..]); assert!(err.to_str().is_err()); assert_eq!(err.as_bytes(), &b"but \xff isn't :("[..]); diff --git a/tests/table.rs b/tests/table.rs index cdbb122c..52cbc3f4 100644 --- a/tests/table.rs +++ b/tests/table.rs @@ -45,17 +45,11 @@ fn test_table() -> Result<()> { assert_eq!(table1.len()?, 5); assert!(!table1.is_empty()); assert_eq!( - table1 - .clone() - .pairs() - .collect::>>()?, + table1.clone().pairs().collect::>>()?, vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] ); assert_eq!( - table1 - .clone() - .sequence_values() - .collect::>>()?, + table1.clone().sequence_values().collect::>>()?, vec![1, 2, 3, 4, 5] ); assert_eq!(table1, [1, 2, 3, 4, 5]); @@ -63,10 +57,7 @@ fn test_table() -> Result<()> { assert_eq!(table2.len()?, 0); assert!(table2.is_empty()); assert_eq!( - table2 - .clone() - .pairs() - .collect::>>()?, + table2.clone().pairs().collect::>>()?, vec![] ); assert_eq!(table2, [0; 0]); @@ -81,29 +72,20 @@ fn test_table() -> Result<()> { globals.set("table4", lua.create_sequence_from(vec![1, 2, 3, 4, 5])?)?; let table4 = globals.get::<_, Table>("table4")?; assert_eq!( - table4 - .clone() - .pairs() - .collect::>>()?, + table4.clone().pairs().collect::>>()?, vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] ); table4.raw_insert(4, 35)?; table4.raw_insert(7, 7)?; assert_eq!( - table4 - .clone() - .pairs() - .collect::>>()?, + table4.clone().pairs().collect::>>()?, vec![(1, 1), (2, 2), (3, 3), (4, 35), (5, 4), (6, 5), (7, 7)] ); table4.raw_remove(1)?; assert_eq!( - table4 - .clone() - .pairs() - .collect::>>()?, + table4.clone().pairs().collect::>>()?, vec![(1, 2), (2, 3), (3, 35), (4, 4), (5, 5), (6, 7)] ); @@ -448,10 +430,7 @@ fn test_table_call() -> Result<()> { // Test calling non-callable table let table2 = lua.create_table()?; - assert!(matches!( - table2.call::<_, ()>(()), - Err(Error::RuntimeError(_)) - )); + assert!(matches!(table2.call::<_, ()>(()), Err(Error::RuntimeError(_)))); Ok(()) } diff --git a/tests/tests.rs b/tests/tests.rs index 8284fc2f..a77a351b 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -8,8 +8,8 @@ use std::sync::Arc; use std::{error, f32, f64, fmt}; use mlua::{ - ChunkMode, Error, ExternalError, Function, Lua, LuaOptions, Nil, Result, StdLib, String, Table, - UserData, Value, Variadic, + ChunkMode, Error, ExternalError, Function, Lua, LuaOptions, Nil, Result, StdLib, String, Table, UserData, + Value, Variadic, }; #[cfg(not(feature = "luau"))] @@ -108,10 +108,7 @@ fn test_exec() -> Result<()> { .eval()?; println!("checkpoint"); assert!(module.contains_key("func")?); - assert_eq!( - module.get::<_, Function>("func")?.call::<_, String>(())?, - "hello" - ); + assert_eq!(module.get::<_, Function>("func")?.call::<_, String>(())?, "hello"); Ok(()) } @@ -128,10 +125,7 @@ fn test_eval() -> Result<()> { incomplete_input: true, .. }) => {} - r => panic!( - "expected SyntaxError with incomplete_input=true, got {:?}", - r - ), + r => panic!("expected SyntaxError with incomplete_input=true, got {:?}", r), } Ok(()) @@ -141,10 +135,7 @@ fn test_eval() -> Result<()> { fn test_load_mode() -> Result<()> { let lua = unsafe { Lua::unsafe_new() }; - assert_eq!( - lua.load("1 + 1").set_mode(ChunkMode::Text).eval::()?, - 2 - ); + assert_eq!(lua.load("1 + 1").set_mode(ChunkMode::Text).eval::()?, 2); match lua.load("1 + 1").set_mode(ChunkMode::Binary).exec() { Ok(_) => panic!("expected SyntaxError, got no error"), Err(Error::SyntaxError { message: msg, .. }) => { @@ -158,12 +149,7 @@ fn test_load_mode() -> Result<()> { #[cfg(feature = "luau")] let bytecode = mlua::Compiler::new().compile("return 1 + 1"); assert_eq!(lua.load(&bytecode).eval::()?, 2); - assert_eq!( - lua.load(&bytecode) - .set_mode(ChunkMode::Binary) - .eval::()?, - 2 - ); + assert_eq!(lua.load(&bytecode).set_mode(ChunkMode::Binary).eval::()?, 2); match lua.load(&bytecode).set_mode(ChunkMode::Text).exec() { Ok(_) => panic!("expected SyntaxError, got no error"), Err(Error::SyntaxError { message: msg, .. }) => { @@ -308,8 +294,7 @@ fn test_error() -> Result<()> { ) .exec()?; - let rust_error_function = - lua.create_function(|_, ()| -> Result<()> { Err(TestError.into_lua_err()) })?; + let rust_error_function = lua.create_function(|_, ()| -> Result<()> { Err(TestError.into_lua_err()) })?; globals.set("rust_error_function", rust_error_function)?; let no_error = globals.get::<_, Function>("no_error")?; @@ -338,10 +323,7 @@ fn test_error() -> Result<()> { let return_string_error = globals.get::<_, Function>("return_string_error")?; assert!(return_string_error.call::<_, Error>(()).is_ok()); - match lua - .load("if youre happy and you know it syntax error") - .exec() - { + match lua.load("if youre happy and you know it syntax error").exec() { Err(Error::SyntaxError { incomplete_input: false, .. @@ -374,15 +356,13 @@ fn test_error() -> Result<()> { fn test_panic() -> Result<()> { fn make_lua(options: LuaOptions) -> Result { let lua = Lua::new_with(StdLib::ALL_SAFE, options)?; - let rust_panic_function = - lua.create_function(|_, msg: Option| -> Result<()> { - if let Some(msg) = msg { - panic!("{}", msg) - } - panic!("rust panic") - })?; - lua.globals() - .set("rust_panic_function", rust_panic_function)?; + let rust_panic_function = lua.create_function(|_, msg: Option| -> Result<()> { + if let Some(msg) = msg { + panic!("{}", msg) + } + panic!("rust panic") + })?; + lua.globals().set("rust_panic_function", rust_panic_function)?; Ok(lua) } @@ -538,12 +518,7 @@ fn test_num_conversion() -> Result<()> { assert_eq!(lua.load("1.0").eval::()?, 1.0); #[cfg(any(feature = "lua54", feature = "lua53"))] assert_eq!(lua.load("1.0").eval::()?, "1.0"); - #[cfg(any( - feature = "lua52", - feature = "lua51", - feature = "luajit", - feature = "luau" - ))] + #[cfg(any(feature = "lua52", feature = "lua51", feature = "luajit", feature = "luau"))] assert_eq!(lua.load("1.0").eval::()?, "1"); assert_eq!(lua.load("1.5").eval::()?, 1); @@ -620,12 +595,7 @@ fn test_pcall_xpcall() -> Result<()> { assert_eq!(globals.get::<_, String>("pcall_error")?, "testerror"); assert_eq!(globals.get::<_, bool>("xpcall_statusr")?, false); - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit"))] assert_eq!( globals.get::<_, std::string::String>("xpcall_error")?, "testerror" @@ -645,9 +615,7 @@ fn test_pcall_xpcall() -> Result<()> { "#, ) .exec()?; - let _ = globals - .get::<_, Function>("xpcall_recursion")? - .call::<_, ()>(()); + let _ = globals.get::<_, Function>("xpcall_recursion")?.call::<_, ()>(()); Ok(()) } @@ -901,10 +869,7 @@ fn test_application_data() -> Result<()> { f.call(())?; assert_eq!(*lua.app_data_ref::<&str>().unwrap(), "test4"); - assert_eq!( - *lua.app_data_ref::>().unwrap(), - vec!["test2", "test3"] - ); + assert_eq!(*lua.app_data_ref::>().unwrap(), vec!["test2", "test3"]); lua.remove_app_data::>(); assert!(matches!(lua.app_data_ref::>(), None)); @@ -919,9 +884,7 @@ fn test_recursion() -> Result<()> { let f = lua.create_function(move |lua, i: i32| { if i < 64 { - lua.globals() - .get::<_, Function>("f")? - .call::<_, ()>(i + 1)?; + lua.globals().get::<_, Function>("f")?.call::<_, ()>(i + 1)?; } Ok(()) })?; @@ -961,8 +924,7 @@ fn test_too_many_arguments() -> Result<()> { fn test_too_many_recursions() -> Result<()> { let lua = Lua::new(); - let f = lua - .create_function(move |lua, ()| lua.globals().get::<_, Function>("f")?.call::<_, ()>(()))?; + let f = lua.create_function(move |lua, ()| lua.globals().get::<_, Function>("f")?.call::<_, ()>(()))?; lua.globals().set("f", &f)?; assert!(f.call::<_, ()>(()).is_err()); @@ -985,9 +947,7 @@ fn test_too_many_binds() -> Result<()> { let concat = globals.get::<_, Function>("f")?; assert!(concat.bind(Variadic::from_iter(1..1000000)).is_err()); - assert!(concat - .call::<_, ()>(Variadic::from_iter(1..1000000)) - .is_err()); + assert!(concat.call::<_, ()>(Variadic::from_iter(1..1000000)).is_err()); Ok(()) } @@ -1038,10 +998,7 @@ fn test_large_args() -> Result<()> { ) .eval()?; - assert_eq!( - f.call::<_, usize>((0..100).collect::>())?, - 4950 - ); + assert_eq!(f.call::<_, usize>((0..100).collect::>())?, 4950); Ok(()) } @@ -1110,12 +1067,7 @@ fn test_context_thread() -> Result<()> { ) .into_function()?; - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] f.call::<_, ()>(lua.current_thread())?; #[cfg(any( @@ -1154,10 +1106,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::<_, String>("version")?.to_str()?.contains("LuaJIT")); Ok(()) } diff --git a/tests/userdata.rs b/tests/userdata.rs index ac026f90..491f1bb3 100644 --- a/tests/userdata.rs +++ b/tests/userdata.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use std::sync::atomic::{AtomicI64, Ordering}; use mlua::{ - AnyUserData, AnyUserDataExt, Error, ExternalError, Function, Lua, MetaMethod, Nil, Result, - String, UserData, UserDataFields, UserDataMethods, UserDataRef, Value, Variadic, + AnyUserData, AnyUserDataExt, Error, ExternalError, Function, Lua, MetaMethod, Nil, Result, String, + UserData, UserDataFields, UserDataMethods, UserDataRef, Value, Variadic, }; #[test] @@ -118,15 +118,11 @@ fn test_metamethods() -> Result<()> { methods.add_method("get", |_, data, ()| Ok(data.0)); methods.add_meta_function( MetaMethod::Add, - |_, (lhs, rhs): (UserDataRef, UserDataRef)| { - Ok(MyUserData(lhs.0 + rhs.0)) - }, + |_, (lhs, rhs): (UserDataRef, UserDataRef)| Ok(MyUserData(lhs.0 + rhs.0)), ); methods.add_meta_function( MetaMethod::Sub, - |_, (lhs, rhs): (UserDataRef, UserDataRef)| { - Ok(MyUserData(lhs.0 - rhs.0)) - }, + |_, (lhs, rhs): (UserDataRef, UserDataRef)| Ok(MyUserData(lhs.0 - rhs.0)), ); methods.add_meta_function( MetaMethod::Eq, @@ -139,22 +135,16 @@ fn test_metamethods() -> Result<()> { Err("no such custom index".into_lua_err()) } }); - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] methods.add_meta_method(MetaMethod::Pairs, |lua, data, ()| { use std::iter::FromIterator; - let stateless_iter = - lua.create_function(|_, (data, i): (UserDataRef, i64)| { - let i = i + 1; - if i <= data.0 { - return Ok(mlua::Variadic::from_iter(vec![i, i])); - } - return Ok(mlua::Variadic::new()); - })?; + let stateless_iter = lua.create_function(|_, (data, i): (UserDataRef, i64)| { + let i = i + 1; + if i <= data.0 { + return Ok(mlua::Variadic::from_iter(vec![i, i])); + } + return Ok(mlua::Variadic::new()); + })?; Ok((stateless_iter, data.clone(), 0)) }); } @@ -172,12 +162,7 @@ fn test_metamethods() -> Result<()> { 10 ); - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] let pairs_it = lua .load( r#" @@ -202,12 +187,7 @@ fn test_metamethods() -> Result<()> { assert_eq!(lua.load("userdata2.inner").eval::()?, 3); assert!(lua.load("userdata2.nonexist_field").eval::<()>().is_err()); - #[cfg(any( - feature = "lua54", - feature = "lua53", - feature = "lua52", - feature = "luajit52" - ))] + #[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52", feature = "luajit52"))] assert_eq!(pairs_it.call::<_, i64>(())?, 28); let userdata2: Value = globals.get("userdata2")?; @@ -454,9 +434,7 @@ fn test_functions() -> Result<()> { impl UserData for MyUserData { fn add_methods<'a, M: UserDataMethods<'a, Self>>(methods: &mut M) { - methods.add_function("get_value", |_, ud: AnyUserData| { - Ok(ud.borrow::()?.0) - }); + methods.add_function("get_value", |_, ud: AnyUserData| Ok(ud.borrow::()?.0)); methods.add_function_mut("set_value", |_, (ud, value): (AnyUserData, i64)| { ud.borrow_mut::()?.0 = value; Ok(()) @@ -517,8 +495,7 @@ fn test_fields() -> Result<()> { // Use userdata "uservalue" storage fields.add_field_function_get("uval", |_, ud| ud.user_value::>()); - fields - .add_field_function_set("uval", |_, ud, s| ud.set_user_value::>(s)); + fields.add_field_function_set("uval", |_, ud, s| ud.set_user_value::>(s)); fields.add_meta_field(MetaMethod::Index, HashMap::from([("f", 321)])); fields.add_meta_field_with(MetaMethod::NewIndex, |lua| { @@ -597,8 +574,7 @@ fn test_metatable() -> Result<()> { let lua = Lua::new(); let globals = lua.globals(); globals.set("ud", MyUserData)?; - lua.load(r#"assert(ud:my_type_name() == "MyUserData")"#) - .exec()?; + lua.load(r#"assert(ud:my_type_name() == "MyUserData")"#).exec()?; #[cfg(any(feature = "lua54", feature = "lua53", feature = "luau"))] lua.load(r#"assert(tostring(ud):sub(1, 11) == "MyUserData:")"#) @@ -654,10 +630,7 @@ fn test_metatable() -> Result<()> { let ud = lua.create_userdata(MyUserData3)?; let metatable = ud.get_metatable()?; - assert_eq!( - metatable.get::(MetaMethod::Type)?.to_str()?, - "CustomName" - ); + assert_eq!(metatable.get::(MetaMethod::Type)?.to_str()?, "CustomName"); Ok(()) } @@ -740,8 +713,7 @@ fn test_any_userdata_wrap() -> Result<()> { reg.add_method("get", |_, this, ()| Ok(this.clone())); })?; - lua.globals() - .set("s", AnyUserData::wrap("hello".to_string()))?; + lua.globals().set("s", AnyUserData::wrap("hello".to_string()))?; lua.load( r#" assert(s:get() == "hello") @@ -854,8 +826,7 @@ fn test_userdata_derive() -> Result<()> { reg.add_function("val", |_, this: MyUserData| Ok(this.0)); })?; - lua.globals() - .set("ud", AnyUserData::wrap(MyUserData(123)))?; + lua.globals().set("ud", AnyUserData::wrap(MyUserData(123)))?; lua.load("assert(ud:val() == 123)").exec()?; // More complex struct where generics and where clause @@ -869,8 +840,7 @@ fn test_userdata_derive() -> Result<()> { reg.add_function("val", |_, this: MyUserData2<'static, i32>| Ok(*this.0)); })?; - lua.globals() - .set("ud", AnyUserData::wrap(MyUserData2(&321)))?; + lua.globals().set("ud", AnyUserData::wrap(MyUserData2(&321)))?; lua.load("assert(ud:val() == 321)").exec()?; Ok(()) diff --git a/tests/value.rs b/tests/value.rs index 7b060258..024c5c59 100644 --- a/tests/value.rs +++ b/tests/value.rs @@ -111,10 +111,7 @@ fn test_value_to_string() -> Result<()> { Value::Vector(mlua::Vector::new(10.0, 11.1, 12.2, 13.3)).to_string()?, "vector(10, 11.1, 12.2, 13.3)" ); - assert_eq!( - Value::String(lua.create_string("hello")?).to_string()?, - "hello" - ); + assert_eq!(Value::String(lua.create_string("hello")?).to_string()?, "hello"); let table: Value = lua.load("{}").eval()?; assert!(table.to_string()?.starts_with("table:")); @@ -189,9 +186,7 @@ fn test_value_conversions() -> Result<()> { assert_eq!(Value::Number(1.23).as_f64(), Some(1.23f64)); assert!(Value::String(lua.create_string("hello")?).is_string()); assert_eq!( - Value::String(lua.create_string("hello")?) - .as_string() - .unwrap(), + Value::String(lua.create_string("hello")?).as_string().unwrap(), "hello" ); assert_eq!( @@ -207,11 +202,9 @@ fn test_value_conversions() -> Result<()> { assert!(Value::Table(lua.create_table()?).is_table()); assert!(Value::Table(lua.create_table()?).as_table().is_some()); assert!(Value::Function(lua.create_function(|_, ()| Ok(())).unwrap()).is_function()); - assert!( - Value::Function(lua.create_function(|_, ()| Ok(())).unwrap()) - .as_function() - .is_some() - ); + assert!(Value::Function(lua.create_function(|_, ()| Ok(())).unwrap()) + .as_function() + .is_some()); assert!(Value::Thread(lua.create_thread(lua.load("function() end").eval()?)?).is_thread()); assert!( Value::Thread(lua.create_thread(lua.load("function() end").eval()?)?)