basic/
basic.rs

1// Copyright 2016 coroutine-rs Developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8extern crate context;
9
10use context::{Context, Transfer};
11use context::stack::ProtectedFixedSizeStack;
12
13// Print the natural numbers from 0 to 9 using a "generator" preserving state on the stack.
14fn main() {
15    // This method will always `resume()` immediately back to the
16    // previous `Context` with a `data` value incremented by one starting at 0.
17    // You could thus describe this method as a "natural number generator".
18    extern "C" fn context_function(mut t: Transfer) -> ! {
19        for i in 0usize.. {
20            print!("Yielding {} => ", i);
21            t = unsafe { t.context.resume(i) };
22        }
23
24        unreachable!();
25    }
26
27    // Allocate some stack.
28    let stack = ProtectedFixedSizeStack::default();
29
30    // Allocate a Context on the stack.
31    let mut t = Transfer::new(unsafe { Context::new(&stack, context_function) }, 0);
32
33    // Yield 10 times to `context_function()`.
34    for _ in 0..10 {
35        // Yield to the "frozen" state of `context_function()`.
36        // The `data` value is not used in this example and is left at 0.
37        // The first and every other call will return references to the actual `Context` data.
38        print!("Resuming => ");
39        t = unsafe { t.context.resume(0) };
40
41        println!("Got {}", t.data);
42    }
43
44    println!("Finished!");
45}