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 JoinHandle {
13    /// create `JoinHandle` instance.
14    pub(crate) fn err(pool: &'static Arc<EventLoop<'static>>) -> Self {
15        Self::new(pool, "")
16    }
17
18    /// create `JoinHandle` instance.
19    pub(crate) fn new(pool: &'static Arc<EventLoop<'static>>, name: &str) -> Self {
20        let boxed: &'static mut CString = Box::leak(Box::from(
21            CString::new(name).expect("init JoinHandle failed!"),
22        ));
23        let cstr: &'static CStr = boxed.as_c_str();
24        JoinHandle(pool, cstr.as_ptr())
25    }
26
27    /// get the task name.
28    ///
29    /// # Errors
30    /// if the task name is invalid.
31    pub fn get_name(&self) -> std::io::Result<&str> {
32        unsafe { CStr::from_ptr(self.1) }
33            .to_str()
34            .map_err(|_| Error::new(ErrorKind::InvalidInput, "Invalid task name"))
35    }
36
37    /// join with `Duration`.
38    ///
39    /// # Errors
40    /// see `timeout_at_join`.
41    pub fn timeout_join(&self, dur: Duration) -> std::io::Result<Result<Option<usize>, &str>> {
42        self.timeout_at_join(crate::common::get_timeout_time(dur))
43    }
44
45    /// join.
46    ///
47    /// # Errors
48    /// see `timeout_at_join`.
49    pub fn join(&self) -> std::io::Result<Result<Option<usize>, &str>> {
50        self.timeout_at_join(u64::MAX)
51    }
52
53    /// join with timeout.
54    ///
55    /// # Errors
56    /// if join failed.
57    pub fn timeout_at_join(
58        &self,
59        timeout_time: u64,
60    ) -> std::io::Result<Result<Option<usize>, &str>> {
61        let name = self.get_name()?;
62        if name.is_empty() {
63            return Err(Error::new(ErrorKind::InvalidInput, "Invalid task name"));
64        }
65        self.0.wait_task_result(
66            name,
67            Duration::from_nanos(timeout_time.saturating_sub(crate::common::now())),
68        )
69    }
70}