Skip to content

Commit

Permalink
Prepare for Rust 2024 edition (see rust-lang/rust#123748)
Browse files Browse the repository at this point in the history
Replace `IntoLua(Multi)` generic with positional arg (impl trait) where possible
This allow to shorten syntax from `a.get::<_, T>` to `a.get::<T>`
  • Loading branch information
khvzak committed Jul 31, 2024
1 parent b7d170a commit 3641c98
Show file tree
Hide file tree
Showing 31 changed files with 378 additions and 413 deletions.
18 changes: 9 additions & 9 deletions benches/benchmark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn table_get_set(c: &mut Criterion) {
.enumerate()
{
table.raw_set(s, i).unwrap();
assert_eq!(table.raw_get::<_, usize>(s).unwrap(), i);
assert_eq!(table.raw_get::<usize>(s).unwrap(), i);
}
},
BatchSize::SmallInput,
Expand Down Expand Up @@ -153,7 +153,7 @@ fn function_call_sum(c: &mut Criterion) {
b.iter_batched(
|| collect_gc_twice(&lua),
|_| {
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
assert_eq!(sum.call::<i64>((10, 20, 30)).unwrap(), 0);
},
BatchSize::SmallInput,
);
Expand All @@ -172,7 +172,7 @@ fn function_call_lua_sum(c: &mut Criterion) {
b.iter_batched(
|| collect_gc_twice(&lua),
|_| {
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
assert_eq!(sum.call::<i64>((10, 20, 30)).unwrap(), 0);
},
BatchSize::SmallInput,
);
Expand All @@ -195,7 +195,7 @@ fn function_call_concat(c: &mut Criterion) {
},
|i| {
assert_eq!(
concat.call::<_, LuaString>(("num:", i)).unwrap(),
concat.call::<LuaString>(("num:", i)).unwrap(),
format!("num:{i}")
);
},
Expand All @@ -221,7 +221,7 @@ fn function_call_lua_concat(c: &mut Criterion) {
},
|i| {
assert_eq!(
concat.call::<_, LuaString>(("num:", i)).unwrap(),
concat.call::<LuaString>(("num:", i)).unwrap(),
format!("num:{i}")
);
},
Expand All @@ -246,7 +246,7 @@ fn function_async_call_sum(c: &mut Criterion) {
b.to_async(rt).iter_batched(
|| collect_gc_twice(&lua),
|_| async {
assert_eq!(sum.call_async::<_, i64>((10, 20, 30)).await.unwrap(), 0);
assert_eq!(sum.call_async::<i64>((10, 20, 30)).await.unwrap(), 0);
},
BatchSize::SmallInput,
);
Expand Down Expand Up @@ -319,7 +319,7 @@ fn userdata_call_index(c: &mut Criterion) {
b.iter_batched(
|| collect_gc_twice(&lua),
|_| {
assert_eq!(index.call::<_, LuaString>(&ud).unwrap(), "test");
assert_eq!(index.call::<LuaString>(&ud).unwrap(), "test");
},
BatchSize::SmallInput,
);
Expand Down Expand Up @@ -349,7 +349,7 @@ fn userdata_call_method(c: &mut Criterion) {
i.fetch_add(1, Ordering::Relaxed)
},
|i| {
assert_eq!(method.call::<_, usize>((&ud, i)).unwrap(), 123 + i);
assert_eq!(method.call::<usize>((&ud, i)).unwrap(), 123 + i);
},
BatchSize::SmallInput,
);
Expand Down Expand Up @@ -384,7 +384,7 @@ fn userdata_async_call_method(c: &mut Criterion) {
(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,
);
Expand Down
4 changes: 2 additions & 2 deletions benches/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn encode_json(c: &mut Criterion) {
b.iter_batched(
|| collect_gc_twice(&lua),
|_| {
encode.call::<_, LuaString>(&table).unwrap();
encode.call::<LuaString>(&table).unwrap();
},
BatchSize::SmallInput,
);
Expand Down Expand Up @@ -69,7 +69,7 @@ fn decode_json(c: &mut Criterion) {
b.iter_batched(
|| collect_gc_twice(&lua),
|_| {
decode.call::<_, LuaTable>(json).unwrap();
decode.call::<LuaTable>(json).unwrap();
},
BatchSize::SmallInput,
);
Expand Down
8 changes: 4 additions & 4 deletions examples/async_http_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,13 @@ impl hyper::service::Service<Request<Incoming>> for Svc {
let handler = self.handler.clone();
let lua_req = LuaRequest(self.peer_addr, req);
Box::pin(async move {
match handler.call_async::<_, Table>(lua_req).await {
match handler.call_async::<Table>(lua_req).await {
Ok(lua_resp) => {
let status = lua_resp.get::<_, Option<u16>>("status")?.unwrap_or(200);
let status = lua_resp.get::<Option<u16>>("status")?.unwrap_or(200);
let mut resp = Response::builder().status(status);

// Set headers
if let Some(headers) = lua_resp.get::<_, Option<Table>>("headers")? {
if let Some(headers) = lua_resp.get::<Option<Table>>("headers")? {
for pair in headers.pairs::<String, LuaString>() {
let (h, v) = pair?;
resp = resp.header(&h, &*v.as_bytes());
Expand All @@ -62,7 +62,7 @@ impl hyper::service::Service<Request<Incoming>> for Svc {

// Set body
let body = lua_resp
.get::<_, Option<LuaString>>("body")?
.get::<Option<LuaString>>("body")?
.map(|b| Full::new(Bytes::copy_from_slice(&b.as_bytes())).boxed())
.unwrap_or_else(|| Empty::<Bytes>::new().boxed());

Expand Down
2 changes: 1 addition & 1 deletion examples/async_tcp_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async fn run_server(handler: Function) -> io::Result<()> {
let handler = handler.clone();
tokio::task::spawn(async move {
let stream = LuaTcpStream(stream);
if let Err(err) = handler.call_async::<_, ()>(stream).await {
if let Err(err) = handler.call_async::<()>(stream).await {
eprintln!("{}", err);
}
});
Expand Down
12 changes: 6 additions & 6 deletions examples/guided_tour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ fn main() -> Result<()> {
globals.set("string_var", "hello")?;
globals.set("int_var", 42)?;

assert_eq!(globals.get::<_, String>("string_var")?, "hello");
assert_eq!(globals.get::<_, i64>("int_var")?, 42);
assert_eq!(globals.get::<String>("string_var")?, "hello");
assert_eq!(globals.get::<i64>("int_var")?, 42);

// You can load and evaluate Lua code. The returned type of `Lua::load` is a builder
// that allows you to change settings before running Lua code. Here, we are using it to set
Expand All @@ -32,7 +32,7 @@ fn main() -> Result<()> {
)
.set_name("example code")
.exec()?;
assert_eq!(globals.get::<_, String>("global")?, "foobar");
assert_eq!(globals.get::<String>("global")?, "foobar");

assert_eq!(lua.load("1 + 1").eval::<i32>()?, 2);
assert_eq!(lua.load("false == false").eval::<bool>()?, true);
Expand Down Expand Up @@ -85,16 +85,16 @@ fn main() -> Result<()> {
// You can load Lua functions

let print: Function = globals.get("print")?;
print.call::<_, ()>("hello from rust")?;
print.call::<()>("hello from rust")?;

// This API generally handles variadic using tuples. This is one way to call a function with
// multiple parameters:

print.call::<_, ()>(("hello", "again", "from", "rust"))?;
print.call::<()>(("hello", "again", "from", "rust"))?;

// But, you can also pass variadic arguments with the `Variadic` type.

print.call::<_, ()>(Variadic::from_iter(
print.call::<()>(Variadic::from_iter(
["hello", "yet", "again", "from", "rust"].iter().cloned(),
))?;

Expand Down
9 changes: 4 additions & 5 deletions src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ impl<'a> Chunk<'a> {
/// All global variables (including the standard library!) are looked up in `_ENV`, so it may be
/// necessary to populate the environment in order for scripts using custom environments to be
/// useful.
pub fn set_environment<V: IntoLua>(mut self, env: V) -> Self {
pub fn set_environment(mut self, env: impl IntoLua) -> Self {
let lua = self.lua.lock();
let lua = lua.lua();
self.env = env
Expand Down Expand Up @@ -343,7 +343,7 @@ impl<'a> Chunk<'a> {
///
/// This is equivalent to calling the chunk function with no arguments and no return values.
pub fn exec(self) -> Result<()> {
self.call::<_, ()>(())?;
self.call::<()>(())?;
Ok(())
}

Expand Down Expand Up @@ -404,7 +404,7 @@ impl<'a> Chunk<'a> {
/// Load the chunk function and call it with the given arguments.
///
/// This is equivalent to `into_function` and calling the resulting function.
pub fn call<A: IntoLuaMulti, R: FromLuaMulti>(self, args: A) -> Result<R> {
pub fn call<R: FromLuaMulti>(self, args: impl IntoLuaMulti) -> Result<R> {
self.into_function()?.call(args)
}

Expand All @@ -417,9 +417,8 @@ impl<'a> Chunk<'a> {
/// [`call`]: #method.call
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub async fn call_async<A, R>(self, args: A) -> Result<R>
pub async fn call_async<R>(self, args: impl IntoLuaMulti) -> Result<R>
where
A: IntoLuaMulti,
R: FromLuaMulti,
{
self.into_function()?.call_async(args).await
Expand Down
15 changes: 7 additions & 8 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl Function {
///
/// let tostring: Function = globals.get("tostring")?;
///
/// assert_eq!(tostring.call::<_, String>(123)?, "123");
/// assert_eq!(tostring.call::<String>(123)?, "123");
///
/// # Ok(())
/// # }
Expand All @@ -94,12 +94,12 @@ impl Function {
/// end
/// "#).eval()?;
///
/// assert_eq!(sum.call::<_, u32>((3, 4))?, 3 + 4);
/// assert_eq!(sum.call::<u32>((3, 4))?, 3 + 4);
///
/// # Ok(())
/// # }
/// ```
pub fn call<A: IntoLuaMulti, R: FromLuaMulti>(&self, args: A) -> Result<R> {
pub fn call<R: FromLuaMulti>(&self, args: impl IntoLuaMulti) -> Result<R> {
let lua = self.0.lua.lock();
let state = lua.state();
unsafe {
Expand Down Expand Up @@ -153,9 +153,8 @@ impl Function {
/// [`AsyncThread`]: crate::AsyncThread
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub fn call_async<A, R>(&self, args: A) -> impl Future<Output = Result<R>>
pub fn call_async<R>(&self, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
where
A: IntoLuaMulti,
R: FromLuaMulti,
{
let lua = self.0.lua.lock();
Expand Down Expand Up @@ -188,15 +187,15 @@ impl Function {
/// "#).eval()?;
///
/// let bound_a = sum.bind(1)?;
/// assert_eq!(bound_a.call::<_, u32>(2)?, 1 + 2);
/// assert_eq!(bound_a.call::<u32>(2)?, 1 + 2);
///
/// let bound_a_and_b = sum.bind(13)?.bind(57)?;
/// assert_eq!(bound_a_and_b.call::<_, u32>(())?, 13 + 57);
/// assert_eq!(bound_a_and_b.call::<u32>(())?, 13 + 57);
///
/// # Ok(())
/// # }
/// ```
pub fn bind<A: IntoLuaMulti>(&self, args: A) -> Result<Function> {
pub fn bind(&self, args: impl IntoLuaMulti) -> Result<Function> {
unsafe extern "C-unwind" fn args_wrapper_impl(state: *mut ffi::lua_State) -> c_int {
let nargs = ffi::lua_gettop(state);
let nbinds = ffi::lua_tointeger(state, ffi::lua_upvalueindex(1)) as c_int;
Expand Down
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@

// Deny warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show *any*
// warnings at all.
#![doc(test(attr(warn(warnings))))] // FIXME: Remove this when rust-lang/rust#123748 is fixed
#![cfg_attr(docsrs, feature(doc_cfg))]

#[macro_use]
Expand Down
4 changes: 2 additions & 2 deletions src/luau/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ fn lua_loader(lua: &Lua, modname: StdString) -> Result<Value> {
let key = lua.app_data_ref::<PackageKey>().unwrap();
lua.registry_value::<Table>(&key.0)
}?;
let search_path = package.get::<_, StdString>("path").unwrap_or_default();
let search_path = package.get::<StdString>("path").unwrap_or_default();

if let Some(file_path) = package_searchpath(&modname, &search_path, false) {
match fs::read(&file_path) {
Expand Down Expand Up @@ -222,7 +222,7 @@ fn dylib_loader(lua: &Lua, modname: StdString) -> Result<Value> {
let key = lua.app_data_ref::<PackageKey>().unwrap();
lua.registry_value::<Table>(&key.0)
}?;
let search_cpath = package.get::<_, StdString>("cpath").unwrap_or_default();
let search_cpath = package.get::<StdString>("cpath").unwrap_or_default();

let find_symbol = |lib: &Library| unsafe {
if let Ok(entry) = lib.get::<ffi::lua_CFunction>(format!("luaopen_{modname}\0").as_bytes()) {
Expand Down
17 changes: 7 additions & 10 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,11 @@ impl Lua {
///
/// lua.sandbox(true)?;
/// lua.load("var = 123").exec()?;
/// assert_eq!(lua.globals().get::<_, u32>("var")?, 123);
/// assert_eq!(lua.globals().get::<u32>("var")?, 123);
///
/// // Restore the global environment (clear changes made in sandbox)
/// lua.sandbox(false)?;
/// assert_eq!(lua.globals().get::<_, Option<u32>>("var")?, None);
/// assert_eq!(lua.globals().get::<Option<u32>>("var")?, None);
/// # Ok(())
/// # }
/// ```
Expand Down Expand Up @@ -1497,7 +1497,7 @@ impl Lua {

/// Converts a value that implements `IntoLua` into a `Value` instance.
#[inline]
pub fn pack<T: IntoLua>(&self, t: T) -> Result<Value> {
pub fn pack(&self, t: impl IntoLua) -> Result<Value> {
t.into_lua(self)
}

Expand All @@ -1509,7 +1509,7 @@ impl Lua {

/// Converts a value that implements `IntoLuaMulti` into a `MultiValue` instance.
#[inline]
pub fn pack_multi<T: IntoLuaMulti>(&self, t: T) -> Result<MultiValue> {
pub fn pack_multi(&self, t: impl IntoLuaMulti) -> Result<MultiValue> {
t.into_lua_multi(self)
}

Expand All @@ -1523,10 +1523,7 @@ impl Lua {
///
/// This value will be available to rust from all `Lua` instances which share the same main
/// state.
pub fn set_named_registry_value<T>(&self, name: &str, t: T) -> Result<()>
where
T: IntoLua,
{
pub fn set_named_registry_value(&self, name: &str, t: impl IntoLua) -> Result<()> {
let lua = self.lock();
let state = lua.state();
unsafe {
Expand Down Expand Up @@ -1575,7 +1572,7 @@ impl Lua {
/// Be warned, garbage collection of values held inside the registry is not automatic, see
/// [`RegistryKey`] for more details.
/// However, dropped [`RegistryKey`]s automatically reused to store new values.
pub fn create_registry_value<T: IntoLua>(&self, t: T) -> Result<RegistryKey> {
pub fn create_registry_value(&self, t: impl IntoLua) -> Result<RegistryKey> {
let lua = self.lock();
let state = lua.state();
unsafe {
Expand Down Expand Up @@ -1657,7 +1654,7 @@ impl Lua {
/// An identifier used in [`RegistryKey`] may possibly be changed to a new value.
///
/// See [`Lua::create_registry_value`] for more details.
pub fn replace_registry_value<T: IntoLua>(&self, key: &mut RegistryKey, t: T) -> Result<()> {
pub fn replace_registry_value(&self, key: &mut RegistryKey, t: impl IntoLua) -> Result<()> {
let lua = self.lock();
if !lua.owns_registry_value(key) {
return Err(Error::MismatchedRegistryKey);
Expand Down
9 changes: 4 additions & 5 deletions src/state/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::cell::{Cell, UnsafeCell};
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
use std::panic::resume_unwind;
use std::rc::Rc;
use std::result::Result as StdResult;
use std::sync::Arc;
use std::{mem, ptr};
Expand Down Expand Up @@ -362,7 +361,7 @@ impl RawLua {
callback_error_ext(state, extra, move |_| {
let hook_cb = (*extra).hook_callback.clone();
let hook_cb = mlua_expect!(hook_cb, "no hook callback set in hook_proc");
if Rc::strong_count(&hook_cb) > 2 {
if std::rc::Rc::strong_count(&hook_cb) > 2 {
return Ok(()); // Don't allow recursion
}
let rawlua = (*extra).raw_lua();
Expand All @@ -372,7 +371,7 @@ impl RawLua {
})
}

(*self.extra.get()).hook_callback = Some(Rc::new(callback));
(*self.extra.get()).hook_callback = Some(std::rc::Rc::new(callback));
(*self.extra.get()).hook_thread = state; // Mark for what thread the hook is set
ffi::lua_sethook(state, Some(hook_proc), triggers.mask(), triggers.count());
}
Expand Down Expand Up @@ -1198,12 +1197,12 @@ impl RawLua {
}

let lua = self.lua();
let coroutine = lua.globals().get::<_, Table>("coroutine")?;
let coroutine = lua.globals().get::<Table>("coroutine")?;

let env = lua.create_table_with_capacity(0, 3)?;
env.set("get_poll", get_poll)?;
// Cache `yield` function
env.set("yield", coroutine.get::<_, Function>("yield")?)?;
env.set("yield", coroutine.get::<Function>("yield")?)?;
unsafe {
env.set("unpack", lua.create_c_function(unpack)?)?;
}
Expand Down
Loading

0 comments on commit 3641c98

Please sign in to comment.