open_coroutine_hooks/
coroutine.rs

1use open_coroutine_core::common::JoinHandle;
2use open_coroutine_core::coroutine::suspender::SuspenderImpl;
3use open_coroutine_core::net::event_loop::join::CoJoinHandleImpl;
4use open_coroutine_core::net::event_loop::{EventLoops, UserFunc};
5use std::ffi::{c_long, c_void};
6use std::time::Duration;
7
8///创建协程
9#[no_mangle]
10pub extern "C" fn coroutine_crate(
11    f: UserFunc,
12    param: usize,
13    stack_size: usize,
14) -> CoJoinHandleImpl {
15    let stack_size = if stack_size > 0 {
16        Some(stack_size)
17    } else {
18        None
19    };
20    EventLoops::submit_co(
21        move |suspender, ()| {
22            #[allow(clippy::cast_ptr_alignment, clippy::ptr_as_ptr)]
23            Some(f(
24                suspender as *const _ as *const SuspenderImpl<(), ()>,
25                param,
26            ))
27        },
28        stack_size,
29    )
30    .unwrap_or_else(|_| CoJoinHandleImpl::err())
31}
32
33///等待协程完成
34#[no_mangle]
35pub extern "C" fn coroutine_join(handle: CoJoinHandleImpl) -> c_long {
36    match handle.join() {
37        Ok(ptr) => match ptr {
38            Ok(ptr) => match ptr {
39                Some(ptr) => ptr as *mut c_void as c_long,
40                None => 0,
41            },
42            Err(_) => -1,
43        },
44        Err(_) => -1,
45    }
46}
47
48///等待协程完成
49#[no_mangle]
50pub extern "C" fn coroutine_timeout_join(handle: &CoJoinHandleImpl, ns_time: u64) -> c_long {
51    match handle.timeout_join(Duration::from_nanos(ns_time)) {
52        Ok(ptr) => match ptr {
53            Ok(ptr) => match ptr {
54                Some(ptr) => ptr as *mut c_void as c_long,
55                None => 0,
56            },
57            Err(_) => -1,
58        },
59        Err(_) => -1,
60    }
61}