Debian Codegraph @

src/loop_logic.rs

raw symbols ◀ ▶
Source reconstructed at patch state 2 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 use std::cell::{Cell, RefCell};
2 use std::fmt::Debug;
3 use std::io;
4 use std::os::unix::io::AsRawFd;
5 use std::rc::Rc;
6 use std::sync::atomic::{AtomicBool, Ordering};
7 use std::sync::Arc;
8 use std::time::{Duration, Instant};
9
10 use slotmap::SlotMap;
11
12 use crate::sources::{Dispatcher, EventSource, Idle, IdleDispatcher};
13 use crate::{EventDispatcher, InsertError, Poll, PostAction, TokenFactory};
14
15 type IdleCallback<'i, Data> = Rc<RefCell<dyn IdleDispatcher<Data> + 'i>>;
16
17 slotmap::new_key_type! {
18 pub(crate) struct CalloopKey;
19 }
20
21 /// A token representing a registration in the [`EventLoop`].
22 ///
23 /// This token is given to you by the [`EventLoop`] when an [`EventSource`] is inserted or
24 /// a [`Dispatcher`] is registered. You can use it to [disable](LoopHandle#method.disable),
25 /// [enable](LoopHandle#method.enable), [update`](LoopHandle#method.update),
26 /// [remove](LoopHandle#method.remove) or [kill](LoopHandle#method.kill) it.
27 #[derive(Debug, PartialEq, Clone, Copy)]
28 pub struct RegistrationToken {
29 key: CalloopKey,
30 }
31
32 pub(crate) struct LoopInner<'l, Data> {
33 pub(crate) poll: RefCell<Poll>,
34 pub(crate) sources: RefCell<SlotMap<CalloopKey, Rc<dyn EventDispatcher<Data> + 'l>>>,
35 idles: RefCell<Vec<IdleCallback<'l, Data>>>,
36 pending_action: Cell<PostAction>,
37 }
38
39 /// An handle to an event loop
40 ///
41 /// This handle allows you to insert new sources and idles in this event loop,
42 /// it can be cloned, and it is possible to insert new sources from within a source
43 /// callback.
44 pub struct LoopHandle<'l, Data> {
45 inner: Rc<LoopInner<'l, Data>>,
46 }
47
48 impl<'l, Data> std::fmt::Debug for LoopHandle<'l, Data> {
49 #[cfg_attr(coverage, no_coverage)]
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 f.write_str("LoopHandle { ... }")
52 }
53 }
54
55 impl<'l, Data> Clone for LoopHandle<'l, Data> {
56 #[cfg_attr(coverage, no_coverage)]
57 fn clone(&self) -> Self {
58 LoopHandle {
59 inner: self.inner.clone(),
60 }
61 }
62 }
63
64 impl<'l, Data> LoopHandle<'l, Data> {
65 /// Inserts a new event source in the loop.
66 ///
67 /// The provided callback will be called during the dispatching cycles whenever the
68 /// associated source generates events, see `EventLoop::dispatch(..)` for details.
69 ///
70 /// This function takes ownership of the event source. Use `register_dispatcher`
71 /// if you need access to the event source after this call.
72 pub fn insert_source<S, F>(
73 &self,
74 source: S,
75 callback: F,
76 ) -> Result<RegistrationToken, InsertError<S>>
77 where
78 S: EventSource + 'l,
79 F: FnMut(S::Event, &mut S::Metadata, &mut Data) -> S::Ret + 'l,
80 {
81 let dispatcher = Dispatcher::new(source, callback);
82 self.register_dispatcher(dispatcher.clone())
83 .map_err(|error| InsertError {
84 error,
85 inserted: dispatcher.into_source_inner(),
86 })
87 }
88
89 /// Registers a `Dispatcher` in the loop.
90 ///
91 /// Use this function if you need access to the event source after its insertion in the loop.
92 ///
93 /// See also `insert_source`.
94 pub fn register_dispatcher<S>(
95 &self,
96 dispatcher: Dispatcher<'l, S, Data>,
97 ) -> crate::Result<RegistrationToken>
98 where
99 S: EventSource + 'l,
100 {
101 let mut sources = self.inner.sources.borrow_mut();
102 let mut poll = self.inner.poll.borrow_mut();
103
104 let key = sources.insert(dispatcher.clone_as_event_dispatcher());
105 let ret = sources
106 .get(key)
107 .unwrap()
108 .register(&mut *poll, &mut TokenFactory::new(key));
109
110 if let Err(error) = ret {
111 sources.remove(key).expect("Source was just inserted?!");
112 return Err(error);
113 }
114
115 Ok(RegistrationToken { key })
116 }
117
118 /// Inserts an idle callback.
119 ///
120 /// This callback will be called during a dispatching cycle when the event loop has
121 /// finished processing all pending events from the sources and becomes idle.
122 pub fn insert_idle<'i, F: FnOnce(&mut Data) + 'l + 'i>(&self, callback: F) -> Idle<'i> {
123 let mut opt_cb = Some(callback);
124 let callback = Rc::new(RefCell::new(Some(move |data: &mut Data| {
125 if let Some(cb) = opt_cb.take() {
126 cb(data);
127 }
128 })));
129 self.inner.idles.borrow_mut().push(callback.clone());
130 Idle { callback }
131 }
132
133 /// Enables this previously disabled event source.
134 ///
135 /// This previously disabled source will start generating events again.
136 ///
137 /// **Note:** this cannot be done from within the source callback.
138 pub fn enable(&self, token: &RegistrationToken) -> crate::Result<()> {
139 if let Some(source) = self.inner.sources.borrow().get(token.key) {
140 source.register(
141 &mut *self.inner.poll.borrow_mut(),
142 &mut TokenFactory::new(token.key),
143 )?;
144 }
145 Ok(())
146 }
147
148 /// Makes this source update its registration.
149 ///
150 /// If after accessing the source you changed its parameters in a way that requires
151 /// updating its registration.
152 pub fn update(&self, token: &RegistrationToken) -> crate::Result<()> {
153 if let Some(source) = self.inner.sources.borrow().get(token.key) {
154 if !source.reregister(
155 &mut *self.inner.poll.borrow_mut(),
156 &mut TokenFactory::new(token.key),
157 )? {
158 // we are in a callback, store for later processing
159 self.inner.pending_action.set(PostAction::Reregister);
160 }
161 }
162 Ok(())
163 }
164
165 /// Disables this event source.
166 ///
167 /// The source remains in the event loop, but it'll no longer generate events
168 pub fn disable(&self, token: &RegistrationToken) -> crate::Result<()> {
169 if let Some(source) = self.inner.sources.borrow().get(token.key) {
170 if !source.unregister(&mut *self.inner.poll.borrow_mut())? {
171 // we are in a callback, store for later processing
172 self.inner.pending_action.set(PostAction::Disable);
173 }
174 }
175 Ok(())
176 }
177
178 /// Removes this source from the event loop.
179 pub fn remove(&self, token: RegistrationToken) {
180 if let Some(source) = self.inner.sources.borrow_mut().remove(token.key) {
181 if let Err(e) = source.unregister(&mut self.inner.poll.borrow_mut()) {
182 log::warn!(
183 "[calloop] Failed to unregister source from the polling system: {:?}",
184 e
185 );
186 }
187 }
188 }
189
190 /// Wrap an IO object into an async adapter
191 ///
192 /// This adapter turns the IO object into an async-aware one that can be used in futures.
193 /// The readiness of these futures will be driven by the event loop.
194 ///
195 /// The produced futures can be polled in any executor, and notably the one provided by
196 /// calloop.
197 pub fn adapt_io<F: AsRawFd>(&self, fd: F) -> crate::Result<crate::io::Async<'l, F>> {
198 crate::io::Async::new(self.inner.clone(), fd)
199 }
200 }
201
202 /// An event loop
203 ///
204 /// This loop can host several event sources, that can be dynamically added or removed.
205 pub struct EventLoop<'l, Data> {
206 handle: LoopHandle<'l, Data>,
207 stop_signal: Arc<AtomicBool>,
208 ping: crate::sources::ping::Ping,
209 }
210
211 impl<'l, Data> std::fmt::Debug for EventLoop<'l, Data> {
212 #[cfg_attr(coverage, no_coverage)]
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 f.write_str("EventLoop { ... }")
215 }
216 }
217
218 impl<'l, Data> EventLoop<'l, Data> {
219 /// Create a new event loop
220 ///
221 /// Fails if the initialization of the polling system failed.
222 pub fn try_new() -> crate::Result<Self> {
223 Self::inner_new(false)
224 }
225
226 /// Create a new event loop in high precision mode
227 ///
228 /// On some platforms it requires to setup more resources to enable high-precision
229 /// (sub millisecond) capabilities, so you should use this constructor if you need
230 /// this kind of precision.
231 ///
232 /// Fails if the initialization of the polling system failed.
233 pub fn try_new_high_precision() -> crate::Result<Self> {
234 Self::inner_new(true)
235 }
236
237 fn inner_new(high_precision: bool) -> crate::Result<Self> {
238 let poll = Poll::new(high_precision)?;
239 let handle = LoopHandle {
240 inner: Rc::new(LoopInner {
241 poll: RefCell::new(poll),
242 sources: RefCell::new(SlotMap::with_key()),
243 idles: RefCell::new(Vec::new()),
244 pending_action: Cell::new(PostAction::Continue),
245 }),
246 };
247 let (ping, ping_source) = crate::sources::ping::make_ping()?;
248 handle.insert_source(ping_source, |_, _, _| {})?;
249 Ok(EventLoop {
250 handle,
251 stop_signal: Arc::new(AtomicBool::new(false)),
252 ping,
253 })
254 }
255
256 /// Retrieve a loop handle
257 pub fn handle(&self) -> LoopHandle<'l, Data> {
258 self.handle.clone()
259 }
260
261 fn dispatch_events(
262 &mut self,
263 mut timeout: Option<Duration>,
264 data: &mut Data,
265 ) -> crate::Result<()> {
266 let now = Instant::now();
267 let events = {
268 let mut poll = self.handle.inner.poll.borrow_mut();
269 loop {
270 let result = poll.poll(timeout);
271
272 match result {
273 Ok(events) => break events,
274 Err(crate::Error::IoError(err)) if err.kind() == io::ErrorKind::Interrupted => {
275 // Interrupted by a signal. Update timeout and retry.
276 if let Some(to) = timeout {
277 let elapsed = now.elapsed();
278 if elapsed >= to {
279 return Ok(());
280 } else {
281 timeout = Some(to - elapsed);
282 }
283 }
284 }
285 Err(err) => return Err(err),
286 };
287 }
288 };
289
290 for event in events {
291 let opt_disp = self
292 .handle
293 .inner
294 .sources
295 .borrow()
296 .get(event.token.key)
297 .cloned();
298
299 if let Some(disp) = opt_disp {
300 let mut ret = disp.process_events(event.readiness, event.token, data)?;
301
302 // if the returned PostAction is Continue, it may be overwritten by an user-specified pending action
303 let pending_action = self
304 .handle
305 .inner
306 .pending_action
307 .replace(PostAction::Continue);
308 if let PostAction::Continue = ret {
309 ret = pending_action;
310 }
311
312 match ret {
313 PostAction::Reregister => {
314 disp.reregister(
315 &mut self.handle.inner.poll.borrow_mut(),
316 &mut TokenFactory::new(event.token.key),
317 )?;
318 }
319 PostAction::Disable => {
320 disp.unregister(&mut self.handle.inner.poll.borrow_mut())?;
321 }
322 PostAction::Remove => {
323 // delete the source from the list, it'll be cleaned up with the if just below
324 self.handle
325 .inner
326 .sources
327 .borrow_mut()
328 .remove(event.token.key);
329 }
330 PostAction::Continue => {}
331 }
332
333 if !self
334 .handle
335 .inner
336 .sources
337 .borrow()
338 .contains_key(event.token.key)
339 {
340 // the source has been removed from within its callback, unregister it
341 let mut poll = self.handle.inner.poll.borrow_mut();
342 if let Err(e) = disp.unregister(&mut *poll) {
343 log::warn!(
344 "[calloop] Failed to unregister source from the polling system: {:?}",
345 e
346 );
347 }
348 }
349 } else {
350 log::warn!(
351 "[calloop] Received an event for non-existence source: {:?}",
352 event.token.key
353 );
354 }
355 }
356
357 Ok(())
358 }
359
360 fn dispatch_idles(&mut self, data: &mut Data) {
361 let idles = std::mem::take(&mut *self.handle.inner.idles.borrow_mut());
362 for idle in idles {
363 idle.borrow_mut().dispatch(data);
364 }
365 }
366
367 fn invoke_pre_run(&self, data: &mut Data) -> crate::Result<()> {
368 let sources = self
369 .handle
370 .inner
371 .sources
372 .borrow()
373 .values()
374 .cloned()
375 .collect::<Vec<_>>();
376
377 for source in sources {
378 source.pre_run(data)?;
379 }
380
381 Ok(())
382 }
383
384 fn invoke_post_run(&self, data: &mut Data) -> crate::Result<()> {
385 let sources = self
386 .handle
387 .inner
388 .sources
389 .borrow()
390 .values()
391 .cloned()
392 .collect::<Vec<_>>();
393
394 for source in sources {
395 source.post_run(data)?;
396 }
397
398 Ok(())
399 }
400
401 /// Dispatch pending events to their callbacks
402 ///
403 /// If some sources have events available, their callbacks will be immediatly called.
404 /// Otherwise this will wait until an event is receive or the provided `timeout`
405 /// is reached. If `timeout` is `None`, it will wait without a duration limit.
406 ///
407 /// Once pending events have been processed or the timeout is reached, all pending
408 /// idle callbacks will be fired before this method returns.
409 pub fn dispatch<D: Into<Option<Duration>>>(
410 &mut self,
411 timeout: D,
412 data: &mut Data,
413 ) -> crate::Result<()> {
414 self.invoke_pre_run(data)?;
415 self.dispatch_events(timeout.into(), data)?;
416 self.dispatch_idles(data);
417 self.invoke_post_run(data)?;
418
419 Ok(())
420 }
421
422 /// Get a signal to stop this event loop from running
423 ///
424 /// To be used in conjunction with the `run()` method.
425 pub fn get_signal(&self) -> LoopSignal {
426 LoopSignal {
427 signal: self.stop_signal.clone(),
428 ping: self.ping.clone(),
429 }
430 }
431
432 /// Run this event loop
433 ///
434 /// This will repeatedly try to dispatch events (see the `dispatch()` method) on
435 /// this event loop, waiting at most `timeout` every time.
436 ///
437 /// Between each dispatch wait, your provided callback will be called.
438 ///
439 /// You can use the `get_signal()` method to retrieve a way to stop or wakeup
440 /// the event loop from anywhere.
441 pub fn run<F, D: Into<Option<Duration>>>(
442 &mut self,
443 timeout: D,
444 data: &mut Data,
445 mut cb: F,
446 ) -> crate::Result<()>
447 where
448 F: FnMut(&mut Data),
449 {
450 let timeout = timeout.into();
451 self.stop_signal.store(false, Ordering::Release);
452 self.invoke_pre_run(data)?;
453 while !self.stop_signal.load(Ordering::Acquire) {
454 self.dispatch_events(timeout, data)?;
455 self.dispatch_idles(data);
456 cb(data);
457 }
458 self.invoke_post_run(data)?;
459 Ok(())
460 }
461 }
462
463 /// A signal that can be shared between thread to stop or wakeup a running
464 /// event loop
465 #[derive(Clone)]
466 pub struct LoopSignal {
467 signal: Arc<AtomicBool>,
468 ping: crate::sources::ping::Ping,
469 }
470
471 impl std::fmt::Debug for LoopSignal {
472 #[cfg_attr(coverage, no_coverage)]
473 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474 f.write_str("LoopSignal { ... }")
475 }
476 }
477
478 impl LoopSignal {
479 /// Stop the event loop
480 ///
481 /// Once this method is called, the next time the event loop has finished
482 /// waiting for events, it will return rather than starting to wait again.
483 ///
484 /// This is only usefull if you are using the `EventLoop::run()` method.
485 pub fn stop(&self) {
486 self.signal.store(true, Ordering::Release);
487 }
488
489 /// Wake up the event loop
490 ///
491 /// This sends a dummy event to the event loop to simulate the reception
492 /// of an event, making the wait return early. Called after `stop()`, this
493 /// ensures the event loop will terminate quickly if you specified a long
494 /// timeout (or no timeout at all) to the `dispatch` or `run` method.
495 pub fn wakeup(&self) {
496 self.ping.ping();
497 }
498 }
499
500 #[cfg(test)]
501 mod tests {
502 use std::time::Duration;
503 use std::os::fd::IntoRawFd;
504
505 use crate::{
506 generic::Generic, ping::*, Dispatcher, Interest, Mode, Poll, PostAction, Readiness,
507 RegistrationToken, Token, TokenFactory,
508 };
509
510 use super::EventLoop;
511
512 #[test]
513 fn dispatch_idle() {
514 let mut event_loop = EventLoop::try_new().unwrap();
515
516 let mut dispatched = false;
517
518 event_loop.handle().insert_idle(|d| {
519 *d = true;
520 });
521
522 event_loop
523 .dispatch(Some(Duration::ZERO), &mut dispatched)
524 .unwrap();
525
526 assert!(dispatched);
527 }
528
529 #[test]
530 fn cancel_idle() {
531 let mut event_loop = EventLoop::try_new().unwrap();
532
533 let mut dispatched = false;
534
535 let handle = event_loop.handle();
536 let idle = handle.insert_idle(move |d| {
537 *d = true;
538 });
539
540 idle.cancel();
541
542 event_loop
543 .dispatch(Duration::ZERO, &mut dispatched)
544 .unwrap();
545
546 assert!(!dispatched);
547 }
548
549 #[test]
550 fn wakeup() {
551 let mut event_loop = EventLoop::try_new().unwrap();
552
553 let signal = event_loop.get_signal();
554
555 ::std::thread::spawn(move || {
556 ::std::thread::sleep(Duration::from_millis(500));
557 signal.wakeup();
558 });
559
560 // the test should return
561 event_loop.dispatch(None, &mut ()).unwrap();
562 }
563
564 #[test]
565 fn wakeup_stop() {
566 let mut event_loop = EventLoop::try_new().unwrap();
567
568 let signal = event_loop.get_signal();
569
570 ::std::thread::spawn(move || {
571 ::std::thread::sleep(Duration::from_millis(500));
572 signal.stop();
573 signal.wakeup();
574 });
575
576 // the test should return
577 event_loop.run(None, &mut (), |_| {}).unwrap();
578 }
579
580 #[test]
581 fn insert_bad_source() {
582 let event_loop = EventLoop::<()>::try_new().unwrap();
583 let ret = event_loop.handle().insert_source(
584 crate::sources::generic::Generic::new(420, Interest::READ, Mode::Level),
585 |_, _, _| Ok(PostAction::Continue),
586 );
587 assert!(ret.is_err());
588 }
589
590 #[test]
591 #[ignore]
592 fn insert_source_no_interest() {
593 let event_loop = EventLoop::<()>::try_new().unwrap();
594 let ret = event_loop.handle().insert_source(
595 crate::sources::generic::Generic::new(0, Interest::EMPTY, Mode::Level),
596 |_, _, _| Ok(PostAction::Continue),
597 );
598 assert!(ret.is_ok());
599 }
600
601 #[test]
602 fn disarm_rearm() {
603 let mut event_loop = EventLoop::<bool>::try_new().unwrap();
604 let (ping, ping_source) = make_ping().unwrap();
605
606 let ping_token = event_loop
607 .handle()
608 .insert_source(ping_source, |(), &mut (), dispatched| {
609 *dispatched = true;
610 })
611 .unwrap();
612
613 ping.ping();
614 let mut dispatched = false;
615 event_loop
616 .dispatch(Duration::ZERO, &mut dispatched)
617 .unwrap();
618 assert!(dispatched);
619
620 // disable the source
621 ping.ping();
622 event_loop.handle().disable(&ping_token).unwrap();
623 let mut dispatched = false;
624 event_loop
625 .dispatch(Duration::ZERO, &mut dispatched)
626 .unwrap();
627 assert!(!dispatched);
628
629 // disabling it again is an error
630 event_loop.handle().disable(&ping_token).unwrap_err();
631
632 // reenable it, the previous ping now gets dispatched
633 event_loop.handle().enable(&ping_token).unwrap();
634 let mut dispatched = false;
635 event_loop
636 .dispatch(Duration::ZERO, &mut dispatched)
637 .unwrap();
638 assert!(dispatched);
639 }
640
641 #[test]
642 fn multiple_tokens() {
643 struct DoubleSource {
644 ping1: PingSource,
645 ping2: PingSource,
646 }
647
648 impl crate::EventSource for DoubleSource {
649 type Event = u32;
650 type Metadata = ();
651 type Ret = ();
652 type Error = PingError;
653
654 fn process_events<F>(
655 &mut self,
656 readiness: Readiness,
657 token: Token,
658 mut callback: F,
659 ) -> Result<PostAction, Self::Error>
660 where
661 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
662 {
663 self.ping1
664 .process_events(readiness, token, |(), &mut ()| callback(1, &mut ()))?;
665 self.ping2
666 .process_events(readiness, token, |(), &mut ()| callback(2, &mut ()))?;
667 Ok(PostAction::Continue)
668 }
669
670 fn register(
671 &mut self,
672 poll: &mut Poll,
673 token_factory: &mut TokenFactory,
674 ) -> crate::Result<()> {
675 self.ping1.register(poll, token_factory)?;
676 self.ping2.register(poll, token_factory)?;
677 Ok(())
678 }
679
680 fn reregister(
681 &mut self,
682 poll: &mut Poll,
683 token_factory: &mut TokenFactory,
684 ) -> crate::Result<()> {
685 self.ping1.reregister(poll, token_factory)?;
686 self.ping2.reregister(poll, token_factory)?;
687 Ok(())
688 }
689
690 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
691 self.ping1.unregister(poll)?;
692 self.ping2.unregister(poll)?;
693 Ok(())
694 }
695 }
696
697 let mut event_loop = EventLoop::<u32>::try_new().unwrap();
698
699 let (ping1, source1) = make_ping().unwrap();
700 let (ping2, source2) = make_ping().unwrap();
701
702 let source = DoubleSource {
703 ping1: source1,
704 ping2: source2,
705 };
706
707 event_loop
708 .handle()
709 .insert_source(source, |i, _, d| {
710 eprintln!("Dispatching {}", i);
711 *d += i
712 })
713 .unwrap();
714
715 let mut dispatched = 0;
716 ping1.ping();
717 event_loop
718 .dispatch(Duration::ZERO, &mut dispatched)
719 .unwrap();
720 assert_eq!(dispatched, 1);
721
722 dispatched = 0;
723 ping2.ping();
724 event_loop
725 .dispatch(Duration::ZERO, &mut dispatched)
726 .unwrap();
727 assert_eq!(dispatched, 2);
728
729 dispatched = 0;
730 ping1.ping();
731 ping2.ping();
732 event_loop
733 .dispatch(Duration::ZERO, &mut dispatched)
734 .unwrap();
735 assert_eq!(dispatched, 3);
736 }
737
738 #[test]
739 fn change_interests() {
740 use nix::sys::socket::{recv, socketpair, AddressFamily, MsgFlags, SockFlag, SockType};
741 use nix::unistd::write;
742 let mut event_loop = EventLoop::<bool>::try_new().unwrap();
743
744 let (sock1, sock2) = socketpair(
745 AddressFamily::Unix,
746 SockType::Stream,
747 None,
748 SockFlag::empty(), // recv with DONTWAIT will suffice for platforms without SockFlag::SOCK_NONBLOCKING such as macOS
749 )
750 .unwrap();
751 let sock1 = sock1.into_raw_fd();
752 let sock2 = sock2.into_raw_fd();
753
754 let source = Generic::new(sock1, Interest::READ, Mode::Level);
755 let dispatcher = Dispatcher::new(source, |_, &mut fd, dispatched| {
756 *dispatched = true;
757 // read all contents available to drain the socket
758 let mut buf = [0u8; 32];
759 loop {
760 match recv(fd, &mut buf, MsgFlags::MSG_DONTWAIT) {
761 Ok(0) => break, // closed pipe, we are now inert
762 Ok(_) => {}
763 Err(e) => {
764 let e: std::io::Error = e.into();
765 if e.kind() == std::io::ErrorKind::WouldBlock {
766 break;
767 // nothing more to read
768 } else {
769 // propagate error
770 return Err(e);
771 }
772 }
773 }
774 }
775 Ok(PostAction::Continue)
776 });
777
778 let sock_token_1 = event_loop
779 .handle()
780 .register_dispatcher(dispatcher.clone())
781 .unwrap();
782
783 // first dispatch, nothing is readable
784 let mut dispatched = false;
785 event_loop
786 .dispatch(Duration::ZERO, &mut dispatched)
787 .unwrap();
788 assert!(!dispatched);
789
790 // write something, the socket becomes readable
791 write(sock2, &[1, 2, 3]).unwrap();
792 dispatched = false;
793 event_loop
794 .dispatch(Duration::ZERO, &mut dispatched)
795 .unwrap();
796 assert!(dispatched);
797
798 // All has been read, no longer readable
799 dispatched = false;
800 event_loop
801 .dispatch(Duration::ZERO, &mut dispatched)
802 .unwrap();
803 assert!(!dispatched);
804
805 // change the interests for writability instead
806 dispatcher.as_source_mut().interest = Interest::WRITE;
807 event_loop.handle().update(&sock_token_1).unwrap();
808
809 // the socket is writable
810 dispatched = false;
811 event_loop
812 .dispatch(Duration::ZERO, &mut dispatched)
813 .unwrap();
814 assert!(dispatched);
815
816 // change back to readable
817 dispatcher.as_source_mut().interest = Interest::READ;
818 event_loop.handle().update(&sock_token_1).unwrap();
819
820 // the socket is not readable
821 dispatched = false;
822 event_loop
823 .dispatch(Duration::ZERO, &mut dispatched)
824 .unwrap();
825 assert!(!dispatched);
826 }
827
828 #[test]
829 fn kill_source() {
830 let mut event_loop = EventLoop::<Option<RegistrationToken>>::try_new().unwrap();
831
832 let handle = event_loop.handle();
833 let (ping, ping_source) = make_ping().unwrap();
834 let ping_token = event_loop
835 .handle()
836 .insert_source(ping_source, move |(), &mut (), opt_src| {
837 if let Some(src) = opt_src.take() {
838 handle.remove(src);
839 }
840 })
841 .unwrap();
842
843 ping.ping();
844
845 let mut opt_src = Some(ping_token);
846
847 event_loop.dispatch(Duration::ZERO, &mut opt_src).unwrap();
848
849 assert!(opt_src.is_none());
850 }
851
852 #[test]
853 fn non_static_data() {
854 use std::sync::mpsc;
855
856 let (sender, receiver) = mpsc::channel();
857
858 {
859 struct RefSender<'a>(&'a mpsc::Sender<()>);
860 let mut ref_sender = RefSender(&sender);
861
862 let mut event_loop = EventLoop::<RefSender<'_>>::try_new().unwrap();
863 let (ping, ping_source) = make_ping().unwrap();
864 let _ping_token = event_loop
865 .handle()
866 .insert_source(ping_source, |_, _, ref_sender| {
867 ref_sender.0.send(()).unwrap();
868 })
869 .unwrap();
870
871 ping.ping();
872
873 event_loop
874 .dispatch(Duration::ZERO, &mut ref_sender)
875 .unwrap();
876 }
877
878 receiver.recv().unwrap();
879 // sender still usable (e.g. for another EventLoop)
880 drop(sender);
881 }
882
883 // A dummy EventSource to test insertion and removal of sources
884 struct DummySource;
885
886 impl crate::EventSource for DummySource {
887 type Event = ();
888 type Metadata = ();
889 type Ret = ();
890 type Error = crate::Error;
891
892 fn process_events<F>(
893 &mut self,
894 _: Readiness,
895 _: Token,
896 mut callback: F,
897 ) -> Result<PostAction, Self::Error>
898 where
899 F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
900 {
901 callback((), &mut ());
902 Ok(PostAction::Continue)
903 }
904
905 fn register(&mut self, _: &mut Poll, _: &mut TokenFactory) -> crate::Result<()> {
906 Ok(())
907 }
908
909 fn reregister(&mut self, _: &mut Poll, _: &mut TokenFactory) -> crate::Result<()> {
910 Ok(())
911 }
912
913 fn unregister(&mut self, _: &mut Poll) -> crate::Result<()> {
914 Ok(())
915 }
916 }
917 }