use gen_impl::GeneratorImpl;
use rt::{Context, ContextStack, Error};
use yield_::raw_yield_now;
pub struct Scope<A, T> {
para: *mut Option<A>,
ret: *mut Option<T>,
}
impl<A, T> Scope<A, T> {
pub fn new(para: *mut Option<A>, ret: *mut Option<T>) -> Self {
Scope {
para: para,
ret: ret,
}
}
#[inline]
fn set_ret(&mut self, v: T) {
let ret = unsafe { &mut *self.ret };
*ret = Some(v);
}
#[inline]
fn raw_yield(&mut self, env: &ContextStack, context: &mut Context, v: T) {
if !context.is_generator() {
panic!("yield from none generator context");
}
self.set_ret(v);
context._ref -= 1;
raw_yield_now(env, context);
if context._ref != 1 {
panic!(Error::Cancel);
}
}
#[inline]
pub fn yield_with(&mut self, v: T) {
let env = ContextStack::current();
let context = env.top();
self.raw_yield(&env, context, v);
}
#[inline]
pub fn get_yield(&mut self) -> Option<A> {
let para = unsafe { &mut *self.para };
para.take()
}
#[inline]
pub fn yield_(&mut self, v: T) -> Option<A> {
self.yield_with(v);
self.get_yield()
}
pub fn yield_from(&mut self, mut g: Box<GeneratorImpl<A, T>>) -> Option<A> {
let env = ContextStack::current();
let context = env.top();
let mut p = self.get_yield();
while !g.is_done() {
match g.raw_send(p) {
None => return None,
Some(r) => self.raw_yield(&env, context, r),
}
p = self.get_yield();
}
p
}
}