Skip to content

Commit

Permalink
rust: Manually allocate output buffer for Into<evmc_result>
Browse files Browse the repository at this point in the history
  • Loading branch information
jakelang committed Mar 19, 2019
1 parent ae5474b commit ccbc90c
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions bindings/rust/evmc-vm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,17 @@ impl From<ffi::evmc_result> for ExecutionResult {
impl Into<*const ffi::evmc_result> for ExecutionResult {
fn into(self) -> *const ffi::evmc_result {
let (buffer, len) = if let Some(buf) = self.output {
(buf.as_ptr(), buf.len())
let buf_len = buf.len();

// Manually allocate heap memory for the new home of the output buffer.
let memlayout = std::alloc::Layout::from_size_align(buf_len, 1).expect("Bad layout");
let new_buf = unsafe { std::alloc::alloc(memlayout) };
unsafe {
// Copy the data into the allocated buffer.
std::ptr::copy(buf.as_ptr(), new_buf, buf_len);
}

(new_buf as *const u8, buf_len)
} else {
(std::ptr::null(), 0)
};
Expand Down Expand Up @@ -171,7 +181,10 @@ mod tests {
assert!((*f).gas_left == 420);
assert!(!(*f).output_data.is_null());
assert!((*f).output_size == 5);
// assert!(std::slice::from_raw_parts((*f).output_data, 5) as &[u8] == &[0xc0, 0xff, 0xee, 0x71, 0x75]);
assert!(
std::slice::from_raw_parts((*f).output_data, 5) as &[u8]
== &[0xc0, 0xff, 0xee, 0x71, 0x75]
);
assert!((*f).create_address.bytes == [0u8; 20]);
}
}
Expand Down

0 comments on commit ccbc90c

Please sign in to comment.