mirror of
https://github.com/mlua-rs/mlua
synced 2026-06-08 16:05:43 +00:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 806bd202d6 | |||
| a644049087 | |||
| ad31bed1db | |||
| 62f0bb97b0 | |||
| f67f8646ae | |||
| fa217d3706 | |||
| b62f2ee0f7 | |||
| 6e6c73e4c7 | |||
| 508517c45e | |||
| a79840afc9 | |||
| 39afe4c6f7 | |||
| 038cc5f974 | |||
| 59b14000f3 | |||
| 849206ef9d | |||
| 80fff4f2e7 | |||
| 9734146313 | |||
| 58be624222 | |||
| 3d43103431 | |||
| 5a22437d5f | |||
| 83c075c72b | |||
| 270b98a429 | |||
| 0ee3324462 | |||
| 8a9c4f0b15 | |||
| 34db5f985e | |||
| 020e8a78a8 | |||
| 3ca7b4942e | |||
| 1754226c74 | |||
| 3014c4d7a1 | |||
| 908f37656a | |||
| f4d783cb41 | |||
| f5982bc204 | |||
| e30b425224 | |||
| 512921404c | |||
| dfd82edc42 |
@@ -1,3 +1,22 @@
|
||||
## v0.9.7
|
||||
|
||||
- Implemented `IntoLua` for `RegistryKey`
|
||||
- Mark `__idiv` metamethod as available for luau
|
||||
- Added `Function::deep_clone()` method (Luau)
|
||||
- Added `SerializeOptions::detect_serde_json_arbitrary_precision` option
|
||||
- Added `Lua::create_buffer()` method (Luau)
|
||||
- Support serializing buffer type as a byte slice (Luau)
|
||||
- Perf: Implemented `push_into_stack`/`from_stack` for `Option<T>`
|
||||
- Added `Lua::create_ser_any_userdata()` method
|
||||
|
||||
## v0.9.6
|
||||
|
||||
- Added `to_pointer` function to `Function`/`Table`/`Thread`
|
||||
- Implemented `IntoLua` for `&Value`
|
||||
- Implemented `FromLua` for `RegistryKey`
|
||||
- Faster (~5%) table array traversal during serialization
|
||||
- Some performance improvements for bool/int types
|
||||
|
||||
## v0.9.5
|
||||
|
||||
- Minimal Luau updated to 0.609
|
||||
|
||||
+11
-9
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mlua"
|
||||
version = "0.9.5" # remember to update mlua_derive
|
||||
version = "0.9.7" # remember to update mlua_derive
|
||||
authors = ["Aleksandr Orlenko <zxteam@pm.me>", "kyren <catherine@kyju.org>"]
|
||||
rust-version = "1.71"
|
||||
edition = "2021"
|
||||
@@ -32,14 +32,14 @@ lua52 = ["ffi/lua52"]
|
||||
lua51 = ["ffi/lua51"]
|
||||
luajit = ["ffi/luajit"]
|
||||
luajit52 = ["luajit", "ffi/luajit52"]
|
||||
luau = ["ffi/luau", "libloading"]
|
||||
luau = ["ffi/luau", "dep:libloading"]
|
||||
luau-jit = ["luau", "ffi/luau-codegen"]
|
||||
luau-vector4 = ["luau", "ffi/luau-vector4"]
|
||||
vendored = ["ffi/vendored"]
|
||||
module = ["mlua_derive", "ffi/module"]
|
||||
async = ["futures-util"]
|
||||
module = ["dep:mlua_derive", "ffi/module"]
|
||||
async = ["dep:futures-util"]
|
||||
send = []
|
||||
serialize = ["serde", "erased-serde", "serde-value"]
|
||||
serialize = ["dep:serde", "dep:erased-serde", "dep:serde-value"]
|
||||
macros = ["mlua_derive/macros"]
|
||||
unstable = []
|
||||
|
||||
@@ -63,18 +63,20 @@ libloading = { version = "0.8", optional = true }
|
||||
[dev-dependencies]
|
||||
trybuild = "1.0"
|
||||
futures = "0.3.5"
|
||||
hyper = { version = "0.14", features = ["client", "server"] }
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
hyper = { version = "1.2", features = ["full"] }
|
||||
hyper-util = { version = "0.1.3", features = ["full"] }
|
||||
http-body-util = "0.1.1"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
tokio = { version = "1.0", features = ["macros", "rt", "time"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { version = "1.0", features = ["arbitrary_precision"] }
|
||||
maplit = "1.0"
|
||||
tempfile = "3"
|
||||
static_assertions = "1.0"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
criterion = { version = "0.5", features = ["async_tokio"] }
|
||||
rustyline = "13.0"
|
||||
rustyline = "14.0"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
|
||||
[[bench]]
|
||||
|
||||
@@ -84,6 +84,20 @@ This works using Lua [coroutines](https://www.lua.org/manual/5.3/manual.html#2.6
|
||||
- [HTTP Server](examples/async_http_server.rs)
|
||||
- [TCP Server](examples/async_tcp_server.rs)
|
||||
|
||||
|
||||
**shell command examples**:
|
||||
```shell
|
||||
# async http client (hyper)
|
||||
cargo run --example async_http_client --features=lua54,async,macros
|
||||
|
||||
# async http client (reqwest)
|
||||
cargo run --example async_http_reqwest --features=lua54,async,macros,serialize
|
||||
|
||||
# async http server
|
||||
cargo run --example async_http_server --features=lua54,async,macros
|
||||
curl -v http://localhost:3000
|
||||
```
|
||||
|
||||
### Serialization (serde) support
|
||||
|
||||
With `serialize` feature flag enabled, `mlua` allows you to serialize/deserialize any type that implements [`serde::Serialize`] and [`serde::Deserialize`] into/from [`mlua::Value`]. In addition `mlua` provides [`serde::Serialize`] trait implementation for it (including `UserData` support).
|
||||
@@ -119,7 +133,7 @@ Add to `Cargo.toml` :
|
||||
|
||||
``` toml
|
||||
[dependencies]
|
||||
mlua = { version = "0.9.1", features = ["lua54", "vendored"] }
|
||||
mlua = { version = "0.9.7", features = ["lua54", "vendored"] }
|
||||
```
|
||||
|
||||
`main.rs`
|
||||
@@ -154,7 +168,7 @@ Add to `Cargo.toml` :
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
mlua = { version = "0.9.1", features = ["lua54", "module"] }
|
||||
mlua = { version = "0.9.7", features = ["lua54", "module"] }
|
||||
```
|
||||
|
||||
`lib.rs` :
|
||||
|
||||
+189
-168
@@ -1,5 +1,7 @@
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::task;
|
||||
|
||||
@@ -10,10 +12,10 @@ fn collect_gc_twice(lua: &Lua) {
|
||||
lua.gc_collect().unwrap();
|
||||
}
|
||||
|
||||
fn create_table(c: &mut Criterion) {
|
||||
fn table_create_empty(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [table empty]", |b| {
|
||||
c.bench_function("table [create empty]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
@@ -24,35 +26,33 @@ fn create_table(c: &mut Criterion) {
|
||||
});
|
||||
}
|
||||
|
||||
fn create_array(c: &mut Criterion) {
|
||||
fn table_create_array(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [array] 10", |b| {
|
||||
c.bench_function("table [create array]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
let table = lua.create_table().unwrap();
|
||||
for i in 1..=10 {
|
||||
table.set(i, i).unwrap();
|
||||
}
|
||||
lua.create_sequence_from(1..=10).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn create_string_table(c: &mut Criterion) {
|
||||
fn table_create_hash(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [table string] 10", |b| {
|
||||
c.bench_function("table [create hash]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
let table = lua.create_table().unwrap();
|
||||
for &s in &["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] {
|
||||
let s = lua.create_string(s).unwrap();
|
||||
table.set(s.clone(), s).unwrap();
|
||||
}
|
||||
lua.create_table_from(
|
||||
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
|
||||
.into_iter()
|
||||
.map(|s| (s, s)),
|
||||
)
|
||||
.unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -62,17 +62,15 @@ fn create_string_table(c: &mut Criterion) {
|
||||
fn table_get_set(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
let table = lua.create_table().unwrap();
|
||||
|
||||
c.bench_function("table raw_get and raw_set [10]", |b| {
|
||||
c.bench_function("table [get and set]", |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
table.clear().unwrap();
|
||||
lua.create_table().unwrap()
|
||||
},
|
||||
|_| {
|
||||
for (i, &s) in ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
|
||||
.iter()
|
||||
|table| {
|
||||
for (i, s) in ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
table.raw_set(s, i).unwrap();
|
||||
@@ -87,7 +85,7 @@ fn table_get_set(c: &mut Criterion) {
|
||||
fn table_traversal_pairs(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("table traversal [pairs]", |b| {
|
||||
c.bench_function("table [traversal pairs]", |b| {
|
||||
b.iter_batched(
|
||||
|| lua.globals(),
|
||||
|globals| {
|
||||
@@ -103,7 +101,7 @@ fn table_traversal_pairs(c: &mut Criterion) {
|
||||
fn table_traversal_for_each(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("table traversal [for_each]", |b| {
|
||||
c.bench_function("table [traversal for_each]", |b| {
|
||||
b.iter_batched(
|
||||
|| lua.globals(),
|
||||
|globals| globals.for_each::<String, LuaValue>(|_k, _v| Ok(())),
|
||||
@@ -117,7 +115,7 @@ fn table_traversal_sequence(c: &mut Criterion) {
|
||||
|
||||
let table = lua.create_sequence_from(1..1000).unwrap();
|
||||
|
||||
c.bench_function("table traversal [sequence]", |b| {
|
||||
c.bench_function("table [traversal sequence]", |b| {
|
||||
b.iter_batched(
|
||||
|| table.clone(),
|
||||
|table| {
|
||||
@@ -130,236 +128,255 @@ fn table_traversal_sequence(c: &mut Criterion) {
|
||||
});
|
||||
}
|
||||
|
||||
fn create_function(c: &mut Criterion) {
|
||||
fn function_create(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [function] 10", |b| {
|
||||
c.bench_function("function [create Rust]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
for i in 0..10 {
|
||||
lua.create_function(move |_, ()| Ok(i)).unwrap();
|
||||
}
|
||||
lua.create_function(|_, ()| Ok(123)).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_lua_function(c: &mut Criterion) {
|
||||
fn function_call_sum(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("call Lua function [sum] 3 10", |b| {
|
||||
b.iter_batched_ref(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function(a, b, c) return a + b + c end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
},
|
||||
|function| {
|
||||
for i in 0..10 {
|
||||
let _result: i64 = function.call((i, i + 1, i + 2)).unwrap();
|
||||
}
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_sum_callback(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
let callback = lua
|
||||
.create_function(|_, (a, b, c): (i64, i64, i64)| Ok(a + b + c))
|
||||
let sum = lua
|
||||
.create_function(|_, (a, b, c): (i64, i64, i64)| Ok(a + b - c))
|
||||
.unwrap();
|
||||
lua.globals().set("callback", callback).unwrap();
|
||||
|
||||
c.bench_function("call Rust callback [sum] 3 10", |b| {
|
||||
b.iter_batched_ref(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do callback(i, i+1, i+2) end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
},
|
||||
|function| {
|
||||
function.call::<_, ()>(()).unwrap();
|
||||
c.bench_function("function [call Rust sum]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_async_sum_callback(c: &mut Criterion) {
|
||||
let options = LuaOptions::new().thread_pool_size(1024);
|
||||
let lua = Lua::new_with(LuaStdLib::ALL_SAFE, options).unwrap();
|
||||
let callback = lua
|
||||
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move {
|
||||
task::yield_now().await;
|
||||
Ok(a + b + c)
|
||||
})
|
||||
.unwrap();
|
||||
lua.globals().set("callback", callback).unwrap();
|
||||
|
||||
c.bench_function("call async Rust callback [sum] 3 10", |b| {
|
||||
let rt = Runtime::new().unwrap();
|
||||
b.to_async(rt).iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do callback(i, i+1, i+2) end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
},
|
||||
|function| async move {
|
||||
function.call_async::<_, ()>(()).await.unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_concat_callback(c: &mut Criterion) {
|
||||
fn function_call_lua_sum(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
let callback = lua
|
||||
|
||||
let sum = lua
|
||||
.load("function(a, b, c) return a + b - c end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
|
||||
c.bench_function("function [call Lua sum]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(sum.call::<_, i64>((10, 20, 30)).unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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()?))
|
||||
})
|
||||
.unwrap();
|
||||
lua.globals().set("callback", callback).unwrap();
|
||||
let i = AtomicUsize::new(0);
|
||||
|
||||
c.bench_function("call Rust callback [concat string] 10", |b| {
|
||||
b.iter_batched_ref(
|
||||
c.bench_function("function [call Rust concat string]", |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do callback('a', tostring(i)) end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|function| {
|
||||
function.call::<_, ()>(()).unwrap();
|
||||
|i| {
|
||||
assert_eq!(
|
||||
concat.call::<_, LuaString>(("num:", i)).unwrap(),
|
||||
format!("num:{i}")
|
||||
);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn create_registry_values(c: &mut Criterion) {
|
||||
fn function_call_lua_concat(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [registry value] 10", |b| {
|
||||
let concat = lua
|
||||
.load("function(a, b) return a..b end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
let i = AtomicUsize::new(0);
|
||||
|
||||
c.bench_function("function [call Lua concat string]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
for _ in 0..10 {
|
||||
lua.create_registry_value(lua.pack(true).unwrap()).unwrap();
|
||||
}
|
||||
lua.expire_registry_values();
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|i| {
|
||||
assert_eq!(
|
||||
concat.call::<_, LuaString>(("num:", i)).unwrap(),
|
||||
format!("num:{i}")
|
||||
);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn create_userdata(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
fn function_async_call_sum(c: &mut Criterion) {
|
||||
let options = LuaOptions::new().thread_pool_size(1024);
|
||||
let lua = Lua::new_with(LuaStdLib::ALL_SAFE, options).unwrap();
|
||||
|
||||
let sum = lua
|
||||
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move {
|
||||
task::yield_now().await;
|
||||
Ok(a + b - c)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
c.bench_function("function [async call Rust sum]", |b| {
|
||||
let rt = Runtime::new().unwrap();
|
||||
b.to_async(rt).iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| async {
|
||||
assert_eq!(sum.call_async::<_, i64>((10, 20, 30)).await.unwrap(), 0);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn registry_value_create(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
lua.gc_stop();
|
||||
|
||||
c.bench_function("registry value [create]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| lua.create_registry_value("hello").unwrap(),
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn userdata_create(c: &mut Criterion) {
|
||||
struct UserData(#[allow(unused)] i64);
|
||||
impl LuaUserData for UserData {}
|
||||
|
||||
let lua = Lua::new();
|
||||
|
||||
c.bench_function("create [table userdata] 10", |b| {
|
||||
c.bench_function("userdata [create]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
let table: LuaTable = lua.create_table().unwrap();
|
||||
for i in 1..11 {
|
||||
table.set(i, UserData(i)).unwrap();
|
||||
}
|
||||
lua.create_userdata(UserData(123)).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_userdata_index(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
fn userdata_call_index(c: &mut Criterion) {
|
||||
struct UserData(#[allow(unused)] i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_meta_method(LuaMetaMethod::Index, move |_, _, index: String| Ok(index));
|
||||
methods.add_meta_method(LuaMetaMethod::Index, move |_, _, key: LuaString| Ok(key));
|
||||
}
|
||||
}
|
||||
|
||||
let lua = Lua::new();
|
||||
lua.globals().set("userdata", UserData(10)).unwrap();
|
||||
let ud = lua.create_userdata(UserData(123)).unwrap();
|
||||
let index = lua
|
||||
.load("function(ud) return ud.test end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
|
||||
c.bench_function("call [userdata index] 10", |b| {
|
||||
b.iter_batched_ref(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do local v = userdata.test end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
},
|
||||
|function| {
|
||||
function.call::<_, ()>(()).unwrap();
|
||||
c.bench_function("userdata [call index]", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
assert_eq!(index.call::<_, LuaString>(&ud).unwrap(), "test");
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_userdata_method(c: &mut Criterion) {
|
||||
fn userdata_call_method(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_method("method", |_, this, ()| Ok(this.0));
|
||||
methods.add_method("add", |_, this, i: i64| Ok(this.0 + i));
|
||||
}
|
||||
}
|
||||
|
||||
let lua = Lua::new();
|
||||
lua.globals().set("userdata", UserData(10)).unwrap();
|
||||
let ud = lua.create_userdata(UserData(123)).unwrap();
|
||||
let method = lua
|
||||
.load("function(ud, i) return ud:add(i) end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
let i = AtomicUsize::new(0);
|
||||
|
||||
c.bench_function("call [userdata method] 10", |b| {
|
||||
b.iter_batched_ref(
|
||||
c.bench_function("userdata [call method]", |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do userdata:method() end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
i.fetch_add(1, Ordering::Relaxed)
|
||||
},
|
||||
|function| {
|
||||
function.call::<_, ()>(()).unwrap();
|
||||
|i| {
|
||||
assert_eq!(method.call::<_, usize>((&ud, i)).unwrap(), 123 + i);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn call_async_userdata_method(c: &mut Criterion) {
|
||||
struct UserData(String);
|
||||
|
||||
fn userdata_async_call_method(c: &mut Criterion) {
|
||||
struct UserData(i64);
|
||||
impl LuaUserData for UserData {
|
||||
fn add_methods<'lua, M: LuaUserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_async_method("method", |_, this, ()| async move { Ok(this.0.clone()) });
|
||||
methods.add_async_method("add", |_, this, i: i64| async move {
|
||||
task::yield_now().await;
|
||||
Ok(this.0 + i)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let options = LuaOptions::new().thread_pool_size(1024);
|
||||
let lua = Lua::new_with(LuaStdLib::ALL_SAFE, options).unwrap();
|
||||
lua.globals()
|
||||
.set("userdata", UserData("hello".to_string()))
|
||||
let ud = lua.create_userdata(UserData(123)).unwrap();
|
||||
let method = lua
|
||||
.load("function(ud, i) return ud:add(i) end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap();
|
||||
let i = AtomicUsize::new(0);
|
||||
|
||||
c.bench_function("call async [userdata method] 10", |b| {
|
||||
c.bench_function("userdata [async call method] 10", |b| {
|
||||
let rt = Runtime::new().unwrap();
|
||||
b.to_async(rt).iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load("function() for i = 1,10 do userdata:method() end end")
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
(
|
||||
method.clone(),
|
||||
ud.clone(),
|
||||
i.fetch_add(1, Ordering::Relaxed),
|
||||
)
|
||||
},
|
||||
|function| async move {
|
||||
function.call_async::<_, ()>(()).await.unwrap();
|
||||
|(method, ud, i)| async move {
|
||||
assert_eq!(
|
||||
method.call_async::<_, usize>((ud, i)).await.unwrap(),
|
||||
123 + i
|
||||
);
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -369,27 +386,31 @@ fn call_async_userdata_method(c: &mut Criterion) {
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = Criterion::default()
|
||||
.sample_size(300)
|
||||
.sample_size(500)
|
||||
.measurement_time(Duration::from_secs(10))
|
||||
.noise_threshold(0.02);
|
||||
targets =
|
||||
create_table,
|
||||
create_array,
|
||||
create_string_table,
|
||||
table_create_empty,
|
||||
table_create_array,
|
||||
table_create_hash,
|
||||
table_get_set,
|
||||
table_traversal_pairs,
|
||||
table_traversal_for_each,
|
||||
table_traversal_sequence,
|
||||
create_function,
|
||||
call_lua_function,
|
||||
call_sum_callback,
|
||||
call_async_sum_callback,
|
||||
call_concat_callback,
|
||||
create_registry_values,
|
||||
create_userdata,
|
||||
call_userdata_index,
|
||||
call_userdata_method,
|
||||
call_async_userdata_method,
|
||||
|
||||
function_create,
|
||||
function_call_sum,
|
||||
function_call_lua_sum,
|
||||
function_call_concat,
|
||||
function_call_lua_concat,
|
||||
function_async_call_sum,
|
||||
|
||||
registry_value_create,
|
||||
|
||||
userdata_create,
|
||||
userdata_call_index,
|
||||
userdata_call_method,
|
||||
userdata_async_call_method,
|
||||
}
|
||||
|
||||
criterion_main!(benches);
|
||||
|
||||
+59
-33
@@ -1,6 +1,7 @@
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
use std::time::Duration;
|
||||
|
||||
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
|
||||
|
||||
use mlua::prelude::*;
|
||||
|
||||
fn collect_gc_twice(lua: &Lua) {
|
||||
@@ -8,43 +9,67 @@ fn collect_gc_twice(lua: &Lua) {
|
||||
lua.gc_collect().unwrap();
|
||||
}
|
||||
|
||||
fn serialize_json(c: &mut Criterion) {
|
||||
fn encode_json(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
lua.globals()
|
||||
.set(
|
||||
"encode",
|
||||
LuaFunction::wrap(|_, t: LuaValue| Ok(serde_json::to_string(&t).unwrap())),
|
||||
let encode = lua
|
||||
.create_function(|_, t: LuaValue| Ok(serde_json::to_string(&t).unwrap()))
|
||||
.unwrap();
|
||||
let table = lua
|
||||
.load(
|
||||
r#"{
|
||||
name = "Clark Kent",
|
||||
address = {
|
||||
city = "Smallville",
|
||||
state = "Kansas",
|
||||
country = "USA",
|
||||
},
|
||||
age = 22,
|
||||
parents = {"Jonathan Kent", "Martha Kent"},
|
||||
superman = true,
|
||||
interests = {"flying", "saving the world", "kryptonite"},
|
||||
}"#,
|
||||
)
|
||||
.eval::<LuaTable>()
|
||||
.unwrap();
|
||||
|
||||
c.bench_function("serialize table to json [10]", |b| {
|
||||
c.bench_function("serialize json", |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
collect_gc_twice(&lua);
|
||||
lua.load(
|
||||
r#"
|
||||
local encode = encode
|
||||
return function()
|
||||
for i = 1, 10 do
|
||||
encode({
|
||||
name = "Clark Kent",
|
||||
nickname = "Superman",
|
||||
address = {
|
||||
city = "Metropolis",
|
||||
},
|
||||
age = 32,
|
||||
superman = true,
|
||||
})
|
||||
end
|
||||
end
|
||||
"#,
|
||||
)
|
||||
.eval::<LuaFunction>()
|
||||
.unwrap()
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
encode.call::<_, LuaString>(&table).unwrap();
|
||||
},
|
||||
|func| {
|
||||
func.call::<_, ()>(()).unwrap();
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn decode_json(c: &mut Criterion) {
|
||||
let lua = Lua::new();
|
||||
|
||||
let decode = lua
|
||||
.create_function(|lua, s: String| {
|
||||
lua.to_value(&serde_json::from_str::<serde_json::Value>(&s).unwrap())
|
||||
})
|
||||
.unwrap();
|
||||
let json = r#"{
|
||||
"name": "Clark Kent",
|
||||
"address": {
|
||||
"city": "Smallville",
|
||||
"state": "Kansas",
|
||||
"country": "USA"
|
||||
},
|
||||
"age": 22,
|
||||
"parents": ["Jonathan Kent", "Martha Kent"],
|
||||
"superman": true,
|
||||
"interests": ["flying", "saving the world", "kryptonite"]
|
||||
}"#;
|
||||
|
||||
c.bench_function("deserialize json", |b| {
|
||||
b.iter_batched(
|
||||
|| collect_gc_twice(&lua),
|
||||
|_| {
|
||||
decode.call::<_, LuaTable>(json).unwrap();
|
||||
},
|
||||
BatchSize::SmallInput,
|
||||
);
|
||||
@@ -54,11 +79,12 @@ fn serialize_json(c: &mut Criterion) {
|
||||
criterion_group! {
|
||||
name = benches;
|
||||
config = Criterion::default()
|
||||
.sample_size(300)
|
||||
.sample_size(500)
|
||||
.measurement_time(Duration::from_secs(10))
|
||||
.noise_threshold(0.02);
|
||||
targets =
|
||||
serialize_json,
|
||||
encode_json,
|
||||
decode_json,
|
||||
}
|
||||
|
||||
criterion_main!(benches);
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use hyper::body::{Body as HyperBody, HttpBody as _};
|
||||
use hyper::Client as HyperClient;
|
||||
use http_body_util::BodyExt as _;
|
||||
use hyper::body::Incoming;
|
||||
use hyper_util::client::legacy::Client as HyperClient;
|
||||
use hyper_util::rt::TokioExecutor;
|
||||
|
||||
use mlua::{chunk, ExternalResult, Lua, Result, UserData, UserDataMethods};
|
||||
|
||||
struct BodyReader(HyperBody);
|
||||
struct BodyReader(Incoming);
|
||||
|
||||
impl UserData for BodyReader {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
// Every call returns a next chunk
|
||||
methods.add_async_method_mut("read", |lua, reader, ()| async move {
|
||||
if let Some(bytes) = reader.0.data().await {
|
||||
let bytes = bytes.into_lua_err()?;
|
||||
return Some(lua.create_string(&bytes)).transpose();
|
||||
if let Some(bytes) = reader.0.frame().await {
|
||||
if let Some(bytes) = bytes.into_lua_err()?.data_ref() {
|
||||
return Some(lua.create_string(&bytes)).transpose();
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
});
|
||||
@@ -24,7 +28,7 @@ async fn main() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let fetch_url = lua.create_async_function(|lua, uri: String| async move {
|
||||
let client = HyperClient::new();
|
||||
let client = HyperClient::builder(TokioExecutor::new()).build_http::<String>();
|
||||
let uri = uri.parse().into_lua_err()?;
|
||||
let resp = client.get(uri).await.into_lua_err()?;
|
||||
|
||||
@@ -55,11 +59,11 @@ async fn main() -> Result<()> {
|
||||
end
|
||||
end
|
||||
repeat
|
||||
local body = res.body:read()
|
||||
if body then
|
||||
print(body)
|
||||
local chunk = res.body:read()
|
||||
if chunk then
|
||||
print(chunk)
|
||||
end
|
||||
until not body
|
||||
until not chunk
|
||||
})
|
||||
.into_function()?;
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
use mlua::{chunk, ExternalResult, Lua, LuaSerdeExt, Result};
|
||||
use mlua::{chunk, ExternalResult, Lua, LuaSerdeExt, Result, Value};
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let null = lua.null();
|
||||
|
||||
let fetch_json = lua.create_async_function(|lua, uri: String| async move {
|
||||
let resp = reqwest::get(&uri)
|
||||
.await
|
||||
@@ -15,19 +13,15 @@ async fn main() -> Result<()> {
|
||||
lua.to_value(&json)
|
||||
})?;
|
||||
|
||||
let dbg = lua.create_function(|_, value: Value| {
|
||||
println!("{value:#?}");
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let f = lua
|
||||
.load(chunk! {
|
||||
function print_r(t, indent)
|
||||
local indent = indent or ""
|
||||
for k, v in pairs(t) do
|
||||
io.write(indent, tostring(k))
|
||||
if type(v) == "table" then io.write(":\n") print_r(v, indent.." ")
|
||||
else io.write(": ", v == $null and "null" or tostring(v), "\n") end
|
||||
end
|
||||
end
|
||||
|
||||
local res = $fetch_json(...)
|
||||
print_r(res)
|
||||
$dbg(res)
|
||||
})
|
||||
.into_function()?;
|
||||
|
||||
|
||||
@@ -1,43 +1,63 @@
|
||||
use std::convert::Infallible;
|
||||
use std::future::Future;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use hyper::server::conn::AddrStream;
|
||||
use hyper::service::Service;
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
use futures::future::LocalBoxFuture;
|
||||
use http_body_util::{combinators::BoxBody, BodyExt as _, Empty, Full};
|
||||
use hyper::body::{Bytes, Incoming};
|
||||
use hyper::{Request, Response};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use hyper_util::server::conn::auto::Builder as ServerConnBuilder;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::LocalSet;
|
||||
|
||||
use mlua::{
|
||||
chunk, Error as LuaError, Function, Lua, String as LuaString, Table, UserData, UserDataMethods,
|
||||
chunk, Error as LuaError, Function, Lua, RegistryKey, String as LuaString, Table, UserData,
|
||||
UserDataMethods,
|
||||
};
|
||||
|
||||
struct LuaRequest(SocketAddr, Request<Body>);
|
||||
/// Wrapper around incoming request that implements UserData
|
||||
struct LuaRequest(SocketAddr, Request<Incoming>);
|
||||
|
||||
impl UserData for LuaRequest {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_method("remote_addr", |_lua, req, ()| Ok((req.0).to_string()));
|
||||
methods.add_method("method", |_lua, req, ()| Ok((req.1).method().to_string()));
|
||||
methods.add_method("remote_addr", |_, req, ()| Ok((req.0).to_string()));
|
||||
methods.add_method("method", |_, req, ()| Ok((req.1).method().to_string()));
|
||||
methods.add_method("path", |_, req, ()| Ok(req.1.uri().path().to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Svc(Rc<Lua>, SocketAddr);
|
||||
/// Service that handles incoming requests
|
||||
#[derive(Clone)]
|
||||
pub struct Svc {
|
||||
lua: Rc<Lua>,
|
||||
handler: Rc<RegistryKey>,
|
||||
peer_addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl Service<Request<Body>> for Svc {
|
||||
type Response = Response<Body>;
|
||||
type Error = LuaError;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
impl Svc {
|
||||
pub fn new(lua: Rc<Lua>, handler: Rc<RegistryKey>, peer_addr: SocketAddr) -> Self {
|
||||
Self {
|
||||
lua,
|
||||
handler,
|
||||
peer_addr,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
impl hyper::service::Service<Request<Incoming>> for Svc {
|
||||
type Response = Response<BoxBody<Bytes, Infallible>>;
|
||||
type Error = LuaError;
|
||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||
|
||||
fn call(&self, req: Request<Incoming>) -> Self::Future {
|
||||
// If handler returns an error then generate 5xx response
|
||||
let lua = self.0.clone();
|
||||
let lua_req = LuaRequest(self.1, req);
|
||||
let lua = self.lua.clone();
|
||||
let handler_key = self.handler.clone();
|
||||
let lua_req = LuaRequest(self.peer_addr, req);
|
||||
Box::pin(async move {
|
||||
let handler: Function = lua.named_registry_value("http_handler")?;
|
||||
let handler: Function = lua.registry_value(&handler_key)?;
|
||||
match handler.call_async::<_, Table>(lua_req).await {
|
||||
Ok(lua_resp) => {
|
||||
let status = lua_resp.get::<_, Option<u16>>("status")?.unwrap_or(200);
|
||||
@@ -51,10 +71,11 @@ impl Service<Request<Body>> for Svc {
|
||||
}
|
||||
}
|
||||
|
||||
// Set body
|
||||
let body = lua_resp
|
||||
.get::<_, Option<LuaString>>("body")?
|
||||
.map(|b| Body::from(b.as_bytes().to_vec()))
|
||||
.unwrap_or_else(Body::empty);
|
||||
.map(|b| Full::new(Bytes::copy_from_slice(b.as_bytes())).boxed())
|
||||
.unwrap_or_else(|| Empty::<Bytes>::new().boxed());
|
||||
|
||||
Ok(resp.body(body).unwrap())
|
||||
}
|
||||
@@ -62,7 +83,7 @@ impl Service<Request<Body>> for Svc {
|
||||
eprintln!("{}", err);
|
||||
Ok(Response::builder()
|
||||
.status(500)
|
||||
.body(Body::from("Internal Server Error"))
|
||||
.body(Full::new(Bytes::from("Internal Server Error")).boxed())
|
||||
.unwrap())
|
||||
}
|
||||
}
|
||||
@@ -75,13 +96,14 @@ async fn main() {
|
||||
let lua = Rc::new(Lua::new());
|
||||
|
||||
// Create Lua handler function
|
||||
let handler: Function = lua
|
||||
let handler: RegistryKey = lua
|
||||
.load(chunk! {
|
||||
function(req)
|
||||
return {
|
||||
status = 200,
|
||||
headers = {
|
||||
["X-Req-Method"] = req:method(),
|
||||
["X-Req-Path"] = req:path(),
|
||||
["X-Remote-Addr"] = req:remote_addr(),
|
||||
},
|
||||
body = "Hello from Lua!\n"
|
||||
@@ -89,37 +111,35 @@ async fn main() {
|
||||
end
|
||||
})
|
||||
.eval()
|
||||
.expect("cannot create Lua handler");
|
||||
.expect("Failed to create Lua handler");
|
||||
let handler = Rc::new(handler);
|
||||
|
||||
// Store it in the Registry
|
||||
lua.set_named_registry_value("http_handler", handler)
|
||||
.expect("cannot store Lua handler");
|
||||
let listen_addr = "127.0.0.1:3000";
|
||||
let listener = TcpListener::bind(listen_addr).await.unwrap();
|
||||
println!("Listening on http://{listen_addr}");
|
||||
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
let server = Server::bind(&addr).executor(LocalExec).serve(MakeSvc(lua));
|
||||
let local = LocalSet::new();
|
||||
loop {
|
||||
let (stream, peer_addr) = match listener.accept().await {
|
||||
Ok(x) => x,
|
||||
Err(err) => {
|
||||
eprintln!("Failed to accept connection: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
// Create `LocalSet` to spawn !Send futures
|
||||
let local = tokio::task::LocalSet::new();
|
||||
local.run_until(server).await.expect("cannot run server")
|
||||
}
|
||||
|
||||
struct MakeSvc(Rc<Lua>);
|
||||
|
||||
impl Service<&AddrStream> for MakeSvc {
|
||||
type Response = Svc;
|
||||
type Error = hyper::Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
|
||||
|
||||
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, stream: &AddrStream) -> Self::Future {
|
||||
let lua = self.0.clone();
|
||||
let remote_addr = stream.remote_addr();
|
||||
Box::pin(async move { Ok(Svc(lua, remote_addr)) })
|
||||
let svc = Svc::new(lua.clone(), handler.clone(), peer_addr);
|
||||
local
|
||||
.run_until(async move {
|
||||
let result = ServerConnBuilder::new(LocalExec)
|
||||
.http1()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
eprintln!("Error serving connection: {err:?}");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +148,7 @@ struct LocalExec;
|
||||
|
||||
impl<F> hyper::rt::Executor<F> for LocalExec
|
||||
where
|
||||
F: std::future::Future + 'static, // not requiring `Send`
|
||||
F: Future + 'static, // not requiring `Send`
|
||||
{
|
||||
fn execute(&self, fut: F) {
|
||||
tokio::task::spawn_local(fut);
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//!
|
||||
//! Based on github.com/keplerproject/lua-compat-5.3
|
||||
|
||||
use std::convert::TryInto;
|
||||
use std::mem;
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
//!
|
||||
//! Based on github.com/keplerproject/lua-compat-5.3
|
||||
|
||||
use std::convert::TryInto;
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
|
||||
@@ -144,9 +144,12 @@ pub unsafe fn luaL_sandbox(L: *mut lua_State, enabled: c_int) {
|
||||
|
||||
// set all builtin metatables to read-only
|
||||
lua_pushliteral(L, "");
|
||||
lua_getmetatable(L, -1);
|
||||
lua_setreadonly(L, -1, enabled);
|
||||
lua_pop(L, 2);
|
||||
if lua_getmetatable(L, -1) != 0 {
|
||||
lua_setreadonly(L, -1, enabled);
|
||||
lua_pop(L, 2);
|
||||
} else {
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
|
||||
// set globals to readonly and activate safeenv since the env is immutable
|
||||
lua_setreadonly(L, LUA_GLOBALSINDEX, enabled);
|
||||
|
||||
@@ -36,6 +36,7 @@ pub unsafe fn luau_compile(source: &[u8], mut options: lua_CompileOptions) -> Ve
|
||||
&mut options,
|
||||
&mut outsize,
|
||||
);
|
||||
assert!(!data_ptr.is_null(), "luau_compile failed");
|
||||
let data = slice::from_raw_parts(data_ptr as *mut u8, outsize).to_vec();
|
||||
free(data_ptr as *mut c_void);
|
||||
data
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::{
|
||||
cmp::{Eq, PartialEq},
|
||||
fmt::{self, Display, Formatter},
|
||||
iter::IntoIterator,
|
||||
vec::IntoIter,
|
||||
};
|
||||
|
||||
|
||||
+124
-16
@@ -1,6 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::convert::TryInto;
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::os::raw::c_int;
|
||||
@@ -33,6 +32,18 @@ impl<'lua> IntoLua<'lua> for Value<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for &Value<'lua> {
|
||||
#[inline]
|
||||
fn into_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
|
||||
Ok(self.clone())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
lua.push_value_ref(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for Value<'lua> {
|
||||
#[inline]
|
||||
fn from_lua(lua_value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
|
||||
@@ -55,7 +66,8 @@ impl<'lua> IntoLua<'lua> for &String<'lua> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_ref(&self.0))
|
||||
lua.push_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +103,8 @@ impl<'lua> IntoLua<'lua> for &OwnedString {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_owned_ref(&self.0))
|
||||
lua.push_owned_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,7 +132,8 @@ impl<'lua> IntoLua<'lua> for &Table<'lua> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_ref(&self.0))
|
||||
lua.push_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +170,8 @@ impl<'lua> IntoLua<'lua> for &OwnedTable {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_owned_ref(&self.0))
|
||||
lua.push_owned_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +199,8 @@ impl<'lua> IntoLua<'lua> for &Function<'lua> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_ref(&self.0))
|
||||
lua.push_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,7 +237,8 @@ impl<'lua> IntoLua<'lua> for &OwnedFunction {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_owned_ref(&self.0))
|
||||
lua.push_owned_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +266,8 @@ impl<'lua> IntoLua<'lua> for &Thread<'lua> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_ref(&self.0))
|
||||
lua.push_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +304,8 @@ impl<'lua> IntoLua<'lua> for &OwnedThread {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_owned_ref(&self.0))
|
||||
lua.push_owned_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +333,8 @@ impl<'lua> IntoLua<'lua> for &AnyUserData<'lua> {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_ref(&self.0))
|
||||
lua.push_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,7 +374,8 @@ impl<'lua> IntoLua<'lua> for &OwnedAnyUserData {
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
Ok(lua.push_owned_ref(&self.0))
|
||||
lua.push_owned_ref(&self.0);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -409,6 +430,18 @@ impl<'lua> FromLua<'lua> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for RegistryKey {
|
||||
#[inline]
|
||||
fn into_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
|
||||
lua.registry_value(&self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
<&RegistryKey>::push_into_stack(&self, lua)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for &RegistryKey {
|
||||
#[inline]
|
||||
fn into_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
|
||||
@@ -429,11 +462,24 @@ impl<'lua> IntoLua<'lua> for &RegistryKey {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for RegistryKey {
|
||||
#[inline]
|
||||
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<RegistryKey> {
|
||||
lua.create_registry_value(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for bool {
|
||||
#[inline]
|
||||
fn into_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
|
||||
Ok(Value::Boolean(self))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
ffi::lua_pushboolean(lua.state(), self as c_int);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for bool {
|
||||
@@ -445,6 +491,11 @@ impl<'lua> FromLua<'lua> for bool {
|
||||
_ => Ok(true),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_stack(idx: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
Ok(ffi::lua_toboolean(lua.state(), idx) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> IntoLua<'lua> for LightUserData {
|
||||
@@ -633,19 +684,49 @@ impl<'lua> IntoLua<'lua> for BString {
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for BString {
|
||||
#[inline]
|
||||
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
|
||||
let ty = value.type_name();
|
||||
Ok(BString::from(
|
||||
lua.coerce_string(value)?
|
||||
match value {
|
||||
Value::String(s) => Ok(s.as_bytes().into()),
|
||||
#[cfg(feature = "luau")]
|
||||
Value::UserData(ud) if ud.1 == crate::types::SubtypeId::Buffer => unsafe {
|
||||
let mut size = 0usize;
|
||||
let buf = ffi::lua_tobuffer(ud.0.lua.ref_thread(), ud.0.index, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
Ok(slice::from_raw_parts(buf as *const u8, size).into())
|
||||
},
|
||||
_ => Ok(lua
|
||||
.coerce_string(value)?
|
||||
.ok_or_else(|| Error::FromLuaConversionError {
|
||||
from: ty,
|
||||
to: "BString",
|
||||
message: Some("expected string or number".to_string()),
|
||||
})?
|
||||
.as_bytes()
|
||||
.to_vec(),
|
||||
))
|
||||
.into()),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn from_stack(idx: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
let state = lua.state();
|
||||
match ffi::lua_type(state, idx) {
|
||||
ffi::LUA_TSTRING => {
|
||||
let mut size = 0;
|
||||
let data = ffi::lua_tolstring(state, idx, &mut size);
|
||||
Ok(slice::from_raw_parts(data as *const u8, size).into())
|
||||
}
|
||||
#[cfg(feature = "luau")]
|
||||
ffi::LUA_TBUFFER => {
|
||||
let mut size = 0;
|
||||
let buf = ffi::lua_tobuffer(state, idx, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
Ok(slice::from_raw_parts(buf as *const u8, size).into())
|
||||
}
|
||||
_ => {
|
||||
// Fallback to default
|
||||
Self::from_lua(lua.stack_value(idx), lua)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,6 +767,15 @@ macro_rules! lua_convert_int {
|
||||
message: Some("out of range".to_owned()),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
match cast(self) {
|
||||
Some(i) => ffi::lua_pushinteger(lua.state(), i),
|
||||
None => ffi::lua_pushnumber(lua.state(), self as ffi::lua_Number),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> FromLua<'lua> for $x {
|
||||
@@ -978,6 +1068,15 @@ impl<'lua, T: IntoLua<'lua>> IntoLua<'lua> for Option<T> {
|
||||
None => Ok(Nil),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack(self, lua: &'lua Lua) -> Result<()> {
|
||||
match self {
|
||||
Some(val) => val.push_into_stack(lua)?,
|
||||
None => ffi::lua_pushnil(lua.state()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option<T> {
|
||||
@@ -988,4 +1087,13 @@ impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option<T> {
|
||||
value => Ok(Some(T::from_lua(value, lua)?)),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_stack(idx: c_int, lua: &'lua Lua) -> Result<Self> {
|
||||
if ffi::lua_isnil(lua.state(), idx) != 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(T::from_stack(idx, lua)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -494,6 +494,37 @@ impl<'lua> Function<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this function to a generic C pointer.
|
||||
///
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
///
|
||||
/// Typically this function is used only for hashing and debug information.
|
||||
#[inline]
|
||||
pub fn to_pointer(&self) -> *const c_void {
|
||||
self.0.to_pointer()
|
||||
}
|
||||
|
||||
/// Creates a deep clone of the Lua function.
|
||||
///
|
||||
/// Copies the function prototype and all its upvalues to the
|
||||
/// newly created function.
|
||||
///
|
||||
/// This function returns shallow clone (same handle) for Rust/C functions.
|
||||
/// Requires `feature = "luau"`
|
||||
#[cfg(feature = "luau")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
|
||||
pub fn deep_clone(&self) -> Self {
|
||||
let ref_thread = self.0.lua.ref_thread();
|
||||
unsafe {
|
||||
if ffi::lua_iscfunction(ref_thread, self.0.index) != 0 {
|
||||
return self.clone();
|
||||
}
|
||||
|
||||
ffi::lua_clonefunction(ref_thread, self.0.index);
|
||||
Function(self.0.lua.pop_ref_thread())
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert this handle to owned version.
|
||||
#[cfg(all(feature = "unstable", any(not(feature = "send"), doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", not(feature = "send")))))]
|
||||
|
||||
+82
-58
@@ -226,6 +226,7 @@ pub(crate) static EXTRA_REGISTRY_KEY: u8 = 0;
|
||||
|
||||
const WRAPPED_FAILURE_POOL_SIZE: usize = 64;
|
||||
const MULTIVALUE_POOL_SIZE: usize = 64;
|
||||
const REF_STACK_RESERVE: c_int = 1;
|
||||
|
||||
/// Requires `feature = "send"`
|
||||
#[cfg(feature = "send")]
|
||||
@@ -519,8 +520,8 @@ impl Lua {
|
||||
#[cfg(feature = "module")]
|
||||
skip_memory_check: false,
|
||||
ref_thread,
|
||||
// We need 1 extra stack space to move values in and out of the ref stack.
|
||||
ref_stack_size: ffi::LUA_MINSTACK - 1,
|
||||
// We need some reserved stack space to move values in and out of the ref stack.
|
||||
ref_stack_size: ffi::LUA_MINSTACK - REF_STACK_RESERVE,
|
||||
ref_stack_top: ffi::lua_gettop(ref_thread),
|
||||
ref_free: Vec::new(),
|
||||
wrapped_failure_pool: Vec::with_capacity(WRAPPED_FAILURE_POOL_SIZE),
|
||||
@@ -1372,6 +1373,27 @@ impl Lua {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create and return a Luau [buffer] object from a byte slice of data.
|
||||
///
|
||||
/// Requires `feature = "luau"`
|
||||
///
|
||||
/// [buffer]: https://luau-lang.org/library#buffer-library
|
||||
#[cfg(feature = "luau")]
|
||||
pub fn create_buffer(&self, buf: impl AsRef<[u8]>) -> Result<AnyUserData> {
|
||||
let state = self.state();
|
||||
unsafe {
|
||||
if self.unlikely_memory_error() {
|
||||
crate::util::push_buffer(self.ref_thread(), buf.as_ref(), false)?;
|
||||
return Ok(AnyUserData(self.pop_ref_thread(), SubtypeId::Buffer));
|
||||
}
|
||||
|
||||
let _sg = StackGuard::new(state);
|
||||
check_stack(state, 4)?;
|
||||
crate::util::push_buffer(state, buf.as_ref(), true)?;
|
||||
Ok(AnyUserData(self.pop_ref(), SubtypeId::Buffer))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates and returns a new empty table.
|
||||
pub fn create_table(&self) -> Result<Table> {
|
||||
self.create_table_with_capacity(0, 0)
|
||||
@@ -1413,8 +1435,8 @@ impl Lua {
|
||||
let protect = !self.unlikely_memory_error();
|
||||
push_table(state, 0, lower_bound, protect)?;
|
||||
for (k, v) in iter {
|
||||
self.push_value(k.into_lua(self)?)?;
|
||||
self.push_value(v.into_lua(self)?)?;
|
||||
self.push(k)?;
|
||||
self.push(v)?;
|
||||
if protect {
|
||||
protect_lua!(state, 3, 1, fn(state) ffi::lua_rawset(state, -3))?;
|
||||
} else {
|
||||
@@ -1442,7 +1464,7 @@ impl Lua {
|
||||
let protect = !self.unlikely_memory_error();
|
||||
push_table(state, lower_bound, 0, protect)?;
|
||||
for (i, v) in iter.enumerate() {
|
||||
self.push_value(v.into_lua(self)?)?;
|
||||
self.push(v)?;
|
||||
if protect {
|
||||
protect_lua!(state, 2, 1, |state| {
|
||||
ffi::lua_rawseti(state, -2, (i + 1) as Integer);
|
||||
@@ -1724,6 +1746,21 @@ impl Lua {
|
||||
unsafe { self.make_any_userdata(UserDataCell::new(data)) }
|
||||
}
|
||||
|
||||
/// Creates a Lua userdata object from a custom serializable Rust type.
|
||||
///
|
||||
/// See [`Lua::create_any_userdata()`] for more details.
|
||||
///
|
||||
/// Requires `feature = "serialize"`
|
||||
#[cfg(feature = "serialize")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
|
||||
#[inline]
|
||||
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
|
||||
where
|
||||
T: Serialize + MaybeSend + 'static,
|
||||
{
|
||||
unsafe { self.make_any_userdata(UserDataCell::new_ser(data)) }
|
||||
}
|
||||
|
||||
/// 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`.
|
||||
@@ -1977,12 +2014,11 @@ impl Lua {
|
||||
T: IntoLua<'lua>,
|
||||
{
|
||||
let state = self.state();
|
||||
let t = t.into_lua(self)?;
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
check_stack(state, 5)?;
|
||||
|
||||
self.push_value(t)?;
|
||||
self.push(t)?;
|
||||
rawset_field(state, ffi::LUA_REGISTRYINDEX, name)
|
||||
}
|
||||
}
|
||||
@@ -2269,33 +2305,38 @@ impl Lua {
|
||||
extra.app_data.remove()
|
||||
}
|
||||
|
||||
/// Pushes a value onto the Lua stack.
|
||||
/// Pushes a value that implements `IntoLua` onto the Lua stack.
|
||||
///
|
||||
/// Uses 2 stack spaces, does not call checkstack.
|
||||
#[doc(hidden)]
|
||||
#[inline(always)]
|
||||
pub unsafe fn push<'lua>(&'lua self, value: impl IntoLua<'lua>) -> Result<()> {
|
||||
value.push_into_stack(self)
|
||||
}
|
||||
|
||||
/// Pushes a `Value` onto the Lua stack.
|
||||
///
|
||||
/// Uses 2 stack spaces, does not call checkstack.
|
||||
#[doc(hidden)]
|
||||
pub unsafe fn push_value(&self, value: Value) -> Result<()> {
|
||||
if let Value::Error(err) = value {
|
||||
let protect = !self.unlikely_memory_error();
|
||||
return push_gc_userdata(self.state(), WrappedFailure::Error(err), protect);
|
||||
}
|
||||
self.push_value_ref(&value)
|
||||
}
|
||||
|
||||
/// Pushes a `&Value` (by reference) onto the Lua stack.
|
||||
///
|
||||
/// Similar to [`Lua::push_value`], uses 2 stack spaces, does not call checkstack.
|
||||
pub(crate) unsafe fn push_value_ref(&self, value: &Value) -> Result<()> {
|
||||
let state = self.state();
|
||||
match value {
|
||||
Value::Nil => {
|
||||
ffi::lua_pushnil(state);
|
||||
}
|
||||
|
||||
Value::Boolean(b) => {
|
||||
ffi::lua_pushboolean(state, b as c_int);
|
||||
}
|
||||
|
||||
Value::LightUserData(ud) => {
|
||||
ffi::lua_pushlightuserdata(state, ud.0);
|
||||
}
|
||||
|
||||
Value::Integer(i) => {
|
||||
ffi::lua_pushinteger(state, i);
|
||||
}
|
||||
|
||||
Value::Number(n) => {
|
||||
ffi::lua_pushnumber(state, n);
|
||||
}
|
||||
|
||||
Value::Nil => ffi::lua_pushnil(state),
|
||||
Value::Boolean(b) => ffi::lua_pushboolean(state, *b as c_int),
|
||||
Value::LightUserData(ud) => ffi::lua_pushlightuserdata(state, ud.0),
|
||||
Value::Integer(i) => ffi::lua_pushinteger(state, *i),
|
||||
Value::Number(n) => ffi::lua_pushnumber(state, *n),
|
||||
#[cfg(feature = "luau")]
|
||||
Value::Vector(v) => {
|
||||
#[cfg(not(feature = "luau-vector4"))]
|
||||
@@ -2303,33 +2344,16 @@ impl Lua {
|
||||
#[cfg(feature = "luau-vector4")]
|
||||
ffi::lua_pushvector(state, v.x(), v.y(), v.z(), v.w());
|
||||
}
|
||||
|
||||
Value::String(s) => {
|
||||
self.push_ref(&s.0);
|
||||
}
|
||||
|
||||
Value::Table(t) => {
|
||||
self.push_ref(&t.0);
|
||||
}
|
||||
|
||||
Value::Function(f) => {
|
||||
self.push_ref(&f.0);
|
||||
}
|
||||
|
||||
Value::Thread(t) => {
|
||||
self.push_ref(&t.0);
|
||||
}
|
||||
|
||||
Value::UserData(ud) => {
|
||||
self.push_ref(&ud.0);
|
||||
}
|
||||
|
||||
Value::String(s) => self.push_ref(&s.0),
|
||||
Value::Table(t) => self.push_ref(&t.0),
|
||||
Value::Function(f) => self.push_ref(&f.0),
|
||||
Value::Thread(t) => self.push_ref(&t.0),
|
||||
Value::UserData(ud) => self.push_ref(&ud.0),
|
||||
Value::Error(err) => {
|
||||
let protect = !self.unlikely_memory_error();
|
||||
push_gc_userdata(state, WrappedFailure::Error(err), protect)?;
|
||||
push_gc_userdata(state, WrappedFailure::Error(err.clone()), protect)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2643,12 +2667,12 @@ impl Lua {
|
||||
let metatable_nrec = metatable_nrec + registry.async_meta_methods.len();
|
||||
push_table(state, 0, metatable_nrec, true)?;
|
||||
for (k, m) in registry.meta_methods {
|
||||
self.push_value(Value::Function(self.create_callback(m)?))?;
|
||||
self.push(self.create_callback(m)?)?;
|
||||
rawset_field(state, -2, MetaMethod::validate(&k)?)?;
|
||||
}
|
||||
#[cfg(feature = "async")]
|
||||
for (k, m) in registry.async_meta_methods {
|
||||
self.push_value(Value::Function(self.create_async_callback(m)?))?;
|
||||
self.push(self.create_async_callback(m)?)?;
|
||||
rawset_field(state, -2, MetaMethod::validate(&k)?)?;
|
||||
}
|
||||
let mut has_name = false;
|
||||
@@ -2699,7 +2723,7 @@ impl Lua {
|
||||
if field_getters_nrec > 0 {
|
||||
push_table(state, 0, field_getters_nrec, true)?;
|
||||
for (k, m) in registry.field_getters {
|
||||
self.push_value(Value::Function(self.create_callback(m)?))?;
|
||||
self.push(self.create_callback(m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
field_getters_index = Some(ffi::lua_absindex(state, -1));
|
||||
@@ -2711,7 +2735,7 @@ impl Lua {
|
||||
if field_setters_nrec > 0 {
|
||||
push_table(state, 0, field_setters_nrec, true)?;
|
||||
for (k, m) in registry.field_setters {
|
||||
self.push_value(Value::Function(self.create_callback(m)?))?;
|
||||
self.push(self.create_callback(m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
field_setters_index = Some(ffi::lua_absindex(state, -1));
|
||||
@@ -2734,12 +2758,12 @@ impl Lua {
|
||||
}
|
||||
}
|
||||
for (k, m) in registry.methods {
|
||||
self.push_value(Value::Function(self.create_callback(m)?))?;
|
||||
self.push(self.create_callback(m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
#[cfg(feature = "async")]
|
||||
for (k, m) in registry.async_methods {
|
||||
self.push_value(Value::Function(self.create_async_callback(m)?))?;
|
||||
self.push(self.create_async_callback(m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
match index_type {
|
||||
@@ -2990,7 +3014,7 @@ impl Lua {
|
||||
nresults => {
|
||||
let results = MultiValue::from_stack_multi(nresults, lua)?;
|
||||
ffi::lua_pushinteger(state, nresults as _);
|
||||
lua.push_value(Value::Table(lua.create_sequence_from(results)?))?;
|
||||
lua.push(lua.create_sequence_from(results)?)?;
|
||||
Ok(2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@ pub(crate) fn register_package_module(lua: &Lua) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
pub(crate) fn disable_dylibs(lua: &Lua) {
|
||||
// Presence of `LoadedDylibs` in app data is used as a flag
|
||||
// to check whether binary modules are enabled
|
||||
|
||||
+28
-1
@@ -1,4 +1,3 @@
|
||||
use std::iter::FromIterator;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::os::raw::c_int;
|
||||
use std::result::Result as StdResult;
|
||||
@@ -23,6 +22,20 @@ impl<'lua, T: IntoLua<'lua>, E: IntoLua<'lua>> IntoLuaMulti<'lua> for StdResult<
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
match self {
|
||||
Ok(v) => v.push_into_stack(lua).map(|_| 1),
|
||||
Err(e) => {
|
||||
let state = lua.state();
|
||||
check_stack(state, 3)?;
|
||||
ffi::lua_pushnil(state);
|
||||
e.push_into_stack(lua)?;
|
||||
Ok(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, E: IntoLua<'lua>> IntoLuaMulti<'lua> for StdResult<(), E> {
|
||||
@@ -38,6 +51,20 @@ impl<'lua, E: IntoLua<'lua>> IntoLuaMulti<'lua> for StdResult<(), E> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<c_int> {
|
||||
match self {
|
||||
Ok(_) => Ok(0),
|
||||
Err(e) => {
|
||||
let state = lua.state();
|
||||
check_stack(state, 3)?;
|
||||
ffi::lua_pushnil(state);
|
||||
e.push_into_stack(lua)?;
|
||||
Ok(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua, T: IntoLua<'lua>> IntoLuaMulti<'lua> for T {
|
||||
|
||||
+5
-5
@@ -19,7 +19,7 @@ use crate::util::{
|
||||
self, assert_stack, check_stack, init_userdata_metatable, push_string, push_table,
|
||||
rawset_field, short_type_name, take_userdata, StackGuard,
|
||||
};
|
||||
use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, Value};
|
||||
use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
|
||||
|
||||
#[cfg(feature = "lua54")]
|
||||
use crate::userdata::USER_VALUE_MAXSLOT;
|
||||
@@ -405,7 +405,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> {
|
||||
let meta_methods_nrec = registry.meta_methods.len() + registry.meta_fields.len() + 1;
|
||||
push_table(state, 0, meta_methods_nrec, true)?;
|
||||
for (k, m) in registry.meta_methods {
|
||||
lua.push_value(Value::Function(wrap_method(self, ud_ptr, &k, m)?))?;
|
||||
lua.push(wrap_method(self, ud_ptr, &k, m)?)?;
|
||||
rawset_field(state, -2, MetaMethod::validate(&k)?)?;
|
||||
}
|
||||
let mut has_name = false;
|
||||
@@ -455,7 +455,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> {
|
||||
if field_getters_nrec > 0 {
|
||||
push_table(state, 0, field_getters_nrec, true)?;
|
||||
for (k, m) in registry.field_getters {
|
||||
lua.push_value(Value::Function(wrap_method(self, ud_ptr, &k, m)?))?;
|
||||
lua.push(wrap_method(self, ud_ptr, &k, m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
field_getters_index = Some(ffi::lua_absindex(state, -1));
|
||||
@@ -466,7 +466,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> {
|
||||
if field_setters_nrec > 0 {
|
||||
push_table(state, 0, field_setters_nrec, true)?;
|
||||
for (k, m) in registry.field_setters {
|
||||
lua.push_value(Value::Function(wrap_method(self, ud_ptr, &k, m)?))?;
|
||||
lua.push(wrap_method(self, ud_ptr, &k, m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
field_setters_index = Some(ffi::lua_absindex(state, -1));
|
||||
@@ -478,7 +478,7 @@ impl<'lua, 'scope> Scope<'lua, 'scope> {
|
||||
// Create table used for methods lookup
|
||||
push_table(state, 0, methods_nrec, true)?;
|
||||
for (k, m) in registry.methods {
|
||||
lua.push_value(Value::Function(wrap_method(self, ud_ptr, &k, m)?))?;
|
||||
lua.push(wrap_method(self, ud_ptr, &k, m)?)?;
|
||||
rawset_field(state, -2, &k)?;
|
||||
}
|
||||
methods_index = Some(ffi::lua_absindex(state, -1));
|
||||
|
||||
+9
-4
@@ -1,5 +1,4 @@
|
||||
use std::cell::RefCell;
|
||||
use std::convert::TryInto;
|
||||
use std::os::raw::c_void;
|
||||
use std::rc::Rc;
|
||||
use std::result::Result as StdResult;
|
||||
@@ -134,9 +133,7 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
Value::Nil => visitor.visit_unit(),
|
||||
Value::Boolean(b) => visitor.visit_bool(b),
|
||||
#[allow(clippy::useless_conversion)]
|
||||
Value::Integer(i) => {
|
||||
visitor.visit_i64(i.try_into().expect("cannot convert lua_Integer to i64"))
|
||||
}
|
||||
Value::Integer(i) => visitor.visit_i64(i.into()),
|
||||
#[allow(clippy::useless_conversion)]
|
||||
Value::Number(n) => visitor.visit_f64(n.into()),
|
||||
#[cfg(feature = "luau")]
|
||||
@@ -151,6 +148,14 @@ impl<'lua, 'de> serde::Deserializer<'de> for Deserializer<'lua> {
|
||||
Value::UserData(ud) if ud.is_serializable() => {
|
||||
serde_userdata(ud, |value| value.deserialize_any(visitor))
|
||||
}
|
||||
#[cfg(feature = "luau")]
|
||||
Value::UserData(ud) if ud.1 == crate::types::SubtypeId::Buffer => unsafe {
|
||||
let mut size = 0usize;
|
||||
let buf = ffi::lua_tobuffer(ud.0.lua.ref_thread(), ud.0.index, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
let buf = std::slice::from_raw_parts(buf as *const u8, size);
|
||||
visitor.visit_bytes(buf)
|
||||
},
|
||||
Value::Function(_)
|
||||
| Value::Thread(_)
|
||||
| Value::UserData(_)
|
||||
|
||||
+83
-15
@@ -3,7 +3,6 @@ use serde::{ser, Serialize};
|
||||
use super::LuaSerdeExt;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::lua::Lua;
|
||||
use crate::string::String;
|
||||
use crate::table::Table;
|
||||
use crate::value::{IntoLua, Value};
|
||||
|
||||
@@ -43,6 +42,12 @@ pub struct Options {
|
||||
/// [`null`]: crate::LuaSerdeExt::null
|
||||
/// [`Nil`]: crate::Value::Nil
|
||||
pub serialize_unit_to_null: bool,
|
||||
|
||||
/// If true, serialize `serde_json::Number` with arbitrary_precision to a Lua number.
|
||||
/// Otherwise it will be serialized as an object (what serde does).
|
||||
///
|
||||
/// Default: **false**
|
||||
pub detect_serde_json_arbitrary_precision: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
@@ -58,6 +63,7 @@ impl Options {
|
||||
set_array_metatable: true,
|
||||
serialize_none_to_null: true,
|
||||
serialize_unit_to_null: true,
|
||||
detect_serde_json_arbitrary_precision: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +93,20 @@ impl Options {
|
||||
self.serialize_unit_to_null = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// 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 disabled by default.
|
||||
///
|
||||
/// [`detect_serde_json_arbitrary_precision`]: #structfield.detect_serde_json_arbitrary_precision
|
||||
#[must_use]
|
||||
pub const fn detect_serde_json_arbitrary_precision(mut self, enabled: bool) -> Self {
|
||||
self.detect_serde_json_arbitrary_precision = enabled;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> Serializer<'lua> {
|
||||
@@ -121,7 +141,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
type SerializeTupleStruct = SerializeSeq<'lua>;
|
||||
type SerializeTupleVariant = SerializeTupleVariant<'lua>;
|
||||
type SerializeMap = SerializeMap<'lua>;
|
||||
type SerializeStruct = SerializeMap<'lua>;
|
||||
type SerializeStruct = SerializeStruct<'lua>;
|
||||
type SerializeStructVariant = SerializeStructVariant<'lua>;
|
||||
|
||||
#[inline]
|
||||
@@ -266,7 +286,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
_len: usize,
|
||||
) -> Result<Self::SerializeTupleVariant> {
|
||||
Ok(SerializeTupleVariant {
|
||||
name: self.lua.create_string(variant)?,
|
||||
variant,
|
||||
table: self.lua.create_table()?,
|
||||
options: self.options,
|
||||
})
|
||||
@@ -282,8 +302,23 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
|
||||
self.serialize_map(Some(len))
|
||||
fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
|
||||
if self.options.detect_serde_json_arbitrary_precision
|
||||
&& name == "$serde_json::private::Number"
|
||||
&& len == 1
|
||||
{
|
||||
return Ok(SerializeStruct {
|
||||
lua: self.lua,
|
||||
inner: None,
|
||||
options: self.options,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(SerializeStruct {
|
||||
lua: self.lua,
|
||||
inner: Some(Value::Table(self.lua.create_table_with_capacity(0, len)?)),
|
||||
options: self.options,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -295,7 +330,7 @@ impl<'lua> ser::Serializer for Serializer<'lua> {
|
||||
len: usize,
|
||||
) -> Result<Self::SerializeStructVariant> {
|
||||
Ok(SerializeStructVariant {
|
||||
name: self.lua.create_string(variant)?,
|
||||
variant,
|
||||
table: self.lua.create_table_with_capacity(0, len)?,
|
||||
options: self.options,
|
||||
})
|
||||
@@ -402,7 +437,7 @@ impl<'lua> ser::SerializeTupleStruct for SerializeSeq<'lua> {
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeTupleVariant<'lua> {
|
||||
name: String<'lua>,
|
||||
variant: &'static str,
|
||||
table: Table<'lua>,
|
||||
options: Options,
|
||||
}
|
||||
@@ -422,7 +457,7 @@ impl<'lua> ser::SerializeTupleVariant for SerializeTupleVariant<'lua> {
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
let lua = self.table.0.lua;
|
||||
let table = lua.create_table()?;
|
||||
table.raw_set(self.name, self.table)?;
|
||||
table.raw_set(self.variant, self.table)?;
|
||||
Ok(Value::Table(table))
|
||||
}
|
||||
}
|
||||
@@ -465,7 +500,14 @@ impl<'lua> ser::SerializeMap for SerializeMap<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeStruct for SerializeMap<'lua> {
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeStruct<'lua> {
|
||||
lua: &'lua Lua,
|
||||
inner: Option<Value<'lua>>,
|
||||
options: Options,
|
||||
}
|
||||
|
||||
impl<'lua> ser::SerializeStruct for SerializeStruct<'lua> {
|
||||
type Ok = Value<'lua>;
|
||||
type Error = Error;
|
||||
|
||||
@@ -473,18 +515,44 @@ impl<'lua> ser::SerializeStruct for SerializeMap<'lua> {
|
||||
where
|
||||
T: Serialize + ?Sized,
|
||||
{
|
||||
ser::SerializeMap::serialize_key(self, key)?;
|
||||
ser::SerializeMap::serialize_value(self, value)
|
||||
match self.inner {
|
||||
Some(Value::Table(ref table)) => {
|
||||
table.raw_set(key, self.lua.to_value_with(value, self.options)?)?;
|
||||
}
|
||||
None if self.options.detect_serde_json_arbitrary_precision => {
|
||||
// A special case for `serde_json::Number` with arbitrary precision.
|
||||
assert_eq!(key, "$serde_json::private::Number");
|
||||
self.inner = Some(self.lua.to_value_with(value, self.options)?);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
ser::SerializeMap::end(self)
|
||||
match self.inner {
|
||||
Some(table @ Value::Table(_)) => Ok(table),
|
||||
Some(value) if self.options.detect_serde_json_arbitrary_precision => {
|
||||
let number_s = value.as_str().expect("not an arbitrary precision number");
|
||||
if number_s.contains(['.', 'e', 'E']) {
|
||||
if let Ok(number) = number_s.parse().map(Value::Number) {
|
||||
return Ok(number);
|
||||
}
|
||||
}
|
||||
Ok(number_s
|
||||
.parse()
|
||||
.map(Value::Integer)
|
||||
.or_else(|_| number_s.parse().map(Value::Number))
|
||||
.unwrap_or(value))
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SerializeStructVariant<'lua> {
|
||||
name: String<'lua>,
|
||||
variant: &'static str,
|
||||
table: Table<'lua>,
|
||||
options: Options,
|
||||
}
|
||||
@@ -505,8 +573,8 @@ impl<'lua> ser::SerializeStructVariant for SerializeStructVariant<'lua> {
|
||||
|
||||
fn end(self) -> Result<Value<'lua>> {
|
||||
let lua = self.table.0.lua;
|
||||
let table = lua.create_table()?;
|
||||
table.raw_set(self.name, self.table)?;
|
||||
let table = lua.create_table_with_capacity(0, 1)?;
|
||||
table.raw_set(self.variant, self.table)?;
|
||||
Ok(Value::Table(table))
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -132,7 +132,7 @@ impl<'lua> String<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the string to a generic C pointer.
|
||||
/// Converts this string to a generic C pointer.
|
||||
///
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
///
|
||||
|
||||
+42
-33
@@ -591,7 +591,7 @@ impl<'lua> Table<'lua> {
|
||||
unsafe { ffi::lua_getreadonly(ref_thread, self.0.index) != 0 }
|
||||
}
|
||||
|
||||
/// Converts the table to a generic C pointer.
|
||||
/// Converts this table to a generic C pointer.
|
||||
///
|
||||
/// Different tables will give different pointers.
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
@@ -721,7 +721,6 @@ impl<'lua> Table<'lua> {
|
||||
TableSequence {
|
||||
table: self.0,
|
||||
index: 1,
|
||||
len: None,
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -733,17 +732,25 @@ impl<'lua> Table<'lua> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
pub(crate) fn sequence_values_by_len<V: FromLua<'lua>>(
|
||||
self,
|
||||
len: Option<usize>,
|
||||
) -> TableSequence<'lua, V> {
|
||||
let len = len.unwrap_or_else(|| self.raw_len()) as Integer;
|
||||
TableSequence {
|
||||
table: self.0,
|
||||
index: 1,
|
||||
len: Some(len),
|
||||
_phantom: PhantomData,
|
||||
pub(crate) fn for_each_value<V>(&self, mut f: impl FnMut(V) -> Result<()>) -> Result<()>
|
||||
where
|
||||
V: FromLua<'lua>,
|
||||
{
|
||||
let lua = self.0.lua;
|
||||
let state = lua.state();
|
||||
unsafe {
|
||||
let _sg = StackGuard::new(state);
|
||||
check_stack(state, 4)?;
|
||||
|
||||
lua.push_ref(&self.0);
|
||||
let len = ffi::lua_rawlen(state, -1);
|
||||
for i in 1..=len {
|
||||
ffi::lua_rawgeti(state, -1, i as _);
|
||||
f(V::from_stack(-1, lua)?)?;
|
||||
ffi::lua_pop(state, 1);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets element value at position `idx` without invoking metamethods.
|
||||
@@ -1085,6 +1092,13 @@ impl<'a, 'lua> Serialize for SerializableTable<'a, 'lua> {
|
||||
use crate::serde::de::{check_value_for_skip, MapPairs};
|
||||
use crate::value::SerializableValue;
|
||||
|
||||
let convert_result = |res: Result<()>, serialize_err: Option<S::Error>| match res {
|
||||
Ok(v) => Ok(v),
|
||||
Err(Error::SerializeError(_)) if serialize_err.is_some() => Err(serialize_err.unwrap()),
|
||||
Err(Error::SerializeError(msg)) => Err(serde::ser::Error::custom(msg)),
|
||||
Err(err) => Err(serde::ser::Error::custom(err.to_string())),
|
||||
};
|
||||
|
||||
let options = self.options;
|
||||
let visited = &self.visited;
|
||||
visited.borrow_mut().insert(self.table.to_pointer());
|
||||
@@ -1093,15 +1107,21 @@ impl<'a, 'lua> Serialize for SerializableTable<'a, 'lua> {
|
||||
let len = self.table.raw_len();
|
||||
if len > 0 || self.table.is_array() {
|
||||
let mut seq = serializer.serialize_seq(Some(len))?;
|
||||
for value in self.table.clone().sequence_values_by_len::<Value>(None) {
|
||||
let value = &value.map_err(serde::ser::Error::custom)?;
|
||||
let skip = check_value_for_skip(value, self.options, &self.visited)
|
||||
.map_err(serde::ser::Error::custom)?;
|
||||
let mut serialize_err = None;
|
||||
let res = self.table.for_each_value::<Value>(|value| {
|
||||
let skip = check_value_for_skip(&value, self.options, &self.visited)
|
||||
.map_err(|err| Error::SerializeError(err.to_string()))?;
|
||||
if skip {
|
||||
continue;
|
||||
// continue iteration
|
||||
return Ok(());
|
||||
}
|
||||
seq.serialize_element(&SerializableValue::new(value, options, Some(visited)))?;
|
||||
}
|
||||
seq.serialize_element(&SerializableValue::new(&value, options, Some(visited)))
|
||||
.map_err(|err| {
|
||||
serialize_err = Some(err);
|
||||
Error::SerializeError(String::new())
|
||||
})
|
||||
});
|
||||
convert_result(res, serialize_err)?;
|
||||
return seq.end();
|
||||
}
|
||||
|
||||
@@ -1138,18 +1158,7 @@ impl<'a, 'lua> Serialize for SerializableTable<'a, 'lua> {
|
||||
process_pair(key, value)
|
||||
})
|
||||
};
|
||||
match res {
|
||||
Ok(_) => {}
|
||||
Err(Error::SerializeError(_)) if serialize_err.is_some() => {
|
||||
return Err(serialize_err.unwrap());
|
||||
}
|
||||
Err(Error::SerializeError(msg)) => {
|
||||
return Err(serde::ser::Error::custom(msg));
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(serde::ser::Error::custom(err.to_string()));
|
||||
}
|
||||
}
|
||||
convert_result(res, serialize_err)?;
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
@@ -1219,9 +1228,9 @@ where
|
||||
///
|
||||
/// [`Table::sequence_values`]: crate::Table::sequence_values
|
||||
pub struct TableSequence<'lua, V> {
|
||||
// TODO: Use `&Table`
|
||||
table: LuaRef<'lua>,
|
||||
index: Integer,
|
||||
len: Option<Integer>,
|
||||
_phantom: PhantomData<V>,
|
||||
}
|
||||
|
||||
@@ -1242,7 +1251,7 @@ where
|
||||
|
||||
lua.push_ref(&self.table);
|
||||
match ffi::lua_rawgeti(state, -1, self.index) {
|
||||
ffi::LUA_TNIL if self.index > self.len.unwrap_or(0) => None,
|
||||
ffi::LUA_TNIL => None,
|
||||
_ => {
|
||||
self.index += 1;
|
||||
Some(V::from_stack(-1, lua))
|
||||
|
||||
+11
-1
@@ -1,4 +1,4 @@
|
||||
use std::os::raw::c_int;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
#[allow(unused)]
|
||||
@@ -375,6 +375,16 @@ impl<'lua> Thread<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this thread to a generic C pointer.
|
||||
///
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
///
|
||||
/// Typically this function is used only for hashing and debug information.
|
||||
#[inline]
|
||||
pub fn to_pointer(&self) -> *const c_void {
|
||||
self.0.to_pointer()
|
||||
}
|
||||
|
||||
/// Convert this handle to owned version.
|
||||
#[cfg(all(feature = "unstable", any(not(feature = "send"), doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", not(feature = "send")))))]
|
||||
|
||||
+32
-13
@@ -5,7 +5,7 @@ use std::fmt;
|
||||
use std::hash::Hash;
|
||||
use std::mem;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::os::raw::{c_char, c_int};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::string::String as StdString;
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
@@ -54,8 +54,8 @@ pub enum MetaMethod {
|
||||
/// The unary minus (`-`) operator.
|
||||
Unm,
|
||||
/// The floor division (//) operator.
|
||||
/// Requires `feature = "lua54/lua53"`
|
||||
#[cfg(any(feature = "lua54", feature = "lua53"))]
|
||||
/// Requires `feature = "lua54/lua53/luau"`
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "luau"))]
|
||||
IDiv,
|
||||
/// The bitwise AND (&) operator.
|
||||
/// Requires `feature = "lua54/lua53"`
|
||||
@@ -180,7 +180,7 @@ impl MetaMethod {
|
||||
MetaMethod::Pow => "__pow",
|
||||
MetaMethod::Unm => "__unm",
|
||||
|
||||
#[cfg(any(feature = "lua54", feature = "lua53"))]
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "luau"))]
|
||||
MetaMethod::IDiv => "__idiv",
|
||||
#[cfg(any(feature = "lua54", feature = "lua53"))]
|
||||
MetaMethod::BAnd => "__band",
|
||||
@@ -815,11 +815,7 @@ impl OwnedAnyUserData {
|
||||
impl<'lua> AnyUserData<'lua> {
|
||||
/// Checks whether the type of this userdata is `T`.
|
||||
pub fn is<T: 'static>(&self) -> bool {
|
||||
match self.inspect(|_: &UserDataCell<T>| Ok(())) {
|
||||
Ok(()) => true,
|
||||
Err(Error::UserDataTypeMismatch) => false,
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
self.inspect(|_: &UserDataCell<T>| Ok(())).is_ok()
|
||||
}
|
||||
|
||||
/// Borrow this userdata immutably if it is of type `T`.
|
||||
@@ -919,7 +915,7 @@ impl<'lua> AnyUserData<'lua> {
|
||||
check_stack(state, 5)?;
|
||||
|
||||
lua.push_userdata_ref(&self.0)?;
|
||||
lua.push_value(v.into_lua(lua)?)?;
|
||||
lua.push(v)?;
|
||||
|
||||
#[cfg(feature = "lua54")]
|
||||
if n < USER_VALUE_MAXSLOT {
|
||||
@@ -1014,7 +1010,7 @@ impl<'lua> AnyUserData<'lua> {
|
||||
check_stack(state, 5)?;
|
||||
|
||||
lua.push_userdata_ref(&self.0)?;
|
||||
lua.push_value(v.into_lua(lua)?)?;
|
||||
lua.push(v)?;
|
||||
|
||||
// Multiple (extra) user values are emulated by storing them in a table
|
||||
protect_lua!(state, 2, 0, |state| {
|
||||
@@ -1096,6 +1092,16 @@ impl<'lua> AnyUserData<'lua> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this userdata to a generic C pointer.
|
||||
///
|
||||
/// There is no way to convert the pointer back to its original value.
|
||||
///
|
||||
/// Typically this function is used only for hashing and debug information.
|
||||
#[inline]
|
||||
pub fn to_pointer(&self) -> *const c_void {
|
||||
self.0.to_pointer()
|
||||
}
|
||||
|
||||
/// Convert this handle to owned version.
|
||||
#[cfg(all(feature = "unstable", any(not(feature = "send"), doc)))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "unstable", not(feature = "send")))))]
|
||||
@@ -1334,6 +1340,19 @@ impl<'lua> Serialize for AnyUserData<'lua> {
|
||||
S: Serializer,
|
||||
{
|
||||
let lua = self.0.lua;
|
||||
|
||||
// Special case for Luau buffer type
|
||||
#[cfg(feature = "luau")]
|
||||
if self.1 == SubtypeId::Buffer {
|
||||
let buf = unsafe {
|
||||
let mut size = 0usize;
|
||||
let buf = ffi::lua_tobuffer(lua.ref_thread(), self.0.index, &mut size);
|
||||
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
|
||||
std::slice::from_raw_parts(buf as *const u8, size)
|
||||
};
|
||||
return serializer.serialize_bytes(buf);
|
||||
}
|
||||
|
||||
let data = unsafe {
|
||||
let _ = lua
|
||||
.get_userdata_ref_type_id(&self.0)
|
||||
@@ -1352,7 +1371,7 @@ impl<'lua> Serialize for AnyUserData<'lua> {
|
||||
/// A wrapper type for an immutably borrowed value from a `AnyUserData`.
|
||||
///
|
||||
/// It implements [`FromLua`] and can be used to receive a typed userdata from Lua.
|
||||
pub struct UserDataRef<'lua, T: 'static>(AnyUserData<'lua>, Ref<'lua, T>);
|
||||
pub struct UserDataRef<'lua, T: 'static>(#[allow(unused)] AnyUserData<'lua>, Ref<'lua, T>);
|
||||
|
||||
impl<'lua, T: 'static> Deref for UserDataRef<'lua, T> {
|
||||
type Target = T;
|
||||
@@ -1374,7 +1393,7 @@ impl<'lua, T: 'static> UserDataRef<'lua, T> {
|
||||
/// A wrapper type for a mutably borrowed value from a `AnyUserData`.
|
||||
///
|
||||
/// It implements [`FromLua`] and can be used to receive a typed userdata from Lua.
|
||||
pub struct UserDataRefMut<'lua, T: 'static>(AnyUserData<'lua>, RefMut<'lua, T>);
|
||||
pub struct UserDataRefMut<'lua, T: 'static>(#[allow(unused)] AnyUserData<'lua>, RefMut<'lua, T>);
|
||||
|
||||
impl<'lua, T: 'static> Deref for UserDataRefMut<'lua, T> {
|
||||
type Target = T;
|
||||
|
||||
+17
-1
@@ -253,6 +253,20 @@ pub unsafe fn push_string(state: *mut ffi::lua_State, s: &[u8], protect: bool) -
|
||||
}
|
||||
}
|
||||
|
||||
// Uses 3 stack spaces (when protect), does not call checkstack.
|
||||
#[cfg(feature = "luau")]
|
||||
#[inline(always)]
|
||||
pub unsafe fn push_buffer(state: *mut ffi::lua_State, b: &[u8], protect: bool) -> Result<()> {
|
||||
let data = if protect {
|
||||
protect_lua!(state, 0, 1, |state| ffi::lua_newbuffer(state, b.len()))?
|
||||
} else {
|
||||
ffi::lua_newbuffer(state, b.len())
|
||||
};
|
||||
let buf = slice::from_raw_parts_mut(data as *mut u8, b.len());
|
||||
buf.copy_from_slice(b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Uses 3 stack spaces, does not call checkstack.
|
||||
#[inline]
|
||||
pub unsafe fn push_table(
|
||||
@@ -928,7 +942,7 @@ pub unsafe fn init_error_registry(state: *mut ffi::lua_State) -> Result<()> {
|
||||
"__mod",
|
||||
"__pow",
|
||||
"__unm",
|
||||
#[cfg(any(feature = "lua54", feature = "lua53"))]
|
||||
#[cfg(any(feature = "lua54", feature = "lua53", feature = "luau"))]
|
||||
"__idiv",
|
||||
#[cfg(any(feature = "lua54", feature = "lua53"))]
|
||||
"__band",
|
||||
@@ -1045,6 +1059,8 @@ pub(crate) unsafe fn to_string(state: *mut ffi::lua_State, index: c_int) -> Stri
|
||||
ffi::LUA_TTHREAD => format!("<thread {:?}>", ffi::lua_topointer(state, index)),
|
||||
#[cfg(feature = "luau")]
|
||||
ffi::LUA_TBUFFER => format!("<buffer {:?}>", ffi::lua_topointer(state, index)),
|
||||
#[cfg(feature = "luajit")]
|
||||
ffi::LUA_TCDATA => format!("<cdata {:?}>", ffi::lua_topointer(state, index)),
|
||||
_ => "<unknown>".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
+4
-6
@@ -1,7 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashSet;
|
||||
use std::iter::{self, FromIterator};
|
||||
use std::iter;
|
||||
use std::ops::Index;
|
||||
use std::os::raw::{c_int, c_void};
|
||||
use std::string::String as StdString;
|
||||
@@ -15,7 +15,7 @@ use {
|
||||
crate::table::SerializableTable,
|
||||
rustc_hash::FxHashSet,
|
||||
serde::ser::{self, Serialize, Serializer},
|
||||
std::{cell::RefCell, convert::TryInto, rc::Rc, result::Result as StdResult},
|
||||
std::{cell::RefCell, rc::Rc, result::Result as StdResult},
|
||||
};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
@@ -252,8 +252,7 @@ impl<'lua> Value<'lua> {
|
||||
/// If the value is a Lua [`Integer`], try to convert it to `i64` or return `None` otherwise.
|
||||
#[inline]
|
||||
pub fn as_i64(&self) -> Option<i64> {
|
||||
#[allow(clippy::useless_conversion)]
|
||||
self.as_integer().and_then(|i| i64::try_from(i).ok())
|
||||
self.as_integer().map(i64::from)
|
||||
}
|
||||
|
||||
/// Cast the value to `u64`.
|
||||
@@ -659,8 +658,7 @@ impl<'a, 'lua> Serialize for SerializableValue<'a, 'lua> {
|
||||
Value::Nil => serializer.serialize_unit(),
|
||||
Value::Boolean(b) => serializer.serialize_bool(*b),
|
||||
#[allow(clippy::useless_conversion)]
|
||||
Value::Integer(i) => serializer
|
||||
.serialize_i64((*i).try_into().expect("cannot convert Lua Integer to i64")),
|
||||
Value::Integer(i) => serializer.serialize_i64((*i).into()),
|
||||
Value::Number(n) => serializer.serialize_f64(*n),
|
||||
#[cfg(feature = "luau")]
|
||||
Value::Vector(v) => v.serialize(serializer),
|
||||
|
||||
+108
-7
@@ -2,8 +2,29 @@ use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::ffi::{CStr, CString};
|
||||
|
||||
use bstr::BString;
|
||||
use maplit::{btreemap, btreeset, hashmap, hashset};
|
||||
use mlua::{AnyUserData, Error, Function, IntoLua, Lua, Result, Table, Thread, UserDataRef, Value};
|
||||
use mlua::{
|
||||
AnyUserData, Error, Function, IntoLua, Lua, RegistryKey, Result, Table, Thread, UserDataRef,
|
||||
Value,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_value_into_lua() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
// Direct conversion
|
||||
let v = Value::Boolean(true);
|
||||
let v2 = (&v).into_lua(&lua)?;
|
||||
assert_eq!(v, v2);
|
||||
|
||||
// Push into stack
|
||||
let table = lua.create_table()?;
|
||||
table.set("v", &v)?;
|
||||
assert_eq!(v, table.get::<_, Value>("v")?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_into_lua() -> Result<()> {
|
||||
@@ -212,14 +233,22 @@ fn test_owned_anyuserdata_into_lua() -> Result<()> {
|
||||
fn test_registry_value_into_lua() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let t = lua.create_table()?;
|
||||
let r = lua.create_registry_value(t)?;
|
||||
let f = lua.create_function(|_, t: Table| t.raw_set("hello", "world"))?;
|
||||
// Direct conversion
|
||||
let s = lua.create_string("hello, world")?;
|
||||
let r = lua.create_registry_value(&s)?;
|
||||
let value1 = lua.pack(&r)?;
|
||||
let value2 = lua.pack(r)?;
|
||||
assert_eq!(value1.as_str(), Some("hello, world"));
|
||||
assert_eq!(value2.to_pointer(), value2.to_pointer());
|
||||
|
||||
f.call(&r)?;
|
||||
let v = r.into_lua(&lua)?;
|
||||
let t = v.as_table().unwrap();
|
||||
// Push into stack
|
||||
let t = lua.create_table()?;
|
||||
let r = lua.create_registry_value(&t)?;
|
||||
let f = lua.create_function(|_, (t, k, v): (Table, Value, Value)| t.set(k, v))?;
|
||||
f.call((&r, "hello", "world"))?;
|
||||
f.call((r, "welcome", "to the jungle"))?;
|
||||
assert_eq!(t.get::<_, String>("hello")?, "world");
|
||||
assert_eq!(t.get::<_, String>("welcome")?, "to the jungle");
|
||||
|
||||
// Try to set nil registry key
|
||||
let r_nil = lua.create_registry_value(Value::Nil)?;
|
||||
@@ -237,6 +266,17 @@ fn test_registry_value_into_lua() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_registry_key_from_lua() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let fkey = lua.load("function() return 1 end").eval::<RegistryKey>()?;
|
||||
let f = lua.registry_value::<Function>(&fkey)?;
|
||||
assert_eq!(f.call::<_, i32>(())?, 1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conv_vec() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
@@ -370,3 +410,64 @@ fn test_conv_array() -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bstring_from_lua() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let s = lua.create_string("hello, world")?;
|
||||
let bstr = lua.unpack::<BString>(Value::String(s))?;
|
||||
assert_eq!(bstr, "hello, world");
|
||||
|
||||
let bstr = lua.unpack::<BString>(Value::Integer(123))?;
|
||||
assert_eq!(bstr, "123");
|
||||
|
||||
let bstr = lua.unpack::<BString>(Value::Number(-123.55))?;
|
||||
assert_eq!(bstr, "-123.55");
|
||||
|
||||
// Test from stack
|
||||
let f = lua.create_function(|_, bstr: BString| Ok(bstr))?;
|
||||
let bstr = f.call::<_, BString>("hello, world")?;
|
||||
assert_eq!(bstr, "hello, world");
|
||||
|
||||
let bstr = f.call::<_, BString>(-43.22)?;
|
||||
assert_eq!(bstr, "-43.22");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
#[test]
|
||||
fn test_bstring_from_lua_buffer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let b = lua.create_buffer("hello, world")?;
|
||||
let bstr = lua.unpack::<BString>(Value::UserData(b))?;
|
||||
assert_eq!(bstr, "hello, world");
|
||||
|
||||
// Test from stack
|
||||
let f = lua.create_function(|_, bstr: BString| Ok(bstr))?;
|
||||
let buf = lua.create_buffer("hello, world")?;
|
||||
let bstr = f.call::<_, BString>(buf)?;
|
||||
assert_eq!(bstr, "hello, world");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_option_into_from_lua() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
// Direct conversion
|
||||
let v = Some(42);
|
||||
let v2 = v.into_lua(&lua)?;
|
||||
assert_eq!(v, v2.as_i32());
|
||||
|
||||
// Push into stack / get from stack
|
||||
let f = lua.create_function(|_, v: Option<i32>| Ok(v))?;
|
||||
assert_eq!(f.call::<_, Option<i32>>(Some(42))?, Some(42));
|
||||
assert_eq!(f.call::<_, Option<i32>>(Option::<i32>::None)?, None);
|
||||
assert_eq!(f.call::<_, Option<i32>>(())?, None);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -231,6 +231,40 @@ fn test_function_info() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_function_pointer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let func1 = lua.load("return function() end").into_function()?;
|
||||
let func2 = func1.call::<_, Function>(())?;
|
||||
|
||||
assert_eq!(func1.to_pointer(), func1.clone().to_pointer());
|
||||
assert_ne!(func1.to_pointer(), func2.to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
#[test]
|
||||
fn test_function_deep_clone() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
lua.globals().set("a", 1)?;
|
||||
let func1 = lua.load("a += 1; return a").into_function()?;
|
||||
let func2 = func1.deep_clone();
|
||||
|
||||
assert_ne!(func1.to_pointer(), func2.to_pointer());
|
||||
assert_eq!(func1.call::<_, i32>(())?, 2);
|
||||
assert_eq!(func2.call::<_, i32>(())?, 3);
|
||||
|
||||
// Check that for Rust functions deep_clone is just a clone
|
||||
let rust_func = lua.create_function(|_, ()| Ok(42))?;
|
||||
let rust_func2 = rust_func.deep_clone();
|
||||
assert_eq!(rust_func.to_pointer(), rust_func2.to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_function_wrap() -> Result<()> {
|
||||
use mlua::Error;
|
||||
|
||||
@@ -275,6 +275,22 @@ fn test_sandbox() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_nolibs() -> Result<()> {
|
||||
let lua = Lua::new_with(StdLib::NONE, LuaOptions::default()).unwrap();
|
||||
|
||||
lua.sandbox(true)?;
|
||||
lua.load("global = 123").exec()?;
|
||||
let n: i32 = lua.load("return global").eval()?;
|
||||
assert_eq!(n, 123);
|
||||
assert_eq!(lua.globals().get::<_, Option<i32>>("global")?, Some(123));
|
||||
|
||||
lua.sandbox(false)?;
|
||||
assert_eq!(lua.globals().get::<_, Option<i32>>("global")?, None);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sandbox_threads() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ fn test_gc_control() -> Result<()> {
|
||||
|
||||
assert_eq!(lua.gc_inc(200, 100, 13), GCMode::Incremental);
|
||||
|
||||
struct MyUserdata(Arc<()>);
|
||||
struct MyUserdata(#[allow(unused)] Arc<()>);
|
||||
impl UserData for MyUserdata {}
|
||||
|
||||
let rc = Arc::new(());
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
use mlua::{Error, ExternalError, IntoLuaMulti, Lua, Result, String, Value};
|
||||
|
||||
#[test]
|
||||
fn test_result_conversions() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
let globals = lua.globals();
|
||||
|
||||
let ok = lua.create_function(|_, ()| Ok(Ok::<(), Error>(())))?;
|
||||
let err = lua.create_function(|_, ()| Ok(Err::<(), _>("failure1".into_lua_err())))?;
|
||||
let ok2 = lua.create_function(|_, ()| Ok(Ok::<_, Error>("!".to_owned())))?;
|
||||
let err2 = lua.create_function(|_, ()| Ok(Err::<String, _>("failure2".into_lua_err())))?;
|
||||
|
||||
globals.set("ok", ok)?;
|
||||
globals.set("ok2", ok2)?;
|
||||
globals.set("err", err)?;
|
||||
globals.set("err2", err2)?;
|
||||
|
||||
lua.load(
|
||||
r#"
|
||||
local r, e = ok()
|
||||
assert(r == nil and e == nil)
|
||||
|
||||
local r, e = err()
|
||||
assert(r == nil)
|
||||
assert(tostring(e):find("failure1") ~= nil)
|
||||
|
||||
local r, e = ok2()
|
||||
assert(r == "!")
|
||||
assert(e == nil)
|
||||
|
||||
local r, e = err2()
|
||||
assert(r == nil)
|
||||
assert(tostring(e):find("failure2") ~= nil)
|
||||
"#,
|
||||
)
|
||||
.exec()?;
|
||||
|
||||
// Try to convert Result into MultiValue
|
||||
let ok1 = Ok::<(), Error>(());
|
||||
let multi_ok1 = ok1.into_lua_multi(&lua)?;
|
||||
assert_eq!(multi_ok1.len(), 0);
|
||||
let err1 = Err::<(), _>("failure1");
|
||||
let multi_err1 = err1.into_lua_multi(&lua)?;
|
||||
assert_eq!(multi_err1.len(), 2);
|
||||
assert_eq!(multi_err1[0], Value::Nil);
|
||||
assert_eq!(multi_err1[1].as_str().unwrap(), "failure1");
|
||||
|
||||
let ok2 = Ok::<_, Error>("!");
|
||||
let multi_ok2 = ok2.into_lua_multi(&lua)?;
|
||||
assert_eq!(multi_ok2.len(), 1);
|
||||
assert_eq!(multi_ok2[0].as_str().unwrap(), "!");
|
||||
let err2 = Err::<String, _>("failure2".into_lua_err());
|
||||
let multi_err2 = err2.into_lua_multi(&lua)?;
|
||||
assert_eq!(multi_err2.len(), 2);
|
||||
assert_eq!(multi_err2[0], Value::Nil);
|
||||
assert!(matches!(multi_err2[1], Value::Error(_)));
|
||||
assert_eq!(multi_err2[1].to_string()?, "failure2");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+10
-10
@@ -155,14 +155,14 @@ fn test_scope_userdata_functions() -> Result<()> {
|
||||
|
||||
impl<'a> UserData for MyUserData<'a> {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
methods.add_meta_function(MetaMethod::Add, |lua, ()| {
|
||||
methods.add_meta_method(MetaMethod::Add, |lua, this, ()| {
|
||||
let globals = lua.globals();
|
||||
globals.set("i", globals.get::<_, i64>("i")? + 1)?;
|
||||
globals.set("i", globals.get::<_, i64>("i")? + this.0)?;
|
||||
Ok(())
|
||||
});
|
||||
methods.add_meta_function(MetaMethod::Sub, |lua, ()| {
|
||||
methods.add_meta_method(MetaMethod::Sub, |lua, this, ()| {
|
||||
let globals = lua.globals();
|
||||
globals.set("i", globals.get::<_, i64>("i")? + 1)?;
|
||||
globals.set("i", globals.get::<_, i64>("i")? + this.0)?;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fn test_scope_userdata_functions() -> Result<()> {
|
||||
|
||||
let lua = Lua::new();
|
||||
|
||||
let dummy = 0;
|
||||
let dummy = 1;
|
||||
let f = lua
|
||||
.load(
|
||||
r#"
|
||||
@@ -178,7 +178,7 @@ fn test_scope_userdata_functions() -> Result<()> {
|
||||
return function(u)
|
||||
_ = u + u
|
||||
_ = u - 1
|
||||
_ = 1 + u
|
||||
_ = u + 1
|
||||
end
|
||||
"#,
|
||||
)
|
||||
@@ -257,7 +257,7 @@ fn test_scope_userdata_mismatch() -> Result<()> {
|
||||
fn test_scope_userdata_drop() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
struct MyUserData(Rc<()>);
|
||||
struct MyUserData(#[allow(unused)] Rc<()>);
|
||||
|
||||
impl UserData for MyUserData {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
@@ -265,7 +265,7 @@ fn test_scope_userdata_drop() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
struct MyUserDataArc(Arc<()>);
|
||||
struct MyUserDataArc(#[allow(unused)] Arc<()>);
|
||||
|
||||
impl UserData for MyUserDataArc {}
|
||||
|
||||
@@ -315,7 +315,7 @@ fn test_scope_userdata_drop() -> Result<()> {
|
||||
fn test_scope_nonstatic_userdata_drop() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
struct MyUserData<'a>(&'a Cell<i64>, Arc<()>);
|
||||
struct MyUserData<'a>(&'a Cell<i64>, #[allow(unused)] Arc<()>);
|
||||
|
||||
impl<'a> UserData for MyUserData<'a> {
|
||||
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
|
||||
@@ -326,7 +326,7 @@ fn test_scope_nonstatic_userdata_drop() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
struct MyUserDataArc(Arc<()>);
|
||||
struct MyUserDataArc(#[allow(unused)] Arc<()>);
|
||||
|
||||
impl UserData for MyUserDataArc {}
|
||||
|
||||
|
||||
+74
-1
@@ -99,7 +99,7 @@ fn test_serialize_in_scope() -> LuaResult<()> {
|
||||
Err(e) => panic!("expected destructed error, got {}", e),
|
||||
}
|
||||
|
||||
struct MyUserDataRef<'a>(&'a ());
|
||||
struct MyUserDataRef<'a>(#[allow(unused)] &'a ());
|
||||
|
||||
impl<'a> UserData for MyUserDataRef<'a> {}
|
||||
|
||||
@@ -115,6 +115,21 @@ fn test_serialize_in_scope() -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_any_userdata() -> Result<(), Box<dyn StdError>> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let json_val = serde_json::json!({
|
||||
"a": 1,
|
||||
"b": "test",
|
||||
});
|
||||
let json_ud = lua.create_ser_any_userdata(json_val)?;
|
||||
let json_str = serde_json::to_string_pretty(&json_ud)?;
|
||||
assert_eq!(json_str, "{\n \"a\": 1,\n \"b\": \"test\"\n}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_failure() -> Result<(), Box<dyn StdError>> {
|
||||
#[derive(Serialize)]
|
||||
@@ -697,3 +712,61 @@ fn test_from_value_sorted() -> Result<(), Box<dyn StdError>> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_arbitrary_precision() {
|
||||
let lua = Lua::new();
|
||||
|
||||
let opts = SerializeOptions::new().detect_serde_json_arbitrary_precision(true);
|
||||
|
||||
// Number
|
||||
let num = serde_json::Value::Number(serde_json::Number::from_f64(1.244e2).unwrap());
|
||||
let num = lua.to_value_with(&num, opts).unwrap();
|
||||
assert_eq!(num, Value::Number(1.244e2));
|
||||
|
||||
// Integer
|
||||
let num = serde_json::Value::Number(serde_json::Number::from_f64(123.0).unwrap());
|
||||
let num = lua.to_value_with(&num, opts).unwrap();
|
||||
assert_eq!(num, Value::Integer(123));
|
||||
|
||||
// Max u64
|
||||
let num = serde_json::Value::Number(serde_json::Number::from(i64::MAX));
|
||||
let num = lua.to_value_with(&num, opts).unwrap();
|
||||
assert_eq!(num, Value::Number(i64::MAX as f64));
|
||||
|
||||
// Check that the option is disabled by default
|
||||
let num = serde_json::Value::Number(serde_json::Number::from_f64(1.244e2).unwrap());
|
||||
let num = lua.to_value(&num).unwrap();
|
||||
assert_eq!(num.type_name(), "table");
|
||||
assert_eq!(
|
||||
format!("{:#?}", num),
|
||||
"{\n [\"$serde_json::private::Number\"] = \"124.4\",\n}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
#[test]
|
||||
fn test_buffer_serialize() {
|
||||
let lua = Lua::new();
|
||||
|
||||
let buf = lua.create_buffer(&[1, 2, 3, 4]).unwrap();
|
||||
let val = serde_value::to_value(&buf).unwrap();
|
||||
assert_eq!(val, serde_value::Value::Bytes(vec![1, 2, 3, 4]));
|
||||
|
||||
// Try empty buffer
|
||||
let buf = lua.create_buffer(&[]).unwrap();
|
||||
let val = serde_value::to_value(&buf).unwrap();
|
||||
assert_eq!(val, serde_value::Value::Bytes(vec![]));
|
||||
}
|
||||
|
||||
#[cfg(feature = "luau")]
|
||||
#[test]
|
||||
fn test_buffer_from_value() {
|
||||
let lua = Lua::new();
|
||||
|
||||
let buf = lua.create_buffer(&[1, 2, 3, 4]).unwrap();
|
||||
let val = lua
|
||||
.from_value::<serde_value::Value>(Value::UserData(buf))
|
||||
.unwrap();
|
||||
assert_eq!(val, serde_value::Value::Bytes(vec![1, 2, 3, 4]));
|
||||
}
|
||||
|
||||
@@ -99,6 +99,19 @@ fn test_string_debug() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_string_pointer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let str1 = lua.create_string("hello")?;
|
||||
let str2 = lua.create_string("hello")?;
|
||||
|
||||
// Lua uses string interning, so these should be the same
|
||||
assert_eq!(str1.to_pointer(), str2.to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", not(feature = "send")))]
|
||||
#[test]
|
||||
fn test_owned_string() -> Result<()> {
|
||||
|
||||
@@ -369,6 +369,19 @@ fn test_table_eq() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_table_pointer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let table1 = lua.create_table()?;
|
||||
let table2 = lua.create_table()?;
|
||||
|
||||
assert_eq!(table1.to_pointer(), table1.clone().to_pointer());
|
||||
assert_ne!(table1.to_pointer(), table2.to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_table_error() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
+1
-39
@@ -504,44 +504,6 @@ fn test_panic() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_result_conversions() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
let globals = lua.globals();
|
||||
|
||||
let ok = lua.create_function(|_, ()| Ok(Ok::<(), Error>(())))?;
|
||||
let err = lua.create_function(|_, ()| Ok(Err::<(), _>("failure1".into_lua_err())))?;
|
||||
let ok2 = lua.create_function(|_, ()| Ok(Ok::<_, Error>("!".to_owned())))?;
|
||||
let err2 = lua.create_function(|_, ()| Ok(Err::<String, _>("failure2".into_lua_err())))?;
|
||||
|
||||
globals.set("ok", ok)?;
|
||||
globals.set("ok2", ok2)?;
|
||||
globals.set("err", err)?;
|
||||
globals.set("err2", err2)?;
|
||||
|
||||
lua.load(
|
||||
r#"
|
||||
local r, e = ok()
|
||||
assert(r == nil and e == nil)
|
||||
|
||||
local r, e = err()
|
||||
assert(r == nil)
|
||||
assert(tostring(e):find("failure1") ~= nil)
|
||||
|
||||
local r, e = ok2()
|
||||
assert(r == "!")
|
||||
assert(e == nil)
|
||||
|
||||
local r, e = err2()
|
||||
assert(r == nil)
|
||||
assert(tostring(e):find("failure2") ~= nil)
|
||||
"#,
|
||||
)
|
||||
.exec()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_num_conversion() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
@@ -781,7 +743,7 @@ fn test_registry_value() -> Result<()> {
|
||||
|
||||
#[test]
|
||||
fn test_drop_registry_value() -> Result<()> {
|
||||
struct MyUserdata(Arc<()>);
|
||||
struct MyUserdata(#[allow(unused)] Arc<()>);
|
||||
|
||||
impl UserData for MyUserdata {}
|
||||
|
||||
|
||||
+14
-1
@@ -101,7 +101,7 @@ fn test_thread_reset() -> Result<()> {
|
||||
|
||||
let lua = Lua::new();
|
||||
|
||||
struct MyUserData(Arc<()>);
|
||||
struct MyUserData(#[allow(unused)] Arc<()>);
|
||||
impl UserData for MyUserData {}
|
||||
|
||||
let arc = Arc::new(());
|
||||
@@ -191,6 +191,19 @@ fn test_coroutine_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thread_pointer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let func = lua.load("return 123").into_function()?;
|
||||
let thread = lua.create_thread(func.clone())?;
|
||||
|
||||
assert_eq!(thread.to_pointer(), thread.clone().to_pointer());
|
||||
assert_ne!(thread.to_pointer(), lua.current_thread().to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", not(feature = "send")))]
|
||||
#[test]
|
||||
fn test_owned_thread() -> Result<()> {
|
||||
|
||||
+17
-1
@@ -370,6 +370,8 @@ fn test_userdata_take() -> Result<()> {
|
||||
r => panic!("improper return for destructed userdata: {:?}", r),
|
||||
}
|
||||
|
||||
assert!(!userdata.is::<MyUserdata>());
|
||||
|
||||
drop(userdata);
|
||||
lua.globals().raw_remove("userdata")?;
|
||||
lua.gc_collect()?;
|
||||
@@ -400,7 +402,7 @@ fn test_userdata_take() -> Result<()> {
|
||||
|
||||
#[test]
|
||||
fn test_userdata_destroy() -> Result<()> {
|
||||
struct MyUserdata(Arc<()>);
|
||||
struct MyUserdata(#[allow(unused)] Arc<()>);
|
||||
|
||||
impl UserData for MyUserdata {}
|
||||
|
||||
@@ -951,6 +953,20 @@ fn test_userdata_method_errors() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_userdata_pointer() -> Result<()> {
|
||||
let lua = Lua::new();
|
||||
|
||||
let ud1 = lua.create_any_userdata("hello")?;
|
||||
let ud2 = lua.create_any_userdata("hello")?;
|
||||
|
||||
assert_eq!(ud1.to_pointer(), ud1.clone().to_pointer());
|
||||
// Different userdata objects with the same value should have different pointers
|
||||
assert_ne!(ud1.to_pointer(), ud2.to_pointer());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "unstable", not(feature = "send")))]
|
||||
#[test]
|
||||
fn test_owned_userdata() -> Result<()> {
|
||||
|
||||
Reference in New Issue
Block a user