use crate::{FiberApi, FiberEntry, FiberError, FiberHandle, FiberStackPointer};
use context::stack::Stack;
use context::{Context, Transfer};
use std::ptr;
use std::ptr::NonNull;
struct BoostFiberContext {
ctx: Option<Context>,
parent: Option<NonNull<BoostFiberContext>>,
entry: FiberEntry,
user_data: *mut (),
}
impl BoostFiberContext {
unsafe fn from_handle(handle: FiberHandle) -> &'static mut Self {
&mut *(handle.0 as *mut BoostFiberContext)
}
}
extern "C" fn fcontext_fiber_wrapper(t: Transfer) -> ! {
unsafe {
let self_ctx = BoostFiberContext::from_handle(FiberHandle(t.data as *mut ()));
if let Some(mut parent_ptr) = self_ctx.parent {
let parent_ctx = parent_ptr.as_mut();
parent_ctx.ctx = Some(t.context);
}
(self_ctx.entry)(self_ctx.user_data);
std::process::abort();
}
}
extern "C" fn thread_stub(_p: *mut ()) {}
pub struct FContextFiberApi;
unsafe impl FiberApi for FContextFiberApi {
unsafe fn create_fiber(
stack: FiberStackPointer,
entry: FiberEntry,
user_data: *mut (),
) -> Result<FiberHandle, FiberError> {
let stack = Stack::new(
stack.top().cast(), stack.bottom().cast(), );
let ctx = Box::new(BoostFiberContext {
ctx: Some(Context::new(&stack, fcontext_fiber_wrapper)),
parent: None,
entry,
user_data,
});
Ok(FiberHandle(Box::into_raw(ctx) as *mut ()))
}
unsafe fn convert_thread_to_fiber() -> Result<FiberHandle, FiberError> {
let ctx = Box::new(BoostFiberContext {
ctx: None,
parent: None,
entry: thread_stub, user_data: ptr::null_mut(),
});
Ok(FiberHandle(Box::into_raw(ctx) as *mut ()))
}
unsafe fn switch_to_fiber(from: FiberHandle, to: FiberHandle) {
let from_ctx = BoostFiberContext::from_handle(from);
let to_ctx = BoostFiberContext::from_handle(to);
to_ctx.parent = Some(NonNull::new_unchecked(from_ctx as *mut BoostFiberContext));
let ctx = to_ctx
.ctx
.take()
.expect("Target fiber has no valid context to resume");
let transfer = ctx.resume(to.0 as usize);
to_ctx.ctx = Some(transfer.context);
}
unsafe fn destroy_fiber(handle: FiberHandle) {
let _ctx = Box::from_raw(handle.0 as *mut BoostFiberContext);
}
}