Skip to content

Commit 65e183e

Browse files
committed
feat(stack): allow context in machine operate function
1 parent 78aab3f commit 65e183e

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

stack/src/lib.rs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use scriptful::{
33
prelude::Stack,
44
};
55
use serde::{Deserialize, Serialize};
6+
use std::marker::PhantomData;
67

78
use witnet_crypto::hash::{calculate_sha256, Sha256};
89
use witnet_data_structures::{
@@ -347,7 +348,7 @@ pub fn encode(a: Script<MyOperator, MyValue>) -> Vec<u8> {
347348

348349
fn 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>
403404
where
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>
412415
where
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

Comments
 (0)