@@ -3,6 +3,7 @@ use scriptful::{
33 prelude:: Stack ,
44} ;
55use serde:: { Deserialize , Serialize } ;
6+ use std:: marker:: PhantomData ;
67
78use witnet_crypto:: hash:: { calculate_sha256, Sha256 } ;
89use witnet_data_structures:: {
@@ -347,7 +348,7 @@ pub fn encode(a: Script<MyOperator, MyValue>) -> Vec<u8> {
347348
348349fn execute_script ( script : Script < MyOperator , MyValue > ) -> bool {
349350 // Instantiate the machine with a reference to your operator system.
350- let mut machine = Machine2 :: new ( & my_operator_system) ;
351+ let mut machine = Machine2 :: new ( my_operator_system) ;
351352 let result = machine. run_script ( & script) ;
352353
353354 result == None || result == Some ( & MyValue :: Boolean ( true ) )
@@ -399,27 +400,29 @@ pub enum MyControlFlow {
399400 Break ,
400401}
401402
402- pub struct Machine2 < ' a , Op , Val >
403+ pub struct Machine2 < Op , Val , F >
403404where
404405 Val : core:: fmt:: Debug + core:: cmp:: PartialEq ,
406+ F : FnMut ( & mut Stack < Val > , & Op , & mut ConditionStack ) -> MyControlFlow ,
405407{
406- op_sys : & ' a dyn Fn ( & mut Stack < Val > , & Op , & mut ConditionStack ) -> MyControlFlow ,
408+ op_sys : F ,
407409 stack : Stack < Val > ,
408410 if_stack : ConditionStack ,
411+ phantom_op : PhantomData < fn ( & Op ) > ,
409412}
410413
411- impl < ' a , Op , Val > Machine2 < ' a , Op , Val >
414+ impl < Op , Val , F > Machine2 < Op , Val , F >
412415where
413416 Op : core:: fmt:: Debug + core:: cmp:: Eq ,
414417 Val : core:: fmt:: Debug + core:: cmp:: PartialEq + core:: clone:: Clone ,
418+ F : FnMut ( & mut Stack < Val > , & Op , & mut ConditionStack ) -> MyControlFlow ,
415419{
416- pub fn new (
417- op_sys : & ' a dyn Fn ( & mut Stack < Val > , & Op , & mut ConditionStack ) -> MyControlFlow ,
418- ) -> Self {
420+ pub fn new ( op_sys : F ) -> Self {
419421 Self {
420422 op_sys,
421423 stack : Stack :: < Val > :: default ( ) ,
422424 if_stack : ConditionStack :: default ( ) ,
425+ phantom_op : PhantomData ,
423426 }
424427 }
425428
@@ -715,4 +718,17 @@ mod tests {
715718 ] ;
716719 assert ! ( execute_script( s) ) ;
717720 }
721+
722+ #[ test]
723+ fn machine_with_context ( ) {
724+ let mut v = vec ! [ 0u32 ] ;
725+ let mut m = Machine2 :: new ( |_stack : & mut Stack < ( ) > , operator, _if_stack| {
726+ v. push ( * operator) ;
727+
728+ MyControlFlow :: Continue
729+ } ) ;
730+ m. run_script ( & [ Item :: Operator ( 1 ) , Item :: Operator ( 3 ) , Item :: Operator ( 2 ) ] ) ;
731+
732+ assert_eq ! ( v, vec![ 0 , 1 , 3 , 2 ] ) ;
733+ }
718734}
0 commit comments