Skip to content

Add load/loadfile etc. wrappers #236

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 20 commits into from
Jan 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,18 @@ jobs:
- restore_cache:
keys:
- cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }}
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- run:
name: Build all targets
command: cargo build --all --all-targets
- run:
name: Run all tests
command: cargo test --all
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- save_cache:
paths:
- /usr/local/cargo/registry
Expand All @@ -58,18 +58,18 @@ jobs:
- restore_cache:
keys:
- cargo-cache-lua53-{{ arch }}-{{ checksum "Cargo.lock" }}
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- run:
name: Build all targets
command: cargo build --no-default-features --features=builtin-lua53 --all --all-targets
- run:
name: Run all tests
command: cargo test --no-default-features --features=builtin-lua53 --all
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- save_cache:
paths:
- /usr/local/cargo/registry
Expand Down Expand Up @@ -102,18 +102,18 @@ jobs:
- restore_cache:
keys:
- cargo-cache-lua51-{{ arch }}-{{ checksum "Cargo.lock" }}
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- run:
name: Build all targets
command: cargo build --no-default-features --features=system-lua51 --all --all-targets
- run:
name: Run all tests
command: cargo test --no-default-features --features=system-lua51 --all
- run:
name: Check Formatting
command: |
rustup component add rustfmt
rustfmt --version
cargo fmt --all -- --check --color=auto
- save_cache:
paths:
- /usr/local/cargo/registry
Expand Down
6 changes: 3 additions & 3 deletions crates/rlua-lua51-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub use {

pub use {
bindings::lua_Alloc, bindings::lua_CFunction, bindings::lua_Debug, bindings::lua_Integer,
bindings::lua_Number, bindings::lua_State,
bindings::lua_Number, bindings::lua_State, bindings::lua_Writer,
};

/*
Expand Down Expand Up @@ -143,8 +143,8 @@ pub use bindings::lua_gc;
** miscellaneous functions
*/
pub use {
bindings::lua_concat, bindings::lua_error, bindings::lua_getallocf, bindings::lua_next,
bindings::lua_setallocf,
bindings::lua_concat, bindings::lua_dump, bindings::lua_error, bindings::lua_getallocf,
bindings::lua_next, bindings::lua_setallocf,
};

/*
Expand Down
35 changes: 28 additions & 7 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,26 +856,32 @@ impl<'lua> Context<'lua> {
source: &[u8],
name: Option<&CString>,
env: Option<Value<'lua>>,
allow_binary: bool,
) -> Result<Function<'lua>> {
unsafe {
let _sg = StackGuard::new(self.state);
assert_stack(self.state, 1);
let mode = if allow_binary {
cstr!("bt")
} else {
cstr!("t")
};

match if let Some(name) = name {
loadbufferx(
self.state,
source.as_ptr() as *const c_char,
source.len(),
name.as_ptr() as *const c_char,
cstr!("t"),
mode,
)
} else {
loadbufferx(
self.state,
source.as_ptr() as *const c_char,
source.len(),
ptr::null(),
cstr!("t"),
mode,
)
} {
ffi::LUA_OK => {
Expand Down Expand Up @@ -956,10 +962,12 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
// actual lua repl does.
let mut expression_source = b"return ".to_vec();
expression_source.extend(self.source);
if let Ok(function) =
self.context
.load_chunk(&expression_source, self.name.as_ref(), self.env.clone())
{
if let Ok(function) = self.context.load_chunk(
&expression_source,
self.name.as_ref(),
self.env.clone(),
false,
) {
function.call(())
} else {
self.call(())
Expand All @@ -978,7 +986,20 @@ impl<'lua, 'a> Chunk<'lua, 'a> {
/// This simply compiles the chunk without actually executing it.
pub fn into_function(self) -> Result<Function<'lua>> {
self.context
.load_chunk(self.source, self.name.as_ref(), self.env)
.load_chunk(self.source, self.name.as_ref(), self.env, false)
}

/// Load this chunk into a regular `Function`.
///
/// This simply compiles the chunk without actually executing it.
/// Unlike `into_function`, this method allows loading code previously
/// compiled and saved with `Function::dump` or `string.dump()`.
/// This method is unsafe because there is no check that the precompiled
/// Lua code is valid; if it is not this may cause a crash or other
/// undefined behaviour.
pub unsafe fn into_function_allow_binary(self) -> Result<Function<'lua>> {
self.context
.load_chunk(self.source, self.name.as_ref(), self.env, true)
}
}

Expand Down
60 changes: 59 additions & 1 deletion src/function.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use std::os::raw::c_int;
use std::ptr;

use libc::c_void;

use crate::error::{Error, Result};
use crate::ffi;
use crate::types::LuaRef;
use crate::util::{
assert_stack, check_stack, error_traceback, pop_error, protect_lua_closure, rotate, StackGuard,
assert_stack, check_stack, dump, error_traceback, pop_error, protect_lua_closure, rotate,
StackGuard,
};
use crate::value::{FromLuaMulti, MultiValue, ToLuaMulti};

Expand Down Expand Up @@ -161,4 +164,59 @@ impl<'lua> Function<'lua> {
Ok(Function(lua.pop_ref()))
}
}

/// Dumps the compiled representation of the function into a binary blob,
/// which can later be loaded using the unsafe Chunk::into_function_allow_binary().
///
/// # Examples
///
/// ```
/// # use rlua::{Lua, Function, Result};
/// # fn main() -> Result<()> {
/// # Lua::new().context(|lua_context| {
/// let add2: Function = lua_context.load(r#"
/// function(a)
/// return a + 2
/// end
/// "#).eval()?;
///
/// let dumped = add2.dump()?;
///
/// let reloaded = unsafe {
/// lua_context.load(&dumped)
/// .into_function_allow_binary()?
/// };
/// assert_eq!(reloaded.call::<_, u32>(7)?, 7+2);
///
/// # Ok(())
/// # })
/// # }
/// ```
pub fn dump(&self) -> Result<Vec<u8>> {
unsafe extern "C" fn writer(
_state: *mut ffi::lua_State,
p: *const c_void,
sz: usize,
ud: *mut c_void,
) -> c_int {
let input_slice = std::slice::from_raw_parts(p as *const u8, sz);
let vec = &mut *(ud as *mut Vec<u8>);
vec.extend_from_slice(input_slice);
0
}
let lua = self.0.lua;
let mut bytes = Vec::new();
unsafe {
let _sg = StackGuard::new(lua.state);
check_stack(lua.state, 1)?;
let bytes_ptr = &mut bytes as *mut _;
protect_lua_closure(lua.state, 0, 0, |state| {
lua.push_ref(&self.0);
let dump_result = dump(state, Some(writer), bytes_ptr as *mut c_void, 0);
// It can only return an error from our writer.
debug_assert_eq!(dump_result, 0);
})?;
}
Ok(bytes)
}
}
Loading