calloop/sources/transient.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
//! Wrapper for a transient Calloop event source.
//!
//! If you have high level event source that you expect to remain in the event
//! loop indefinitely, and another event source nested inside that one that you
//! expect to require removal or disabling from time to time, this module can
//! handle it for you.
/// A [`TransientSource`] wraps a Calloop event source and manages its
/// registration. A user of this type only needs to perform the usual Calloop
/// calls (`process_events()` and `*register()`) and the return value of
/// [`process_events()`](crate::EventSource::process_events).
///
/// Rather than needing to check for the full set of
/// [`PostAction`](crate::PostAction) values returned from `process_events()`,
/// you can just check for `Continue` or `Reregister` and pass that back out
/// through your own `process_events()` implementation. In your registration
/// functions, you then only need to call the same function on this type ie.
/// `register()` inside `register()` etc.
///
/// For example, say you have a source that contains a channel along with some
/// other logic. If the channel's sending end has been dropped, it needs to be
/// removed from the loop. So to manage this, you use this in your struct:
///
/// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
/// struct CompositeSource {
/// // Event source for channel.
/// mpsc_receiver: TransientSource<calloop::channel::Channel<T>>,
///
/// // Any other fields go here...
/// }
/// ```
///
/// To create the transient source, you can simply use the `Into`
/// implementation:
///
/// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
/// let (sender, source) = channel();
/// let mpsc_receiver: TransientSource<Channel> = source.into();
/// ```
///
/// (If you want to start off with an empty `TransientSource`, you can just use
/// `Default::default()` instead.)
///
/// `TransientSource` implements [`EventSource`](crate::EventSource) and passes
/// through `process_events()` calls, so in the parent's `process_events()`
/// implementation you can just do this:
///
/// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
/// fn process_events<F>(
/// &mut self,
/// readiness: calloop::Readiness,
/// token: calloop::Token,
/// callback: F,
/// ) -> Result<calloop::PostAction, Self::Error>
/// where
/// F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
/// {
/// let channel_return = self.mpsc_receiver.process_events(readiness, token, callback)?;
///
/// // Perform other logic here...
///
/// Ok(channel_return)
/// }
/// ```
///
/// Note that:
///
/// - You can call `process_events()` on the `TransientSource<Channel>` even
/// if the channel has been unregistered and dropped. All that will happen
/// is that you won't get any events from it.
///
/// - The [`PostAction`](crate::PostAction) returned from `process_events()`
/// will only ever be `PostAction::Continue` or `PostAction::Reregister`.
/// You will still need to combine this with the result of any other sources
/// (transient or not).
///
/// Once you return `channel_return` from your `process_events()` method (and
/// assuming it propagates all the way up to the event loop itself through any
/// other event sources), the event loop might call `reregister()` on your
/// source. All your source has to do is:
///
/// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
/// fn reregister(
/// &mut self,
/// poll: &mut calloop::Poll,
/// token_factory: &mut calloop::TokenFactory,
/// ) -> crate::Result<()> {
/// self.mpsc_receiver.reregister(poll, token_factory)?;
///
/// // Other registration actions...
///
/// Ok(())
/// }
/// ```
///
/// The `TransientSource` will take care of updating the registration of the
/// inner source, even if it actually needs to be unregistered or initially
/// registered.
///
/// ## Replacing or removing `TransientSource`s
///
/// Not properly removing or replacing `TransientSource`s can cause spurious
/// wakeups of the event loop, and in some cases can leak file descriptors or
/// fail to free entries in Calloop's internal data structures. No unsoundness
/// or undefined behaviour will result, but leaking file descriptors can result
/// in errors or panics.
///
/// If you want to remove a source before it returns `PostAction::Remove`, use
/// the [`TransientSource::remove()`] method. If you want to replace a source
/// with another one, use the [`TransientSource::replace()`] method. Either of
/// these may be called at any time during processing or from outside the event
/// loop. Both require either returning `PostAction::Reregister` from the
/// `process_event()` call that does this, or reregistering the event source
/// some other way eg. via the top-level loop handle.
///
/// If, instead, you directly assign a new source to the variable holding the
/// `TransientSource`, the inner source will be dropped before it can be
/// unregistered. For example:
///
/// ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
/// self.mpsc_receiver = Default::default();
/// self.mpsc_receiver = new_channel.into();
/// ```
#[derive(Debug, Default)]
pub struct TransientSource<T> {
state: TransientSourceState<T>,
}
/// This is the internal state of the [`TransientSource`], as a separate type so
/// it's not exposed.
#[derive(Debug)]
enum TransientSourceState<T> {
/// The source should be kept in the loop.
Keep(T),
/// The source needs to be registered with the loop.
Register(T),
/// The source needs to be disabled but kept.
Disable(T),
/// The source needs to be removed from the loop.
Remove(T),
/// The source is being replaced by another. For most API purposes (eg.
/// `map()`), this will be treated as the `Register` state enclosing the new
/// source.
Replace {
/// The new source, which will be registered and used from now on.
new: T,
/// The old source, which will be unregistered and dropped.
old: T,
},
/// The source has been removed from the loop and dropped (this might also
/// be observed if there is a panic while changing states).
None,
}
impl<T> Default for TransientSourceState<T> {
fn default() -> Self {
Self::None
}
}
impl<T> TransientSourceState<T> {
/// If a caller needs to flag the contained source for removal or
/// registration, we need to replace the enum variant safely. This requires
/// having a `None` value in there temporarily while we do the swap.
///
/// If the variant is `None` the value will not change and `replacer` will
/// not be called. If the variant is `Replace` then `replacer` will be
/// called **on the new source**, which may cause the old source to leak
/// registration in the event loop if it has not yet been unregistered.
///
/// The `replacer` function here is expected to be one of the enum variant
/// constructors eg. `replace(TransientSource::Remove)`.
fn replace_state<F>(&mut self, replacer: F)
where
F: FnOnce(T) -> Self,
{
*self = match std::mem::take(self) {
Self::Keep(source)
| Self::Register(source)
| Self::Remove(source)
| Self::Disable(source)
| Self::Replace { new: source, .. } => replacer(source),
Self::None => return,
};
}
}
impl<T> TransientSource<T> {
/// Apply a function to the enclosed source, if it exists and is not about
/// to be removed.
pub fn map<F, U>(&mut self, f: F) -> Option<U>
where
F: FnOnce(&mut T) -> U,
{
match &mut self.state {
TransientSourceState::Keep(source)
| TransientSourceState::Register(source)
| TransientSourceState::Disable(source)
| TransientSourceState::Replace { new: source, .. } => Some(f(source)),
TransientSourceState::Remove(_) | TransientSourceState::None => None,
}
}
/// Returns `true` if there is no wrapped event source.
pub fn is_none(&self) -> bool {
matches!(self.state, TransientSourceState::None)
}
/// Removes the wrapped event source from the event loop and this wrapper.
///
/// If this is called from outside of the event loop, you will need to wake
/// up the event loop for any changes to take place. If it is called from
/// within the event loop, you must return `PostAction::Reregister` from
/// your own event source's `process_events()`, and the source will be
/// unregistered as needed after it exits.
pub fn remove(&mut self) {
self.state.replace_state(TransientSourceState::Remove);
}
/// Replace the currently wrapped source with the given one. No more events
/// will be generated from the old source after this point. The old source
/// will not be dropped immediately, it will be kept so that it can be
/// deregistered.
///
/// If this is called from outside of the event loop, you will need to wake
/// up the event loop for any changes to take place. If it is called from
/// within the event loop, you must return `PostAction::Reregister` from
/// your own event source's `process_events()`, and the sources will be
/// registered and unregistered as needed after it exits.
pub fn replace(&mut self, new: T) {
self.state
.replace_state(|old| TransientSourceState::Replace { new, old });
}
}
impl<T: crate::EventSource> From<T> for TransientSource<T> {
fn from(source: T) -> Self {
Self {
state: TransientSourceState::Register(source),
}
}
}
impl<T: crate::EventSource> crate::EventSource for TransientSource<T> {
type Event = T::Event;
type Metadata = T::Metadata;
type Ret = T::Ret;
type Error = T::Error;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
callback: F,
) -> Result<crate::PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let reregister = if let TransientSourceState::Keep(source) = &mut self.state {
let child_post_action = source.process_events(readiness, token, callback)?;
match child_post_action {
// Nothing needs to change.
crate::PostAction::Continue => false,
// Our child source needs re-registration, therefore this
// wrapper needs re-registration.
crate::PostAction::Reregister => true,
// If our nested source needs to be removed or disabled, we need
// to swap it out for the "Remove" or "Disable" variant.
crate::PostAction::Disable => {
self.state.replace_state(TransientSourceState::Disable);
true
}
crate::PostAction::Remove => {
self.state.replace_state(TransientSourceState::Remove);
true
}
}
} else {
false
};
let post_action = if reregister {
crate::PostAction::Reregister
} else {
crate::PostAction::Continue
};
Ok(post_action)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
match &mut self.state {
TransientSourceState::Keep(source) => {
source.register(poll, token_factory)?;
}
TransientSourceState::Register(source)
| TransientSourceState::Disable(source)
| TransientSourceState::Replace { new: source, .. } => {
source.register(poll, token_factory)?;
self.state.replace_state(TransientSourceState::Keep);
// Drops the disposed source in the Replace case.
}
TransientSourceState::Remove(_source) => {
self.state.replace_state(|_| TransientSourceState::None);
}
TransientSourceState::None => (),
}
Ok(())
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
match &mut self.state {
TransientSourceState::Keep(source) => source.reregister(poll, token_factory)?,
TransientSourceState::Register(source) => {
source.register(poll, token_factory)?;
self.state.replace_state(TransientSourceState::Keep);
}
TransientSourceState::Disable(source) => {
source.unregister(poll)?;
}
TransientSourceState::Remove(source) => {
source.unregister(poll)?;
self.state.replace_state(|_| TransientSourceState::None);
}
TransientSourceState::Replace { new, old } => {
old.unregister(poll)?;
new.register(poll, token_factory)?;
self.state.replace_state(TransientSourceState::Keep);
// Drops 'dispose'.
}
TransientSourceState::None => (),
}
Ok(())
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
match &mut self.state {
TransientSourceState::Keep(source)
| TransientSourceState::Register(source)
| TransientSourceState::Disable(source) => source.unregister(poll)?,
TransientSourceState::Remove(source) => {
source.unregister(poll)?;
self.state.replace_state(|_| TransientSourceState::None);
}
TransientSourceState::Replace { new, old } => {
old.unregister(poll)?;
new.unregister(poll)?;
self.state.replace_state(TransientSourceState::Register);
}
TransientSourceState::None => (),
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
channel::{channel, Channel, Event},
ping::{make_ping, PingSource},
Dispatcher, EventSource, PostAction,
};
use std::{
rc::Rc,
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
#[test]
fn test_transient_drop() {
// A test source that sets a flag when it's dropped.
struct TestSource<'a> {
dropped: &'a AtomicBool,
ping: PingSource,
}
impl<'a> Drop for TestSource<'a> {
fn drop(&mut self) {
self.dropped.store(true, Ordering::Relaxed)
}
}
impl<'a> crate::EventSource for TestSource<'a> {
type Event = ();
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
callback: F,
) -> Result<crate::PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
self.ping.process_events(readiness, token, callback)?;
Ok(PostAction::Remove)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.ping.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.ping.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.ping.unregister(poll)
}
}
// Test that the inner source is actually dropped when it asks to be
// removed from the loop, while the TransientSource remains. We use two
// flags for this:
// - fired: should be set only when the inner event source has an event
// - dropped: set by the drop handler for the inner source (it's an
// AtomicBool becaues it requires a longer lifetime than the fired
// flag)
let mut fired = false;
let dropped = false.into();
// The inner source that should be dropped after the first loop run.
let (pinger, ping) = make_ping().unwrap();
let inner = TestSource {
dropped: &dropped,
ping,
};
// The TransientSource wrapper.
let outer: TransientSource<_> = inner.into();
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let _token = handle
.insert_source(outer, |_, _, fired| {
*fired = true;
})
.unwrap();
// First loop run: the ping generates an event for the inner source.
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
assert!(fired);
assert!(dropped.load(Ordering::Relaxed));
// Second loop run: the ping does nothing because the receiver has been
// dropped.
fired = false;
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
assert!(!fired);
}
#[test]
fn test_transient_passthrough() {
// Test that event processing works when a source is nested inside a
// TransientSource. In particular, we want to ensure that the final
// event is received even if it corresponds to that same event source
// returning `PostAction::Remove`.
let (sender, receiver) = channel();
let outer: TransientSource<_> = receiver.into();
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
// Our callback puts the receied events in here for us to check later.
let mut msg_queue = vec![];
let _token = handle
.insert_source(outer, |msg, _, queue: &mut Vec<_>| {
queue.push(msg);
})
.unwrap();
// Send some data and drop the sender. We specifically want to test that
// we get the "closed" message.
sender.send(0u32).unwrap();
sender.send(1u32).unwrap();
sender.send(2u32).unwrap();
sender.send(3u32).unwrap();
drop(sender);
// Run loop once to process events.
event_loop.dispatch(Duration::ZERO, &mut msg_queue).unwrap();
assert!(matches!(
msg_queue.as_slice(),
&[
Event::Msg(0u32),
Event::Msg(1u32),
Event::Msg(2u32),
Event::Msg(3u32),
Event::Closed
]
));
}
#[test]
fn test_transient_map() {
struct IdSource {
id: u32,
ping: PingSource,
}
impl EventSource for IdSource {
type Event = u32;
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let id = self.id;
self.ping
.process_events(readiness, token, |_, md| callback(id, md))?;
let action = if self.id > 2 {
PostAction::Remove
} else {
PostAction::Continue
};
Ok(action)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.ping.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.ping.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.ping.unregister(poll)
}
}
struct WrapperSource(TransientSource<IdSource>);
impl EventSource for WrapperSource {
type Event = <IdSource as EventSource>::Event;
type Metadata = <IdSource as EventSource>::Metadata;
type Ret = <IdSource as EventSource>::Ret;
type Error = <IdSource as EventSource>::Error;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let action = self.0.process_events(readiness, token, callback);
self.0.map(|inner| inner.id += 1);
action
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.0.map(|inner| inner.id += 1);
self.0.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.0.map(|inner| inner.id += 1);
self.0.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.0.map(|inner| inner.id += 1);
self.0.unregister(poll)
}
}
// To test the id later.
let mut id = 0;
// Create our source.
let (pinger, ping) = make_ping().unwrap();
let inner = IdSource { id, ping };
// The TransientSource wrapper.
let outer: TransientSource<_> = inner.into();
// The top level source.
let top = WrapperSource(outer);
// Create a dispatcher so we can check the source afterwards.
let dispatcher = Dispatcher::new(top, |got_id, _, test_id| {
*test_id = got_id;
});
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let token = handle.register_dispatcher(dispatcher.clone()).unwrap();
// First loop run: the ping generates an event for the inner source.
// The ID should be 1 after the increment in register().
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
assert_eq!(id, 1);
// Second loop run: the ID should be 2 after the previous
// process_events().
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
assert_eq!(id, 2);
// Third loop run: the ID should be 3 after another process_events().
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
assert_eq!(id, 3);
// Fourth loop run: the callback is no longer called by the inner
// source, so our local ID is not incremented.
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut id).unwrap();
assert_eq!(id, 3);
// Remove the dispatcher so we can inspect the sources.
handle.remove(token);
let mut top_after = dispatcher.into_source_inner();
// I expect the inner source to be dropped, so the TransientSource
// variant is None (its version of None, not Option::None), so its map()
// won't call the passed-in function (hence the unreachable!()) and its
// return value should be Option::None.
assert!(top_after.0.map(|_| unreachable!()).is_none());
}
#[test]
fn test_transient_disable() {
// Test that disabling and enabling is handled properly.
struct DisablingSource(PingSource);
impl EventSource for DisablingSource {
type Event = ();
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
self.0.process_events(readiness, token, callback)?;
Ok(PostAction::Disable)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.0.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.0.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.0.unregister(poll)
}
}
// Flag for checking when the source fires.
let mut fired = false;
// Create our source.
let (pinger, ping) = make_ping().unwrap();
let inner = DisablingSource(ping);
// The TransientSource wrapper.
let outer: TransientSource<_> = inner.into();
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let token = handle
.insert_source(outer, |_, _, fired| {
*fired = true;
})
.unwrap();
// Ping here and not later, to check that disabling after an event is
// triggered but not processed does not discard the event.
pinger.ping();
event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
assert!(fired);
// Source should now be disabled.
pinger.ping();
fired = false;
event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
assert!(!fired);
// Re-enable the source.
handle.enable(&token).unwrap();
// Trigger another event.
pinger.ping();
fired = false;
event_loop.dispatch(Duration::ZERO, &mut fired).unwrap();
assert!(fired);
}
#[test]
fn test_transient_replace_unregister() {
// This is a bit of a complex test, but it essentially boils down to:
// how can a "parent" event source containing a TransientSource replace
// the "child" source without leaking the source's registration?
// First, a source that finishes immediately. This is so we cover the
// edge case of replacing a source as soon as it wants to be removed.
struct FinishImmediatelySource {
source: PingSource,
data: Option<i32>,
registered: bool,
dropped: Rc<AtomicBool>,
}
impl FinishImmediatelySource {
// The constructor passes out the drop flag so we can check that
// this source was or wasn't dropped.
fn new(source: PingSource, data: i32) -> (Self, Rc<AtomicBool>) {
let dropped = Rc::new(false.into());
(
Self {
source,
data: Some(data),
registered: false,
dropped: Rc::clone(&dropped),
},
dropped,
)
}
}
impl EventSource for FinishImmediatelySource {
type Event = i32;
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let mut data = self.data.take();
self.source.process_events(readiness, token, |_, _| {
if let Some(data) = data.take() {
callback(data, &mut ())
}
})?;
self.data = data;
Ok(if self.data.is_none() {
PostAction::Remove
} else {
PostAction::Continue
})
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.registered = true;
self.source.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.source.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.registered = false;
self.source.unregister(poll)
}
}
// The drop handler sets a flag we can check for debugging (we want to
// know that the source itself was dropped), and also checks that the
// source was unregistered. Ultimately neither the source nor its
// registration should be leaked.
impl Drop for FinishImmediatelySource {
fn drop(&mut self) {
assert!(!self.registered, "source dropped while still registered");
self.dropped.store(true, Ordering::Relaxed);
}
}
// Our wrapper source handles detecting when the child source finishes,
// and replacing that child source with another one that will generate
// more events. This is one intended use case of the TransientSource.
struct WrapperSource {
current: TransientSource<FinishImmediatelySource>,
replacement: Option<FinishImmediatelySource>,
dropped: Rc<AtomicBool>,
}
impl WrapperSource {
// The constructor passes out the drop flag so we can check that
// this source was or wasn't dropped.
fn new(
first: FinishImmediatelySource,
second: FinishImmediatelySource,
) -> (Self, Rc<AtomicBool>) {
let dropped = Rc::new(false.into());
(
Self {
current: first.into(),
replacement: second.into(),
dropped: Rc::clone(&dropped),
},
dropped,
)
}
}
impl EventSource for WrapperSource {
type Event = i32;
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
// Did our event source generate an event?
let mut fired = false;
let post_action = self.current.process_events(readiness, token, |data, _| {
callback(data, &mut ());
fired = true;
})?;
if fired {
// The event source will be unregistered after the current
// process_events() iteration is finished. The replace()
// method will handle doing that even while we've added a
// new source.
if let Some(replacement) = self.replacement.take() {
self.current.replace(replacement);
}
// Parent source is responsible for flagging this, but it's
// already set.
assert_eq!(post_action, PostAction::Reregister);
}
Ok(post_action)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.current.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.current.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.current.unregister(poll)
}
}
impl Drop for WrapperSource {
fn drop(&mut self) {
self.dropped.store(true, Ordering::Relaxed);
}
}
// Construct the various nested sources - FinishImmediatelySource inside
// TransientSource inside WrapperSource. The numbers let us verify which
// event source fires first.
let (ping0_tx, ping0_rx) = crate::ping::make_ping().unwrap();
let (ping1_tx, ping1_rx) = crate::ping::make_ping().unwrap();
let (inner0, inner0_dropped) = FinishImmediatelySource::new(ping0_rx, 0);
let (inner1, inner1_dropped) = FinishImmediatelySource::new(ping1_rx, 1);
let (outer, outer_dropped) = WrapperSource::new(inner0, inner1);
// Now the actual test starts.
let mut event_loop: crate::EventLoop<(Option<i32>, crate::LoopSignal)> =
crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
let signal = event_loop.get_signal();
// This is how we communicate with the event sources.
let mut context = (None, signal);
let _token = handle
.insert_source(outer, |data, _, (evt, sig)| {
*evt = Some(data);
sig.stop();
})
.unwrap();
// Ensure our sources fire.
ping0_tx.ping();
ping1_tx.ping();
// Use run() rather than dispatch() because it's not strictly part of
// any API contract as to how many runs of the event loop it takes to
// replace the nested source.
event_loop.run(None, &mut context, |_| {}).unwrap();
// First, make sure the inner source actually did fire.
assert_eq!(context.0.take(), Some(0), "first inner source did not fire");
// Make sure that the outer source is still alive.
assert!(
!outer_dropped.load(Ordering::Relaxed),
"outer source already dropped"
);
// Make sure that the inner child source IS dropped now.
assert!(
inner0_dropped.load(Ordering::Relaxed),
"first inner source not dropped"
);
// Make sure that, in between the first event and second event, the
// replacement child source still exists.
assert!(
!inner1_dropped.load(Ordering::Relaxed),
"replacement inner source dropped"
);
// Run the event loop until we get a second event.
event_loop.run(None, &mut context, |_| {}).unwrap();
// Ensure the replacement source fired (which checks that it was
// registered and is being processed by the TransientSource).
assert_eq!(context.0.take(), Some(1), "replacement source did not fire");
}
#[test]
fn test_transient_remove() {
// This tests that calling remove(), even before an event source has
// requested its own removal, results in the event source being removed.
const STOP_AT: i32 = 2;
// A wrapper source to automate the removal of the inner source.
struct WrapperSource {
inner: TransientSource<Channel<i32>>,
}
impl EventSource for WrapperSource {
type Event = i32;
type Metadata = ();
type Ret = ();
type Error = Box<dyn std::error::Error + Sync + Send>;
fn process_events<F>(
&mut self,
readiness: crate::Readiness,
token: crate::Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
{
let mut remove = false;
let mut post_action = self.inner.process_events(readiness, token, |evt, _| {
if let Event::Msg(num) = evt {
callback(num, &mut ());
remove = num >= STOP_AT;
}
})?;
if remove {
self.inner.remove();
post_action |= PostAction::Reregister;
}
Ok(post_action)
}
fn register(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.inner.register(poll, token_factory)
}
fn reregister(
&mut self,
poll: &mut crate::Poll,
token_factory: &mut crate::TokenFactory,
) -> crate::Result<()> {
self.inner.reregister(poll, token_factory)
}
fn unregister(&mut self, poll: &mut crate::Poll) -> crate::Result<()> {
self.inner.unregister(poll)
}
}
// Create our sources and loop.
let (sender, receiver) = channel();
let wrapper = WrapperSource {
inner: receiver.into(),
};
let mut event_loop = crate::EventLoop::try_new().unwrap();
let handle = event_loop.handle();
handle
.insert_source(wrapper, |num, _, out: &mut Option<_>| {
*out = Some(num);
})
.unwrap();
// Storage for callback data.
let mut out = None;
// Send some data we expect to get callbacks for.
for num in 0..=STOP_AT {
sender.send(num).unwrap();
event_loop.dispatch(Duration::ZERO, &mut out).unwrap();
assert_eq!(out.take(), Some(num));
}
// Now we expect the receiver to be gone.
assert!(matches!(
sender.send(STOP_AT + 1),
Err(std::sync::mpsc::SendError { .. })
));
}
}