socket_set.rs 5.1 KB

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