1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! opaque handle type of syscall.

use std::any::TypeId;

/// A transparent type pointer that represents any implementation-related asynchronous system type.
#[derive(Debug)]
pub struct Handle {
    data: *const (),
    drop: fn(*const ()),
    type_id: TypeId,
}

/// safely: the handle wrap type `T` must implements `Send + Sync`
unsafe impl Send for Handle {}
unsafe impl Sync for Handle {}

impl Handle {
    pub fn new<T>(value: T) -> Self
    where
        T: Send + Sync + 'static,
    {
        Self {
            data: Box::into_raw(Box::new(value)) as *const (),
            drop: Self::handle_drop_fn::<T>,
            type_id: TypeId::of::<T>(),
        }
    }

    /// safely drop opaque data object.
    fn handle_drop_fn<T>(data: *const ()) {
        drop(unsafe { Box::from_raw(data as *mut T) })
    }

    /// Returns `T` reference to the inner value if it is of type `T`, or [`None`].
    ///
    /// As required by the `NASI`, there is no way to get a mutable reference to `T`,
    /// so the inner type `T` should implements `Send + Sync` auto traits.
    pub fn downcast<T>(&self) -> Option<&T>
    where
        T: Send + Sync + 'static,
    {
        if self.type_id == TypeId::of::<T>() {
            Some(unsafe { &*(self.data as *const T) })
        } else {
            None
        }
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        (self.drop)(self.data);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    };

    use crate::Handle;

    struct Mock(Arc<AtomicUsize>);

    impl Drop for Mock {
        fn drop(&mut self) {
            self.0.fetch_sub(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn test_handle() {
        let counter: Arc<AtomicUsize> = Default::default();

        let mock = Mock(counter.clone());

        counter.fetch_add(1, Ordering::Relaxed);

        let handle = Handle::new(mock);

        assert_eq!(handle.downcast::<u32>(), None);

        assert!(handle.downcast::<Mock>().is_some());

        assert_eq!(counter.load(Ordering::Relaxed), 1);

        drop(handle);

        assert_eq!(counter.load(Ordering::Relaxed), 0);
    }
}