open_coroutine_core/net/
join.rs1use crate::net::event_loop::EventLoop;
2use std::ffi::{c_char, CStr, CString};
3use std::io::{Error, ErrorKind};
4use std::sync::Arc;
5use std::time::Duration;
6
7#[allow(missing_docs)]
8#[repr(C)]
9#[derive(Debug)]
10pub struct JoinHandle(&'static Arc<EventLoop<'static>>, *const c_char);
11
12impl Drop for JoinHandle {
13 fn drop(&mut self) {
14 if let Ok(name) = self.get_name() {
15 self.0.clean_task_result(name);
16 }
17 }
18}
19
20impl JoinHandle {
21 pub(crate) fn err(pool: &'static Arc<EventLoop<'static>>) -> Self {
23 Self::new(pool, "")
24 }
25
26 pub(crate) fn new(pool: &'static Arc<EventLoop<'static>>, name: &str) -> Self {
28 let boxed: &'static mut CString = Box::leak(Box::from(
29 CString::new(name).expect("init JoinHandle failed!"),
30 ));
31 let cstr: &'static CStr = boxed.as_c_str();
32 JoinHandle(pool, cstr.as_ptr())
33 }
34
35 pub fn get_name(&self) -> std::io::Result<&str> {
40 unsafe { CStr::from_ptr(self.1) }
41 .to_str()
42 .map_err(|_| Error::new(ErrorKind::InvalidInput, "Invalid task name"))
43 }
44
45 pub fn timeout_join(&self, dur: Duration) -> std::io::Result<Result<Option<usize>, &str>> {
50 self.timeout_at_join(crate::common::get_timeout_time(dur))
51 }
52
53 pub fn join(&self) -> std::io::Result<Result<Option<usize>, &str>> {
58 self.timeout_at_join(u64::MAX)
59 }
60
61 pub fn timeout_at_join(
66 &self,
67 timeout_time: u64,
68 ) -> std::io::Result<Result<Option<usize>, &str>> {
69 let name = self.get_name()?;
70 if name.is_empty() {
71 return Err(Error::new(ErrorKind::InvalidInput, "Invalid task name"));
72 }
73 self.0.wait_task_result(
74 name,
75 Duration::from_nanos(timeout_time.saturating_sub(crate::common::now())),
76 )
77 }
78}