use std::{error::Error, fmt::Display};
pub use crate::stack::{FiberStack, FiberStackPointer, UnsafeFiberStack};
use cfg_if::cfg_if;
mod stack;
pub mod sys;
cfg_if! {
if #[cfg(all(feature = "ucontext", target_os = "linux"))] {
pub type DefaultFiberApi = sys::ucontext::UContextFiberApi;
} else {
pub type DefaultFiberApi = sys::fcontext::FContextFiberApi;
}
}
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FiberHandle(*mut ());
impl FiberHandle {
pub const fn null() -> Self {
FiberHandle(std::ptr::null_mut())
}
}
unsafe impl Send for FiberHandle {}
pub type FiberEntry = unsafe extern "C" fn(*mut ());
pub unsafe trait FiberApi {
unsafe fn create_fiber(
stack: FiberStackPointer,
entry: FiberEntry,
user_data: *mut (),
) -> Result<FiberHandle, FiberError>;
unsafe fn convert_thread_to_fiber() -> Result<FiberHandle, FiberError>;
unsafe fn switch_to_fiber(from: FiberHandle, to: FiberHandle);
unsafe fn destroy_fiber(handle: FiberHandle);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FiberError {
CreationFailed,
PlatformError(i32),
}
impl Error for FiberError {}
impl Display for FiberError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FiberError::CreationFailed => write!(f, "Fiber creation failed"),
FiberError::PlatformError(code) => write!(f, "Platform error with code {}", code),
}
}
}