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
use std::any::TypeId;
use std::mem;
use std::mem::MaybeUninit;
use std::pin::Pin;
use std::ptr;

use crate::assert_send;
use crate::spi_async_socket_impl_delegate;
use crate::AsyncSocket;

/// Newtype for [`Box<dyn AsyncSocket>`](AsyncSocket).
#[derive(Debug)]
pub struct AsyncSocketBox(Box<dyn AsyncSocket>);

fn _assert_kinds() {
    assert_send::<AsyncSocketBox>();
}

fn transmute_or_map<A: 'static, B: 'static>(a: A, f: impl FnOnce(A) -> B) -> B {
    if TypeId::of::<A>() == TypeId::of::<B>() {
        assert_eq!(mem::size_of::<A>(), mem::size_of::<B>());
        // Can be made safe with specialization.
        unsafe {
            let mut b = MaybeUninit::<B>::uninit();
            ptr::copy(&a as *const A, b.as_mut_ptr() as *mut A, 1);
            mem::forget(a);
            b.assume_init()
        }
    } else {
        f(a)
    }
}

impl AsyncSocketBox {
    /// Construct.
    pub fn new<S: AsyncSocket>(socket: S) -> AsyncSocketBox {
        transmute_or_map(socket, |socket| AsyncSocketBox(Box::new(socket)))
    }

    fn deref_pin_mut_for_impl_socket(self: Pin<&mut Self>) -> Pin<&mut dyn AsyncSocket> {
        Pin::new(&mut self.get_mut().0)
    }

    fn deref_for_impl_socket(&self) -> &dyn AsyncSocket {
        &self.0
    }
}

spi_async_socket_impl_delegate!(AsyncSocketBox);

fn _assert_async_socket_box_is_async_socket(s: AsyncSocketBox) {
    fn accepts_socket<S: AsyncSocket>(_: S) {}
    accepts_socket(s);
}