Skip to main content

network/manager/
context.rs

1use core::task::{Context, Poll};
2
3use crate::manager::stack::Stack;
4use smoltcp::iface::SocketHandle;
5
6pub struct SocketContext {
7    pub handle: SocketHandle,
8    pub stack: Stack,
9    pub closed: bool,
10    pub was_connected: bool,
11}
12
13impl SocketContext {
14    pub async fn with<F, S, R>(&self, f: F) -> R
15    where
16        F: FnOnce(&S) -> R,
17        S: smoltcp::socket::AnySocket<'static>,
18    {
19        self.stack
20            .with(|stack_inner| {
21                let socket = stack_inner.sockets.get::<S>(self.handle);
22                f(socket)
23            })
24            .await
25    }
26
27    pub async fn with_mutable<F, S, R>(&self, f: F) -> R
28    where
29        F: FnOnce(&mut S) -> R,
30        S: smoltcp::socket::AnySocket<'static>,
31    {
32        self.stack
33            .with_mutable(|stack_inner| {
34                let socket = stack_inner.sockets.get_mut::<S>(self.handle);
35                f(socket)
36            })
37            .await
38    }
39
40    pub fn poll_with<F, S, R>(&self, context: &mut Context<'_>, f: F) -> Poll<R>
41    where
42        F: FnOnce(&S, &mut Context<'_>) -> Poll<R>,
43        S: smoltcp::socket::AnySocket<'static>,
44    {
45        self.stack.poll_with(context, |stack_inner, context| {
46            let socket = stack_inner.sockets.get::<S>(self.handle);
47
48            f(socket, context)
49        })
50    }
51
52    pub fn poll_with_mutable<F, S, R>(&self, context: &mut core::task::Context<'_>, f: F) -> Poll<R>
53    where
54        F: FnOnce(&mut S, &mut Context<'_>) -> Poll<R>,
55        S: smoltcp::socket::AnySocket<'static>,
56    {
57        self.stack
58            .poll_with_mutable(context, |stack_inner, context| {
59                let socket = stack_inner.sockets.get_mut::<S>(self.handle);
60
61                f(socket, context)
62            })
63    }
64}
65
66impl Drop for SocketContext {
67    fn drop(&mut self) {
68        // The context owns this handle. Closing a protocol socket alone leaves
69        // its owned buffers in the SocketSet, even after the wrapper is gone.
70        // Retire it for every protocol and explicit/implicit close path; TCP
71        // storage remains owned by the runner until shutdown is dispatched.
72        embassy_futures::block_on(self.stack.with_mutable(|stack| {
73            stack.retire_socket(self.handle);
74        }));
75    }
76}