open_coroutine_core/net/
join.rs

1use 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    /// create `JoinHandle` instance.
22    pub(crate) fn err(pool: &'static Arc<EventLoop<'static>>) -> Self {
23        Self::new(pool, "")
24    }
25
26    /// create `JoinHandle` instance.
27    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    /// get the task name.
36    ///
37    /// # Errors
38    /// if the task name is invalid.
39    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    /// join with `Duration`.
46    ///
47    /// # Errors
48    /// see `timeout_at_join`.
49    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    /// join.
54    ///
55    /// # Errors
56    /// see `timeout_at_join`.
57    pub fn join(&self) -> std::io::Result<Result<Option<usize>, &str>> {
58        self.timeout_at_join(u64::MAX)
59    }
60
61    /// join with timeout.
62    ///
63    /// # Errors
64    /// if join failed.
65    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}