1use core::fmt;
2use managed::ManagedSlice;
34use super::socket_meta::Meta;
5use crate::socket::{AnySocket, Socket};
67/// 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}
1516impl<'a> SocketStorage<'a> {
17pub const EMPTY: Self = Self { inner: None };
18}
1920/// An item of a socket set.
21#[derive(Debug)]
22pub(crate) struct Item<'a> {
23pub(crate) meta: Meta,
24pub(crate) socket: Socket<'a>,
25}
2627/// 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);
3132impl fmt::Display for SocketHandle {
33fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34write!(f, "#{}", self.0)
35 }
36}
3738/// 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}
4748impl<'a> SocketSet<'a> {
49/// Create a socket set using the provided storage.
50pub fn new<SocketsT>(sockets: SocketsT) -> SocketSet<'a>
51where
52SocketsT: Into<ManagedSlice<'a, SocketStorage<'a>>>,
53 {
54let sockets = sockets.into();
55 SocketSet { sockets }
56 }
5758/// 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.
62pub fn add<T: AnySocket<'a>>(&mut self, socket: T) -> SocketHandle {
63fn put<'a>(index: usize, slot: &mut SocketStorage<'a>, socket: Socket<'a>) -> SocketHandle {
64net_trace!("[{}]: adding", index);
65let handle = SocketHandle(index);
66let mut meta = Meta::default();
67 meta.handle = handle;
68*slot = SocketStorage {
69 inner: Some(Item { meta, socket }),
70 };
71 handle
72 }
7374let socket = socket.upcast();
7576for (index, slot) in self.sockets.iter_mut().enumerate() {
77if slot.inner.is_none() {
78return put(index, slot, socket);
79 }
80 }
8182match &mut self.sockets {
83 ManagedSlice::Borrowed(_) => panic!("adding a socket to a full SocketSet"),
84#[cfg(feature = "alloc")]
85ManagedSlice::Owned(sockets) => {
86 sockets.push(SocketStorage { inner: None });
87let index = sockets.len() - 1;
88 put(index, &mut sockets[index], socket)
89 }
90 }
91 }
9293/// 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.
98pub fn get<T: AnySocket<'a>>(&self, handle: SocketHandle) -> &T {
99match self.sockets[handle.0].inner.as_ref() {
100Some(item) => {
101 T::downcast(&item.socket).expect("handle refers to a socket of a wrong type")
102 }
103None => panic!("handle does not refer to a valid socket"),
104 }
105 }
106107/// 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.
112pub fn get_mut<T: AnySocket<'a>>(&mut self, handle: SocketHandle) -> &mut T {
113match self.sockets[handle.0].inner.as_mut() {
114Some(item) => T::downcast_mut(&mut item.socket)
115 .expect("handle refers to a socket of a wrong type"),
116None => panic!("handle does not refer to a valid socket"),
117 }
118 }
119120/// 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.
124pub fn remove(&mut self, handle: SocketHandle) -> Socket<'a> {
125net_trace!("[{}]: removing", handle.0);
126match self.sockets[handle.0].inner.take() {
127Some(item) => item.socket,
128None => panic!("handle does not refer to a valid socket"),
129 }
130 }
131132/// Get an iterator to the inner sockets.
133pub fn iter(&self) -> impl Iterator<Item = (SocketHandle, &Socket<'a>)> {
134self.items().map(|i| (i.meta.handle, &i.socket))
135 }
136137/// Get a mutable iterator to the inner sockets.
138pub fn iter_mut(&mut self) -> impl Iterator<Item = (SocketHandle, &mut Socket<'a>)> {
139self.items_mut().map(|i| (i.meta.handle, &mut i.socket))
140 }
141142/// Iterate every socket in this set.
143pub(crate) fn items(&self) -> impl Iterator<Item = &Item<'a>> + '_ {
144self.sockets.iter().filter_map(|x| x.inner.as_ref())
145 }
146147/// Iterate every socket in this set.
148pub(crate) fn items_mut(&mut self) -> impl Iterator<Item = &mut Item<'a>> + '_ {
149self.sockets.iter_mut().filter_map(|x| x.inner.as_mut())
150 }
151}