1
1
use std::time::Duration;
2

            
3
use budget_executor::blocking::singlethreaded::{Progress, Runtime};
4

            
5
1
fn main() {
6
1
    // Run a task with no initial budget. The first time the task asks to spend
7
1
    // any budget, it will be paused.
8
1
    let mut progress = Runtime::run_with_budget(some_task_to_limit, 0);
9

            
10
    // At this point, the task has run until the first call to
11
    // budget_executor::spend. Because we gave an initial_budget of 0, the future
12
    // is now paused. Let's loop until it's finished, feeding it 5 budget at a
13
    // time.
14
    loop {
15
8
        progress = match progress {
16
7
            Progress::NoBudget(incomplete_task) => {
17
7
                // Resume the task, allowing for 5 more budget to be spent.
18
7
                println!("+5 budget");
19
7
                incomplete_task.continue_with_additional_budget(5)
20
            }
21
1
            Progress::Complete(result) => {
22
1
                // The task has completed. `result.output` contains the output
23
1
                // of the task itself. We can also inspect the balance of the
24
1
                // budget:
25
1
                println!(
26
1
                    "Task completed with balance: {:?}, output: {:?}",
27
1
                    result.balance, result.output
28
1
                );
29
1
                break;
30
1
            }
31
1
        };
32
1
    }
33
1
}
34

            
35
1
async fn some_task_to_limit(runtime: Runtime<usize>) -> bool {
36
1
    do_some_operation(1, &runtime).await;
37
1
    do_some_operation(5, &runtime).await;
38
1
    do_some_operation(1, &runtime).await;
39
5
    do_some_operation(25, &runtime).await;
40
1
    true
41
1
}
42

            
43
4
async fn do_some_operation(times: u8, runtime: &Runtime<usize>) {
44
4
    println!("> Asking to spend {times} from the budget");
45
7
    runtime.spend(usize::from(times)).await;
46

            
47
    // Despite being async code, because we know we're running in a
48
    // single-threaded environment, we can still call blocking operations.
49
4
    std::thread::sleep(Duration::from_millis(u64::from(times) * 100));
50
4
}
51

            
52
1
#[test]
53
1
fn runs() {
54
1
    main()
55
1
}