smoltcp/iface/
socket_set.rs

1use core::fmt;
2use managed::ManagedSlice;
3
4use super::socket_meta::Meta;
5use crate::socket::{AnySocket, Socket};
6
7/// Opaque struct with space for storing one socket.
8///
9/// This is public so you can use it to allocate space for storing
10/// sockets when creating an Interface.
11#[derive(Debug, Default)]
12pub struct SocketStorage<'a> {
13    inner: Option<Item<'a>>,
14}
15
16impl<'a> SocketStorage<'a> {
17    pub const EMPTY: Self = Self { inner: None };
18}
19
20/// An item of a socket set.
21#[derive(Debug)]
22pub(crate) struct Item<'a> {
23    pub(crate) meta: Meta,
24    pub(crate) socket: Socket<'a>,
25}
26
27/// A handle, identifying a socket in an Interface.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
29#[cfg_attr(feature = "defmt", derive(defmt::Format))]
30pub struct SocketHandle(usize);
31
32impl fmt::Display for SocketHandle {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        write!(f, "#{}", self.0)
35    }
36}
37
38/// An extensible set of sockets.
39///
40/// The lifetime `'a` is used when storing a `Socket<'a>`.  If you're using
41/// owned buffers for your sockets (passed in as `Vec`s) you can use
42/// `SocketSet<'static>`.
43#[derive(Debug)]
44pub struct SocketSet<'a> {
45    sockets: ManagedSlice<'a, SocketStorage<'a>>,
46}
47
48impl<'a> SocketSet<'a> {
49    /// Create a socket set using the provided storage.
50    pub fn new<SocketsT>(sockets: SocketsT) -> SocketSet<'a>
51    where
52        SocketsT: Into<ManagedSlice<'a, SocketStorage<'a>>>,
53    {
54        let sockets = sockets.into();
55        SocketSet { sockets }
56    }
57
58    /// Add a socket to the set, and return its handle.
59    ///
60    /// # Panics
61    /// This function panics if the storage is fixed-size (not a `Vec`) and is full.
62    pub fn add<T: AnySocket<'a>>(&mut self, socket: T) -> SocketHandle {
63        fn put<'a>(index: usize, slot: &mut SocketStorage<'a>, socket: Socket<'a>) -> SocketHandle {
64            net_trace!("[{}]: adding", index);
65            let handle = SocketHandle(index);
66            let mut meta = Meta::default();
67            meta.handle = handle;
68            *slot = SocketStorage {
69                inner: Some(Item { meta, socket }),
70            };
71            handle
72        }
73
74        let socket = socket.upcast();
75
76        for (index, slot) in self.sockets.iter_mut().enumerate() {
77            if slot.inner.is_none() {
78                return put(index, slot, socket);
79            }
80        }
81
82        match &mut self.sockets {
83            ManagedSlice::Borrowed(_) => panic!("adding a socket to a full SocketSet"),
84            #[cfg(feature = "alloc")]
85            ManagedSlice::Owned(sockets) => {
86                sockets.push(SocketStorage { inner: None });
87                let index = sockets.len() - 1;
88                put(index, &mut sockets[index], socket)
89            }
90        }
91    }
92
93    /// Get a socket from the set by its handle, as mutable.
94    ///
95    /// # Panics
96    /// This function may panic if the handle does not belong to this socket set
97    /// or the socket has the wrong type.
98    pub fn get<T: AnySocket<'a>>(&self, handle: SocketHandle) -> &T {
99        match self.sockets[handle.0].inner.as_ref() {
100            Some(item) => {
101                T::downcast(&item.socket).expect("handle refers to a socket of a wrong type")
102            }
103            None => panic!("handle does not refer to a valid socket"),
104        }
105    }
106
107    /// Get a mutable socket from the set by its handle, as mutable.
108    ///
109    /// # Panics
110    /// This function may panic if the handle does not belong to this socket set
111    /// or the socket has the wrong type.
112    pub fn get_mut<T: AnySocket<'a>>(&mut self, handle: SocketHandle) -> &mut T {
113        match self.sockets[handle.0].inner.as_mut() {
114            Some(item) => T::downcast_mut(&mut item.socket)
115                .expect("handle refers to a socket of a wrong type"),
116            None => panic!("handle does not refer to a valid socket"),
117        }
118    }
119
120    /// Remove a socket from the set, without changing its state.
121    ///
122    /// # Panics
123    /// This function may panic if the handle does not belong to this socket set.
124    pub fn remove(&mut self, handle: SocketHandle) -> Socket<'a> {
125        net_trace!("[{}]: removing", handle.0);
126        match self.sockets[handle.0].inner.take() {
127            Some(item) => item.socket,
128            None => panic!("handle does not refer to a valid socket"),
129        }
130    }
131
132    /// Get an iterator to the inner sockets.
133    pub fn iter(&self) -> impl Iterator<Item = (SocketHandle, &Socket<'a>)> {
134        self.items().map(|i| (i.meta.handle, &i.socket))
135    }
136
137    /// Get a mutable iterator to the inner sockets.
138    pub fn iter_mut(&mut self) -> impl Iterator<Item = (SocketHandle, &mut Socket<'a>)> {
139        self.items_mut().map(|i| (i.meta.handle, &mut i.socket))
140    }
141
142    /// Iterate every socket in this set.
143    pub(crate) fn items(&self) -> impl Iterator<Item = &Item<'a>> + '_ {
144        self.sockets.iter().filter_map(|x| x.inner.as_ref())
145    }
146
147    /// Iterate every socket in this set.
148    pub(crate) fn items_mut(&mut self) -> impl Iterator<Item = &mut Item<'a>> + '_ {
149        self.sockets.iter_mut().filter_map(|x| x.inner.as_mut())
150    }
151}