Skip to content

Commit

Permalink
rust: Create separate high-level struct instead of wrapping FFI
Browse files Browse the repository at this point in the history
  • Loading branch information
jakelang committed Mar 15, 2019
1 parent 349b283 commit ad02bad
Showing 1 changed file with 48 additions and 3 deletions.
51 changes: 48 additions & 3 deletions bindings/rust/evmc-vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,52 @@ pub use evmc_sys as ffi;
// TODO: Add a derive macro here for creating evmc_create

/// EVMC result structure.
pub struct ExecutionResult(Box<ffi::evmc_result>);
pub struct ExecutionResult {
status: ffi::evmc_status_code,
gas: i64,
output: Option<Vec<u8>>,
release_fn: Option<unsafe extern "C" fn(*const ffi::evmc_result)>,
create_addr: Option<ffi::evmc_address>,
}

impl From<ffi::evmc_result> for ExecutionResult {
fn from(result: ffi::evmc_result) -> Self {
let ret = ExecutionResult {
status: result.status_code.clone(), // Maybe explicit copying not needed?
gas: result.gas_left.clone(),
output: if !result.output_data.is_null() {
// Pre-allocate a vector.
let mut buf: Vec<u8> = Vec::with_capacity(result.output_size);

// Copy from the C struct's buffer to the vec's buffer.
unsafe {
std::ptr::copy(result.output_data, buf.as_mut_ptr(), result.output_size);
}

Some(buf)
} else {
None
},
release_fn: result.release.clone(),
create_addr: if result.status_code == ffi::evmc_status_code::EVMC_SUCCESS {
// NOTE: This field is only Some if the evmc return code is SUCCESS.
Some(result.create_address)
} else {
None
},
};

// Release allocated ffi struct.
unsafe {
result.release.unwrap()(&result as *const ffi::evmc_result);
}

ret
}

}

/*
impl ExecutionResult {
/// Initialize a new result struct given a status code, remaining gas, and optional output
/// data.
Expand Down Expand Up @@ -74,7 +118,7 @@ impl ExecutionResult {
unsafe { ExecutionResult::from_boxed(Box::from_raw(raw)) }
}
}

*/
/// Callback to pass across FFI, de-allocating the struct.
extern "C" fn release_result(result: *const ffi::evmc_result) {
unsafe {
Expand All @@ -86,7 +130,7 @@ extern "C" fn release_result(result: *const ffi::evmc_result) {
mod tests {
use super::*;
use evmc_sys as ffi;

/*
#[test]
fn constructor() {
let result = ExecutionResult::new(
Expand Down Expand Up @@ -132,4 +176,5 @@ mod tests {
assert!(back.output().unwrap().len() == 4);
assert!(back.output().unwrap() == &[0xde, 0xad, 0xbe, 0xef]);
}
*/
}

0 comments on commit ad02bad

Please sign in to comment.