From c8afdcd6ecfae970dd2ab0575706ff3c553adf63 Mon Sep 17 00:00:00 2001 From: Alex Beregszaszi Date: Sat, 11 Aug 2018 19:19:56 +0100 Subject: [PATCH] Turn EwasmAPI into a trait --- src/lib.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 23663f2..62aca6d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -587,3 +587,68 @@ pub fn selfdestruct(address: &Address) -> ! { native::ethereum_selfDestruct(address.bytes.as_ptr() as *const u32); } } + +pub trait EwasmAPI: Send + Sync { + fn consume_gas(mut self, amount: u64); + fn gas_left(self) -> u64; + fn current_address() -> [u8; 20]; +} + +#[derive(Debug)] +pub struct NativeImpl; + +#[derive(Debug)] +pub struct TestImpl { + gas: u64, +} + +impl Default for TestImpl { + fn default() -> TestImpl { + TestImpl { gas: 0 } + } +} + +/* +trait TestSetter { + fn set_gas(mut self, amount: u64); +} + +impl TestSetter for TestImpl { + fn set_gas(mut self, amount: u64) { + self.gas = amount + } +} +*/ + +impl EwasmAPI for NativeImpl { + fn consume_gas(self, amount: u64) {} + fn gas_left(self) -> u64 { + 0 + } + fn current_address() -> [u8; 20] { + [0u8; 20] + } +} + +impl EwasmAPI for TestImpl { + fn consume_gas(mut self, amount: u64) { + self.gas + } + fn gas_left(self) -> u64 { + self.gas + } + fn current_address() -> [u8; 20] { + [0u8; 20] + } +} + +#[cfg(test)] +mod tests { + use super::{EwasmAPI, TestImpl}; + + #[test] + fn consume_gas_func() { + assert_eq!(0, EwasmAPI::gas_left(::default())); + assert_eq!(TestImpl::default().gas_left(), 0); + } +}