| 1 | //! A generic event source wrapping an IO objects or file descriptor |
| 2 | //! |
| 3 | //! You can use this general purpose adapter around file-descriptor backed objects to |
| 4 | //! insert into an [`EventLoop`](crate::EventLoop). |
| 5 | //! |
| 6 | //! The event generated by this [`Generic`] event source are the [`Readiness`](crate::Readiness) |
| 7 | //! notification itself, and the monitored object is provided to your callback as the second |
| 8 | //! argument. |
| 9 | //! |
| 10 | //! ``` |
| 11 | //! # extern crate calloop; |
| 12 | //! use calloop::{generic::Generic, Interest, Mode, PostAction}; |
| 13 | //! |
| 14 | //! # fn main() { |
| 15 | //! # let mut event_loop = calloop::EventLoop::<()>::try_new() |
| 16 | //! # .expect("Failed to initialize the event loop!"); |
| 17 | //! # let handle = event_loop.handle(); |
| 18 | //! # let io_object = 0; |
| 19 | //! handle.insert_source( |
| 20 | //! // wrap your IO object in a Generic, here we register for read readiness |
| 21 | //! // in level-triggering mode |
| 22 | //! Generic::new(io_object, Interest::READ, Mode::Level), |
| 23 | //! |readiness, io_object, shared_data| { |
| 24 | //! // The first argument of the callback is a Readiness |
| 25 | //! // The second is a &mut reference to your object |
| 26 | //! |
| 27 | //! // your callback needs to return a Result<PostAction, std::io::Error> |
| 28 | //! // if it returns an error, the event loop will consider this event |
| 29 | //! // event source as erroring and report it to the user. |
| 30 | //! Ok(PostAction::Continue) |
| 31 | //! } |
| 32 | //! ); |
| 33 | //! # } |
| 34 | //! ``` |
| 35 | //! |
| 36 | //! It can also help you implementing your own event sources: just have |
| 37 | //! these `Generic<_>` as fields of your event source, and delegate the |
| 38 | //! [`EventSource`](crate::EventSource) implementation to them. |
| 39 | //! |
| 40 | //! If you need to directly work with a [`RawFd`](std::os::unix::io::RawFd), rather than an |
| 41 | //! FD-backed object, see [`Generic::from_fd`](Generic#method.from_fd). |
| 42 | |
| 43 | use std::{marker::PhantomData, os::unix::io::AsRawFd}; |
| 44 | |
| 45 | use crate::{EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory}; |
| 46 | |
| 47 | /// A generic event source wrapping a FD-backed type |
| 48 | #[derive(Debug)] |
| 49 | pub struct Generic<F: AsRawFd, E = std::io::Error> { |
| 50 | /// The wrapped FD-backed type |
| 51 | pub file: F, |
| 52 | /// The programmed interest |
| 53 | pub interest: Interest, |
| 54 | /// The programmed mode |
| 55 | pub mode: Mode, |
| 56 | |
| 57 | // This token is used by the event loop logic to look up this source when an |
| 58 | // event occurs. |
| 59 | token: Option<Token>, |
| 60 | |
| 61 | // This allows us to make the associated error and return types generic. |
| 62 | _error_type: PhantomData<E>, |
| 63 | } |
| 64 | |
| 65 | impl<F: AsRawFd> Generic<F, std::io::Error> { |
| 66 | /// Wrap a FD-backed type into a `Generic` event source that uses |
| 67 | /// [`std::io::Error`] as its error type. |
| 68 | pub fn new(file: F, interest: Interest, mode: Mode) -> Generic<F, std::io::Error> { |
| 69 | Generic { |
| 70 | file, |
| 71 | interest, |
| 72 | mode, |
| 73 | token: None, |
| 74 | _error_type: PhantomData::default(), |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Wrap a FD-backed type into a `Generic` event source using an arbitrary error type. |
| 79 | pub fn new_with_error<E>(file: F, interest: Interest, mode: Mode) -> Generic<F, E> { |
| 80 | Generic { |
| 81 | file, |
| 82 | interest, |
| 83 | mode, |
| 84 | token: None, |
| 85 | _error_type: PhantomData::default(), |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | impl<F: AsRawFd, E> Generic<F, E> { |
| 91 | /// Unwrap the `Generic` source to retrieve the underlying type |
| 92 | pub fn unwrap(self) -> F { |
| 93 | self.file |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | impl<F, E> EventSource for Generic<F, E> |
| 98 | where |
| 99 | F: AsRawFd, |
| 100 | E: Into<Box<dyn std::error::Error + Send + Sync>>, |
| 101 | { |
| 102 | type Event = Readiness; |
| 103 | type Metadata = F; |
| 104 | type Ret = Result<PostAction, E>; |
| 105 | type Error = E; |
| 106 | |
| 107 | fn process_events<C>( |
| 108 | &mut self, |
| 109 | readiness: Readiness, |
| 110 | token: Token, |
| 111 | mut callback: C, |
| 112 | ) -> Result<PostAction, Self::Error> |
| 113 | where |
| 114 | C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret, |
| 115 | { |
| 116 | // If the token is invalid or not ours, skip processing. |
| 117 | if self.token != Some(token) { |
| 118 | return Ok(PostAction::Continue); |
| 119 | } |
| 120 | |
| 121 | callback(readiness, &mut self.file) |
| 122 | } |
| 123 | |
| 124 | fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> { |
| 125 | let token = token_factory.token(); |
| 126 | |
| 127 | poll.register(self.file.as_raw_fd(), self.interest, self.mode, token)?; |
| 128 | |
| 129 | self.token = Some(token); |
| 130 | Ok(()) |
| 131 | } |
| 132 | |
| 133 | fn reregister( |
| 134 | &mut self, |
| 135 | poll: &mut Poll, |
| 136 | token_factory: &mut TokenFactory, |
| 137 | ) -> crate::Result<()> { |
| 138 | let token = token_factory.token(); |
| 139 | |
| 140 | poll.reregister(self.file.as_raw_fd(), self.interest, self.mode, token)?; |
| 141 | |
| 142 | self.token = Some(token); |
| 143 | Ok(()) |
| 144 | } |
| 145 | |
| 146 | fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> { |
| 147 | poll.unregister(self.file.as_raw_fd())?; |
| 148 | self.token = None; |
| 149 | Ok(()) |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | #[cfg(test)] |
| 154 | mod tests { |
| 155 | use std::io::{Read, Write}; |
| 156 | |
| 157 | use super::Generic; |
| 158 | use crate::{Dispatcher, Interest, Mode, PostAction}; |
| 159 | #[cfg(unix)] |
| 160 | #[test] |
| 161 | fn dispatch_unix() { |
| 162 | use std::os::unix::net::UnixStream; |
| 163 | |
| 164 | let mut event_loop = crate::EventLoop::try_new().unwrap(); |
| 165 | |
| 166 | let handle = event_loop.handle(); |
| 167 | |
| 168 | let (mut tx, rx) = UnixStream::pair().unwrap(); |
| 169 | |
| 170 | let generic = Generic::new(rx, Interest::READ, Mode::Level); |
| 171 | |
| 172 | let mut dispached = false; |
| 173 | |
| 174 | let _generic_token = handle |
| 175 | .insert_source(generic, move |readiness, file, d| { |
| 176 | assert!(readiness.readable); |
| 177 | // we have not registered for writability |
| 178 | assert!(!readiness.writable); |
| 179 | let mut buffer = vec![0; 10]; |
| 180 | let ret = file.read(&mut buffer).unwrap(); |
| 181 | assert_eq!(ret, 6); |
| 182 | assert_eq!(&buffer[..6], &[1, 2, 3, 4, 5, 6]); |
| 183 | |
| 184 | *d = true; |
| 185 | Ok(PostAction::Continue) |
| 186 | }) |
| 187 | .unwrap(); |
| 188 | |
| 189 | event_loop |
| 190 | .dispatch(Some(::std::time::Duration::ZERO), &mut dispached) |
| 191 | .unwrap(); |
| 192 | |
| 193 | assert!(!dispached); |
| 194 | |
| 195 | let ret = tx.write(&[1, 2, 3, 4, 5, 6]).unwrap(); |
| 196 | assert_eq!(ret, 6); |
| 197 | tx.flush().unwrap(); |
| 198 | |
| 199 | event_loop |
| 200 | .dispatch(Some(::std::time::Duration::ZERO), &mut dispached) |
| 201 | .unwrap(); |
| 202 | |
| 203 | assert!(dispached); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn register_deregister_unix() { |
| 208 | use std::os::unix::net::UnixStream; |
| 209 | |
| 210 | let mut event_loop = crate::EventLoop::try_new().unwrap(); |
| 211 | |
| 212 | let handle = event_loop.handle(); |
| 213 | |
| 214 | let (mut tx, rx) = UnixStream::pair().unwrap(); |
| 215 | |
| 216 | let generic = Generic::new(rx, Interest::READ, Mode::Level); |
| 217 | let dispatcher = Dispatcher::new(generic, move |_, _, d| { |
| 218 | *d = true; |
| 219 | Ok(PostAction::Continue) |
| 220 | }); |
| 221 | |
| 222 | let mut dispached = false; |
| 223 | |
| 224 | let generic_token = handle.register_dispatcher(dispatcher.clone()).unwrap(); |
| 225 | |
| 226 | event_loop |
| 227 | .dispatch(Some(::std::time::Duration::ZERO), &mut dispached) |
| 228 | .unwrap(); |
| 229 | |
| 230 | assert!(!dispached); |
| 231 | |
| 232 | // remove the source, and then write something |
| 233 | |
| 234 | event_loop.handle().remove(generic_token); |
| 235 | |
| 236 | let ret = tx.write(&[1, 2, 3, 4, 5, 6]).unwrap(); |
| 237 | assert_eq!(ret, 6); |
| 238 | tx.flush().unwrap(); |
| 239 | |
| 240 | event_loop |
| 241 | .dispatch(Some(::std::time::Duration::ZERO), &mut dispached) |
| 242 | .unwrap(); |
| 243 | |
| 244 | // the source has not been dispatched, as the source is no longer here |
| 245 | assert!(!dispached); |
| 246 | |
| 247 | // insert it again |
| 248 | let generic = dispatcher.into_source_inner(); |
| 249 | let _generic_token = handle |
| 250 | .insert_source(generic, move |readiness, file, d| { |
| 251 | assert!(readiness.readable); |
| 252 | // we have not registered for writability |
| 253 | assert!(!readiness.writable); |
| 254 | let mut buffer = vec![0; 10]; |
| 255 | let ret = file.read(&mut buffer).unwrap(); |
| 256 | assert_eq!(ret, 6); |
| 257 | assert_eq!(&buffer[..6], &[1, 2, 3, 4, 5, 6]); |
| 258 | |
| 259 | *d = true; |
| 260 | Ok(PostAction::Continue) |
| 261 | }) |
| 262 | .unwrap(); |
| 263 | |
| 264 | event_loop |
| 265 | .dispatch(Some(::std::time::Duration::ZERO), &mut dispached) |
| 266 | .unwrap(); |
| 267 | |
| 268 | // the has now been properly dispatched |
| 269 | assert!(dispached); |
| 270 | } |
| 271 | } |