set.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. use core::{fmt, slice};
  2. use managed::ManagedSlice;
  3. use super::{Socket, SocketRef, AnySocket};
  4. #[cfg(feature = "proto-tcp")] use super::TcpState;
  5. /// An item of a socket set.
  6. ///
  7. /// The only reason this struct is public is to allow the socket set storage
  8. /// to be allocated externally.
  9. #[derive(Debug)]
  10. pub struct Item<'a, 'b: 'a> {
  11. socket: Socket<'a, 'b>,
  12. refs: usize
  13. }
  14. /// A handle, identifying a socket in a set.
  15. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
  16. pub struct Handle(usize);
  17. impl Handle {
  18. pub(crate) const EMPTY: Handle = Handle(0);
  19. }
  20. impl fmt::Display for Handle {
  21. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  22. write!(f, "#{}", self.0)
  23. }
  24. }
  25. /// An extensible set of sockets.
  26. ///
  27. /// The lifetimes `'b` and `'c` are used when storing a `Socket<'b, 'c>`.
  28. #[derive(Debug)]
  29. pub struct Set<'a, 'b: 'a, 'c: 'a + 'b> {
  30. sockets: ManagedSlice<'a, Option<Item<'b, 'c>>>
  31. }
  32. impl<'a, 'b: 'a, 'c: 'a + 'b> Set<'a, 'b, 'c> {
  33. /// Create a socket set using the provided storage.
  34. pub fn new<SocketsT>(sockets: SocketsT) -> Set<'a, 'b, 'c>
  35. where SocketsT: Into<ManagedSlice<'a, Option<Item<'b, 'c>>>> {
  36. let sockets = sockets.into();
  37. Set {
  38. sockets: sockets
  39. }
  40. }
  41. /// Add a socket to the set with the reference count 1, and return its handle.
  42. ///
  43. /// # Panics
  44. /// This function panics if the storage is fixed-size (not a `Vec`) and is full.
  45. pub fn add(&mut self, socket: Socket<'b, 'c>) -> Handle {
  46. fn put<'b, 'c>(index: usize, slot: &mut Option<Item<'b, 'c>>,
  47. mut socket: Socket<'b, 'c>) -> Handle {
  48. net_trace!("[{}]: adding", index);
  49. let handle = Handle(index);
  50. socket.set_handle(handle);
  51. *slot = Some(Item { socket: socket, refs: 1 });
  52. handle
  53. }
  54. for (index, slot) in self.sockets.iter_mut().enumerate() {
  55. if slot.is_none() {
  56. return put(index, slot, socket)
  57. }
  58. }
  59. match self.sockets {
  60. ManagedSlice::Borrowed(_) => {
  61. panic!("adding a socket to a full SocketSet")
  62. }
  63. #[cfg(any(feature = "std", feature = "alloc"))]
  64. ManagedSlice::Owned(ref mut sockets) => {
  65. sockets.push(None);
  66. let index = sockets.len() - 1;
  67. return put(index, &mut sockets[index], socket)
  68. }
  69. }
  70. }
  71. /// Get a socket from the set by its handle, as mutable.
  72. ///
  73. /// # Panics
  74. /// This function may panic if the handle does not belong to this socket set
  75. /// or the socket has the wrong type.
  76. pub fn get<T: AnySocket<'b, 'c>>(&mut self, handle: Handle) -> SocketRef<T> {
  77. match self.sockets[handle.0].as_mut() {
  78. Some(item) => {
  79. T::downcast(SocketRef::new(&mut item.socket))
  80. .expect("handle refers to a socket of a wrong type")
  81. }
  82. None => panic!("handle does not refer to a valid socket")
  83. }
  84. }
  85. /// Remove a socket from the set, without changing its state.
  86. ///
  87. /// # Panics
  88. /// This function may panic if the handle does not belong to this socket set.
  89. pub fn remove(&mut self, handle: Handle) -> Socket<'b, 'c> {
  90. net_trace!("[{}]: removing", handle.0);
  91. match self.sockets[handle.0].take() {
  92. Some(item) => item.socket,
  93. None => panic!("handle does not refer to a valid socket")
  94. }
  95. }
  96. /// Increase reference count by 1.
  97. ///
  98. /// # Panics
  99. /// This function may panic if the handle does not belong to this socket set.
  100. pub fn retain(&mut self, handle: Handle) {
  101. self.sockets[handle.0]
  102. .as_mut()
  103. .expect("handle does not refer to a valid socket")
  104. .refs += 1
  105. }
  106. /// Decrease reference count by 1.
  107. ///
  108. /// # Panics
  109. /// This function may panic if the handle does not belong to this socket set,
  110. /// or if the reference count is already zero.
  111. pub fn release(&mut self, handle: Handle) {
  112. let refs = &mut self.sockets[handle.0]
  113. .as_mut()
  114. .expect("handle does not refer to a valid socket")
  115. .refs;
  116. if *refs == 0 { panic!("decreasing reference count past zero") }
  117. *refs -= 1
  118. }
  119. /// Prune the sockets in this set.
  120. ///
  121. /// Pruning affects sockets with reference count 0. Open sockets are closed.
  122. /// Closed sockets are removed and dropped.
  123. pub fn prune(&mut self) {
  124. for (index, item) in self.sockets.iter_mut().enumerate() {
  125. let mut may_remove = false;
  126. if let &mut Some(Item { refs: 0, ref mut socket }) = item {
  127. match socket {
  128. #[cfg(feature = "proto-raw")]
  129. &mut Socket::Raw(_) =>
  130. may_remove = true,
  131. #[cfg(feature = "proto-udp")]
  132. &mut Socket::Udp(_) =>
  133. may_remove = true,
  134. #[cfg(feature = "proto-tcp")]
  135. &mut Socket::Tcp(ref mut socket) =>
  136. if socket.state() == TcpState::Closed {
  137. may_remove = true
  138. } else {
  139. socket.close()
  140. },
  141. &mut Socket::__Nonexhaustive(_) => unreachable!()
  142. }
  143. }
  144. if may_remove {
  145. net_trace!("[{}]: pruning", index);
  146. *item = None
  147. }
  148. }
  149. }
  150. /// Iterate every socket in this set.
  151. pub fn iter<'d>(&'d self) -> Iter<'d, 'b, 'c> {
  152. Iter { lower: self.sockets.iter() }
  153. }
  154. /// Iterate every socket in this set, as SocketRef.
  155. pub fn iter_mut<'d>(&'d mut self) -> IterMut<'d, 'b, 'c> {
  156. IterMut { lower: self.sockets.iter_mut() }
  157. }
  158. }
  159. /// Immutable socket set iterator.
  160. ///
  161. /// This struct is created by the [iter](struct.SocketSet.html#method.iter)
  162. /// on [socket sets](struct.SocketSet.html).
  163. pub struct Iter<'a, 'b: 'a, 'c: 'a + 'b> {
  164. lower: slice::Iter<'a, Option<Item<'b, 'c>>>
  165. }
  166. impl<'a, 'b: 'a, 'c: 'a + 'b> Iterator for Iter<'a, 'b, 'c> {
  167. type Item = &'a Socket<'b, 'c>;
  168. fn next(&mut self) -> Option<Self::Item> {
  169. while let Some(item_opt) = self.lower.next() {
  170. if let Some(item) = item_opt.as_ref() {
  171. return Some(&item.socket)
  172. }
  173. }
  174. None
  175. }
  176. }
  177. /// Mutable socket set iterator.
  178. ///
  179. /// This struct is created by the [iter_mut](struct.SocketSet.html#method.iter_mut)
  180. /// on [socket sets](struct.SocketSet.html).
  181. pub struct IterMut<'a, 'b: 'a, 'c: 'a + 'b> {
  182. lower: slice::IterMut<'a, Option<Item<'b, 'c>>>,
  183. }
  184. impl<'a, 'b: 'a, 'c: 'a + 'b> Iterator for IterMut<'a, 'b, 'c> {
  185. type Item = SocketRef<'a, Socket<'b, 'c>>;
  186. fn next(&mut self) -> Option<Self::Item> {
  187. while let Some(item_opt) = self.lower.next() {
  188. if let Some(item) = item_opt.as_mut() {
  189. return Some(SocketRef::new(&mut item.socket))
  190. }
  191. }
  192. None
  193. }
  194. }