67 lines
1.6 KiB
Rust
67 lines
1.6 KiB
Rust
use std::time::Duration;
|
|
|
|
use comrade::iterated::{FunctionContext, IteratedFunction};
|
|
|
|
#[derive(Debug, Default, Clone)]
|
|
pub struct AccFnContext {
|
|
pub iter: u64,
|
|
pub acc: u64,
|
|
}
|
|
|
|
pub fn multiply_iterated(
|
|
mut ctx: FunctionContext<AccFnContext, (u64, u64), u64>,
|
|
) -> FunctionContext<AccFnContext, (u64, u64), u64> {
|
|
// init
|
|
let (a, b) = ctx.initial;
|
|
|
|
// end condition (return)
|
|
if b == ctx.context.iter {
|
|
ctx.done(ctx.context.acc);
|
|
return ctx;
|
|
}
|
|
|
|
// computation
|
|
println!("doing calc {}", ctx.context.acc);
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
let val = ctx.context.acc + a;
|
|
|
|
// saving state
|
|
ctx.state(|x| {
|
|
x.iter += 1;
|
|
x.acc = val;
|
|
});
|
|
|
|
return ctx;
|
|
}
|
|
|
|
fn main() {
|
|
env_logger::init();
|
|
|
|
let f: IteratedFunction<AccFnContext, (u64, u64), u64> =
|
|
IteratedFunction::new(multiply_iterated);
|
|
|
|
let x = f.run_to_end((5, 4));
|
|
println!("computed x -> {x}");
|
|
|
|
// async
|
|
let f = IteratedFunction::new_threaded(multiply_iterated, (5, 5));
|
|
println!("This is running");
|
|
println!("result is {}", f.output());
|
|
|
|
let f = IteratedFunction::new_threaded(multiply_iterated, (5, 50));
|
|
|
|
// pause the function
|
|
f.pause();
|
|
|
|
// stop the function and get state
|
|
let state = f.stop();
|
|
println!("This was running");
|
|
println!("state is {state:?}");
|
|
|
|
println!("reviving function");
|
|
// continue with previous computed state
|
|
let f = IteratedFunction::new_threaded_from_state(multiply_iterated, state);
|
|
|
|
// get output
|
|
println!("result is {}", f.output());
|
|
}
|