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
use crate::NetworkInterface;
use alloc::sync::Arc;
use core::{
    marker::PhantomData,
    ops::{Deref, DerefMut},
};
use smoltcp::{
    iface::{SocketHandle, SocketSet},
    socket::AnySocket,
    wire::{IpEndpoint, IpListenEndpoint},
};
use sync_block::MutexGuard;

pub use smoltcp::socket::tcp::ConnectError;

/// A network socket.
///
/// In order to use the socket, it must be locked using the [`lock`] method.
/// This will lock the interface's list of sockets, and so the guard returned by
/// [`lock`] must be dropped before calling [`Interface::poll`].
pub struct Socket<T>
where
    // TODO: Relax 'static lifetime.
    T: AnySocket<'static> + ?Sized,
{
    pub(crate) handle: SocketHandle,
    pub(crate) interface: Arc<NetworkInterface>,
    pub(crate) phantom_data: PhantomData<T>,
}

pub struct LockedSocket<'a, T>
where
    T: AnySocket<'static> + ?Sized,
{
    handle: SocketHandle,
    sockets: MutexGuard<'a, SocketSet<'static>>,
    interface: &'a Arc<NetworkInterface>,
    phantom_data: PhantomData<T>,
}

impl<'a> LockedSocket<'a, smoltcp::socket::tcp::Socket<'static>> {
    pub fn connect<R, L>(
        &mut self,
        remote_endpoint: R,
        local_endpoint: L,
    ) -> Result<(), ConnectError>
    where
        R: Into<IpEndpoint>,
        L: Into<IpListenEndpoint>,
    {
        let mut interface = self.interface.inner.lock();
        let context = interface.context();
        (**self).connect(context, remote_endpoint, local_endpoint)
    }
}

impl<'a, T> Deref for LockedSocket<'a, T>
where
    T: AnySocket<'static>,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.sockets.get(self.handle)
    }
}

impl<'a, T> DerefMut for LockedSocket<'a, T>
where
    T: AnySocket<'static>,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.sockets.get_mut(self.handle)
    }
}

impl<T> Socket<T>
where
    T: AnySocket<'static>,
{
    pub fn lock(&self) -> LockedSocket<'_, T> {
        LockedSocket {
            handle: self.handle,
            sockets: self.interface.sockets.lock(),
            interface: &self.interface,
            phantom_data: PhantomData,
        }
    }
}