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 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
//! # Instant channels. //! //! Just add water! ;) //! //! ## Creating channels //! There are a number of ways to create a channel in this module. The most //! straight forward is to use the function [txrx]. This will create a linked //! [Transmitter] + [Receiver] pair: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx): (Transmitter<()>, Receiver<()>) = txrx(); //! ``` //! //! Or maybe you prefer an alternative syntax: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx) = txrx::<()>(); //! ``` //! //! Or simply let the compiler try to figure it out: //! //! ```rust, ignore //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx) = txrx(); //! // ... //! ``` //! //! This pair makes a linked channel. Messages you send on the [Transmitter] //! will be sent directly to the [Receiver] on the other end. //! //! You can create separate terminals using the [trns] and [recv] functions. Then //! later in your code you can spawn new linked partners from them: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let mut tx = trns(); //! let rx = tx.spawn_recv(); //! tx.send(&()); // rx will receive the message //! ``` //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let rx = recv(); //! let tx = rx.new_trns(); //! tx.send(&()); // rx will receive the message //! ``` //! //! Note that [Transmitter::spawn_recv] mutates the transmitter its called on, //! while [Receiver::new_trns] requires no such mutation. //! //! ## Sending messages //! //! Once you have a txrx pair you can start sending messages: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx) = txrx(); //! tx.send(&()); //! tx.send(&()); //! tx.send(&()); //! ``` //! //! Notice that we send references. This is because neither the transmitter nor //! the receiver own the messages. //! //! It's also possible to send asynchronous messages! We can do this with //! [Transmitter::send_async], which takes a type that implements [Future]. //! Check out [Transmitter::send_async] to see an example of running an async //! web request to send some text from an `async` block. //! //! ## Responding to messages //! //! [Receiver]s can respond immediately to the messages that are sent to them. //! There is no polling and no internal message buffer. These channels are //! instant! Receivers do this by invoking their response function when they //! receive a message. The response function can be set using //! [Receiver::respond]: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx) = txrx(); //! rx.respond(|&()| { //! println!("Message received!"); //! }); //! tx.send(&()); //! ``` //! //! For convenience we also have the [Receiver::respond_shared] method and the //! [new_shared] function that together allow you to respond using a shared //! mutable variable. Inside your fold function you can simply mutate this shared //! variable as normal. This makes it easy to encapsulate a little bit of shared //! state in your responder without requiring much knowledge about thread-safe //! asynchronous programming: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let shared_count = new_shared(0); //! let (tx, rx) = txrx(); //! rx.respond_shared(shared_count.clone(), |count: &mut i32, &()| { //! *count += 1; //! println!("{} messages received!", *count); //! }); //! tx.send(&()); //! tx.send(&()); //! tx.send(&()); //! assert_eq!(*shared_count.borrow(), 3); //! ``` //! //! ## Composing channels //! //! Sending messages into a transmitter and having it pop out automatically is //! great, but wait, there's more! What if we have a `tx_a:Transmitter<A>` and a //! `rx_b:Receiver<B>`, but we want to send `A`s on `tx_a` and have `B`s pop out //! of `rx_b`? We could use the machinery we have and write something like: //! //! ```rust //! # extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx_a, rx_b) = { //! let (tx_a, rx_a) = txrx::<u32>(); //! let (tx_b, rx_b) = txrx::<String>(); //! let f = |a: &u32| { format!("{}", a) }; //! rx_a.respond(move |a| { //! tx_b.send(&f(a)); //! }); //! (tx_a, rx_b) //! }; //! ``` //! //! And indeed, it works! But that's an awful lot of boilerplate just to get a //! channel of `A`s to `B`s. Instead we can use the `txrx_map` function, which //! does all of this for us given the map function. Here's an example using //! a `Transmitter<()>` that sends to a `Receiver<i32>`: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! // For every unit that gets sent, map it to `1:i32`. //! let (tx_a, rx_b) = txrx_map(|&()| 1); //! let shared_count = new_shared(0); //! rx_b.respond_shared(shared_count.clone(), |count: &mut i32, n: &i32| { //! *count += n; //! println!("Current count is {}", *count); //! }); //! //! tx_a.send(&()); //! tx_a.send(&()); //! tx_a.send(&()); //! assert_eq!(*shared_count.borrow(), 3); //! ``` //! //! That is useful, but we can also do much more than simple maps! We can fold //! over an internal state or a shared state, we can filter some of the sent //! messages and we can do all those things together! Check out the `txrx_*` //! family of functions: //! //! * [txrx] //! * [txrx_filter_fold] //! * [txrx_filter_fold_shared] //! * [txrx_filter_map] //! * [txrx_fold] //! * [txrx_fold_shared] //! * [txrx_map] //! //! You'll also find functions with these flavors in [Transmitter] and //! [Receiver]. //! //! ## Wiring [Transmitter]s and forwading [Receiver]s //! //! Another way to get a txrx pair of different types is to create each side //! separately using [trns] and [recv] and then wire them together: //! //! ```rust //! # extern crate mogwai; //! use mogwai::prelude::*; //! //! let mut tx = trns::<()>(); //! let rx = recv::<i32>(); //! tx.wire_map(&rx, |&()| 1); //! ``` //! //! The following make up the `wire_*` family of functions on [Transmitter]: //! //! * [Transmitter::wire_filter_fold] //! * [Transmitter::wire_filter_fold_async] //! * [Transmitter::wire_filter_fold_shared] //! * [Transmitter::wire_filter_map] //! * [Transmitter::wire_fold] //! * [Transmitter::wire_fold_shared] //! * [Transmitter::wire_map] //! //! Conversely, if you would like to forward messages from a receiver into a //! transmitter of a different type you can "forward" messages from the receiver //! to the transmitter: //! //! ```rust //! # extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx) = txrx::<()>(); //! let (mut tx_i32, rx_i32) = txrx::<i32>(); //! rx.forward_map(&tx_i32, |&()| 1); //! //! let shared_got_it = new_shared(false); //! rx_i32.respond_shared(shared_got_it.clone(), |got_it: &mut bool, n: &i32| { //! println!("Got {}", *n); //! *got_it = true; //! }); //! //! tx.send(&()); //! assert_eq!(*shared_got_it.borrow(), true); //! ``` //! //! These make up the `forward_*` family of functions on [Receiver]: //! //! * [Receiver::forward_filter_fold] //! * [Receiver::forward_filter_fold_async] //! * [Receiver::forward_filter_fold_shared] //! * [Receiver::forward_filter_map] //! * [Receiver::forward_fold] //! * [Receiver::forward_fold_shared] //! * [Receiver::forward_map] //! //! Note that they all consume the [Receiver] they are called on. //! //! ## Cloning, branching, etc //! //! [Transmitter]s may be cloned. Once a transmitter is cloned a message sent on //! either the clone or the original will pop out on any linked receivers: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx1, rx) = txrx(); //! let tx2 = tx1.clone(); //! let shared_count = new_shared(0); //! rx.respond_shared(shared_count.clone(), |count: &mut i32, &()| { //! *count += 1; //! }); //! tx1.send(&()); //! tx2.send(&()); //! assert_eq!(*shared_count.borrow(), 2); //! ``` //! //! [Receiver]s are a bit different from [Transmitter]s, though. They are _not_ //! clonable because they house a responder, which must be unique. Instead we can //! use [Receiver::branch] to create a new receiver that is linked to the same //! transmitters as the original, but owns its own unique response to messages: //! //! ```rust //! extern crate mogwai; //! use mogwai::prelude::*; //! //! let (tx, rx1) = txrx(); //! let rx2 = rx1.branch(); //! let shared_count = new_shared(0); //! rx1.respond_shared(shared_count.clone(), |count: &mut i32, &()| { //! *count += 1; //! }); //! rx2.respond_shared(shared_count.clone(), |count: &mut i32, &()| { //! *count += 1; //! }); //! tx.send(&()); //! assert_eq!(*shared_count.borrow(), 2); //! ``` //! //! Both [Transmitter]s and [Receiver]s can be "branched" so that multiple //! transmitters may send to the same receiver and multiple receivers may respond //! to the same transmitter. These use the `contra_*` family of functions on //! [Transmitter] and the `branch_*` family of functions on [Receiver]. //! //! ### Transmitter's contra_* family //! //! This family of functions are named after Haskell's [contramap]. That's //! because these functions take a transmitter of `B`s, some flavor of function //! that transforms `B`s into `A`s and returns a new transmitter of `A`s. //! Essentially - the newly created transmitter extends the original _backward_, //! allowing you to send `A`s into it and have `B`s automatically sent on the //! original. //! //! * [Transmitter::contra_filter_fold] //! * [Transmitter::contra_filter_fold_shared] //! * [Transmitter::contra_filter_map] //! * [Transmitter::contra_fold] //! * [Transmitter::contra_map] //! //! ### Receiver's branch_* family //! //! This family of functions all extend new receivers off of an original and //! can transform messages of `A`s received on the original into messages of `B`s //! received on the newly created receiver. This is analogous to Haskell's //! [fmap]. //! //! * [Receiver::branch] //! * [Receiver::branch_filter_fold] //! * [Receiver::branch_filter_fold_shared] //! * [Receiver::branch_filter_map] //! * [Receiver::branch_fold] //! * [Receiver::branch_fold_shared] //! * [Receiver::branch_map] //! //! ### [Receiver::merge] //! //! If you have many receivers that you would like to merge you can use the //! [Receiver::merge] function. //! //! ## Done! //! //! The channels defined here are the backbone of this library. Getting to //! know the many constructors and combinators may seem like a daunting task but //! don't worry - the patterns of branching, mapping and folding are functional //! programming's bread and butter. Once you get a taste for this flavor of //! development you'll want more (and it will get easier). But remember, //! no matter how much it begs, no matter how much it cries, [NEVER feed Mogwai //! after midnight](https://youtu.be/OrHdo-v9mRA) ;) //! //! [contramap]: https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Contravariant.html#v:contramap //! [fmap]: https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor.html#v:fmap #[cfg(not(target_arch = "wasm32"))] use log::warn; use std::{ cell::{Cell, RefCell}, collections::HashMap, future::Future, pin::Pin, rc::Rc, task::{Context, Poll, Waker}, }; /// A pinned, possible future message. pub type RecvFuture<A> = Pin<Box<dyn Future<Output = Option<A>>>>; /// Wrap an optional future message in a pin box. pub fn wrap_future<A, F>(future: F) -> Option<RecvFuture<A>> where F: Future<Output = Option<A>> + 'static, { Some(Box::pin(future)) } struct Responders<A> { next_k: Cell<usize>, branches: RefCell<HashMap<usize, Box<dyn FnMut(&A)>>>, } impl<A> Default for Responders<A> { fn default() -> Self { Self { next_k: Cell::new(0), branches: Default::default(), } } } impl<A> Responders<A> { fn recv_from(self: Rc<Self>) -> Receiver<A> { let k = { let k = self.next_k.get(); self.next_k.set(k + 1); k }; Receiver { k, responders: self, } } fn insert(&self, k: usize, f: impl FnMut(&A) + 'static) { self.branches.borrow_mut().insert(k, Box::new(f)); } fn remove(&self, k: usize) { self.branches.borrow_mut().remove(&k); } fn send(&self, a: &A) { self.branches.borrow_mut().values_mut().for_each(|f| { f(a); }); } } /// Send messages instantly. pub struct Transmitter<A> { responders: Rc<Responders<A>>, } impl<A> Clone for Transmitter<A> { fn clone(&self) -> Self { Self { responders: self.responders.clone(), } } } impl<A: 'static> Transmitter<A> { /// Create a new transmitter. pub fn new() -> Transmitter<A> { Self { responders: Default::default(), } } /// Spawn a receiver for this transmitter. pub fn spawn_recv(&self) -> Receiver<A> { self.responders.clone().recv_from() } /// Send a message to any and all receivers of this transmitter. pub fn send(&self, a: &A) { self.responders.send(a); } /// Send a bunch of messages. pub fn send_many(&self, msgs: &[A]) { msgs .iter() .for_each(|msg| self.send(msg)); } /// Execute a future that results in a message, then send it. `wasm32` spawns /// a local execution context to drive the `Future` to completion. Outside of /// `wasm32` (e.g. during server-side rendering) this is a noop. /// /// ### Notes /// /// Does not exist outside of the wasm32 architecture because the /// functionality of [`wasm_bindgen_futures::spawn_local`] is largely /// managed by third party runtimes that mogwai does not need to depend /// upon. If `send_async` is necessary for server side rendering it may be /// better to modify the behavior so the [`Future`] resolves outside of the /// `Transmitter` lifecycle. /// /// ```rust, ignore /// extern crate mogwai; /// extern crate web_sys; /// use mogwai::prelude::*; /// use web_sys::{Request, RequestMode, RequestInit, Response}; /// /// // Here's our async function that fetches a text response from a server, /// // or returns an error string. /// async fn request_to_text(req:Request) -> Result<String, String> { /// let resp:Response = /// JsFuture::from( /// window() /// .fetch_with_request(&req) /// ) /// .await /// .map_err(|_| "request failed".to_string())? /// .dyn_into() /// .map_err(|_| "response is malformed")?; /// let text:String = /// JsFuture::from( /// resp /// .text() /// .map_err(|_| "could not get response text")? /// ) /// .await /// .map_err(|_| "getting text failed")? /// .as_string() /// .ok_or("couldn't get text as string".to_string())?; /// Ok(text) /// } /// /// let (tx, rx) = txrx(); /// tx.send_async(async { /// let mut opts = RequestInit::new(); /// opts.method("GET"); /// opts.mode(RequestMode::Cors); /// /// let req = /// Request::new_with_str_and_init( /// "https://worldtimeapi.org/api/timezone/Europe/London.txt", /// &opts /// ) /// .unwrap_throw(); /// /// request_to_text(req) /// .await /// .unwrap_or_else(|e| e) /// }); /// ``` #[cfg(not(target_arch = "wasm32"))] pub fn send_async<FutureA>(&self, fa: FutureA) where FutureA: Future<Output = A> + 'static { warn!("Transmitter::send_async is a noop on non-wasm32 targets"); let _ = fa;// noop } /// Placeholder docs to negate warnings. #[cfg(target_arch = "wasm32")] pub fn send_async<FutureA>(&self, fa: FutureA) where FutureA: Future<Output = A> + 'static, { let tx = self.clone(); wasm_bindgen_futures::spawn_local(async move { let a: A = fa.await; tx.send(&a); }); } /// Extend this transmitter with a new transmitter using a filtering fold /// function. The given function folds messages of `B` over a shared state `T` /// and optionally sends `A`s down into this transmitter. pub fn contra_filter_fold_shared<B, T, F>(&self, var: Rc<RefCell<T>>, f: F) -> Transmitter<B> where B: 'static, T: 'static, F: Fn(&mut T, &B) -> Option<A> + 'static, { let tx = self.clone(); let (tev, rev) = txrx(); rev.respond(move |ev| { let result = { let mut t = var.borrow_mut(); f(&mut t, ev) }; result.into_iter().for_each(|b| { tx.send(&b); }); }); tev } /// Extend this transmitter with a new transmitter using a filtering fold /// function. The given function folds messages of `B` over a state `T` and /// optionally sends `A`s into this transmitter. pub fn contra_filter_fold<B, X, T, F>(&self, init: X, f: F) -> Transmitter<B> where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &B) -> Option<A> + 'static, { let tx = self.clone(); let (tev, rev) = txrx(); let mut t = init.into(); rev.respond(move |ev| { f(&mut t, ev).into_iter().for_each(|b| { tx.send(&b); }); }); tev } /// Extend this transmitter with a new transmitter using a fold function. /// The given function folds messages of `B` into a state `T` and sends `A`s /// into this transmitter. pub fn contra_fold<B, X, T, F>(&self, init: X, f: F) -> Transmitter<B> where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &B) -> A + 'static, { self.contra_filter_fold(init, move |t, ev| Some(f(t, ev))) } /// Extend this transmitter with a new transmitter using a filter function. /// The given function maps messages of `B` and optionally sends `A`s into this /// transmitter. pub fn contra_filter_map<B, F>(&self, f: F) -> Transmitter<B> where B: 'static, F: Fn(&B) -> Option<A> + 'static, { self.contra_filter_fold((), move |&mut (), ev| f(ev)) } /// Extend this transmitter with a new transmitter using a map function. /// The given function maps messages of `B` into `A`s and sends them all into /// this transmitter. This is much like Haskell's /// [contramap](https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor-Contravariant.html#v:contramap), /// hence the `contra_` prefix on this family of methods. pub fn contra_map<B, F>(&self, f: F) -> Transmitter<B> where B: 'static, F: Fn(&B) -> A + 'static, { self.contra_filter_map(move |ev| Some(f(ev))) } /// Wires the transmitter to send to the given receiver using a stateful fold /// function, where the state is a shared mutex. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the receiver. pub fn wire_filter_fold_shared<T, B, F>(&self, rb: &Receiver<B>, var: Rc<RefCell<T>>, f: F) where B: 'static, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_filter_fold_shared(&tb, var, f); } /// Wires the transmitter to send to the given receiver using a stateful fold /// function. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the receiver. pub fn wire_filter_fold<T, B, X, F>(&self, rb: &Receiver<B>, init: X, f: F) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> Option<B> + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_filter_fold(&tb, init, f); } /// Wires the transmitter to send to the given receiver using a stateful fold /// function. pub fn wire_fold<T, B, X, F>(&self, rb: &Receiver<B>, init: X, f: F) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> B + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_fold(&tb, init, f); } /// Wires the transmitter to send to the given receiver using a stateful fold /// function, where the state is a shared mutex. pub fn wire_fold_shared<T, B, F>(&self, rb: &Receiver<B>, var: Rc<RefCell<T>>, f: F) where B: 'static, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_filter_fold_shared(&tb, var, move |t, a| Some(f(t, a))); } /// Wires the transmitter to the given receiver using a stateless map function. /// If the map function returns `None` for any messages those messages will /// *not* be sent to the given transmitter. pub fn wire_filter_map<B, F>(&self, rb: &Receiver<B>, f: F) where B: 'static, F: Fn(&A) -> Option<B> + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_filter_map(&tb, f); } /// Wires the transmitter to the given receiver using a stateless map function. pub fn wire_map<B, F>(&self, rb: &Receiver<B>, f: F) where B: 'static, F: Fn(&A) -> B + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_map(&tb, f); } /// Wires the transmitter to the given receiver using a stateful fold function /// that returns an optional future. The future, if available, results in an /// `Option<B>`. In the case that the value of the future's result is `None`, /// no message will be sent to the given receiver. /// /// Lastly, a clean up function is ran at the completion of the future with its /// result. /// /// To aid in returning a viable future in your fold function, use /// `wrap_future`. pub fn wire_filter_fold_async<T, B, X, F, H>(&self, rb: &Receiver<B>, init: X, f: F, h: H) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> Option<RecvFuture<B>> + 'static, H: Fn(&mut T, &Option<B>) + 'static, { let tb = rb.new_trns(); let ra = self.spawn_recv(); ra.forward_filter_fold_async(&tb, init, f, h); } } // A message received by a [`Receiver`] at some point in the future. struct MessageFuture<A> { var: Rc<RefCell<Option<A>>>, waker: Rc<RefCell<Option<Waker>>>, } impl<A> Future for MessageFuture<A> { type Output = A; fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> { let future: &mut MessageFuture<A> = self.get_mut(); let var: Option<A> = future.var.as_ref().borrow_mut().take(); match var { Some(msg) => Poll::Ready(msg), None => { *future.waker.borrow_mut() = Some(ctx.waker().clone()); Poll::Pending } } } } /// Receive messages instantly. pub struct Receiver<A> { k: usize, responders: Rc<Responders<A>>, } impl<A> Clone for Receiver<A> { fn clone(&self) -> Self { self.responders.clone().recv_from() } } impl<A> Receiver<A> { /// Create a new Receiver. pub fn new() -> Receiver<A> { Responders::recv_from(Default::default()) } /// Set the response this receiver has to messages. Upon receiving a message /// the response will run immediately. pub fn respond<F>(self, f: F) where F: FnMut(&A) + 'static, { self.responders.insert(self.k, f); } /// Set the response this receiver has to messages. Upon receiving a message /// the response will run immediately. /// /// Folds mutably over a Rc<RefCell<T>>. pub fn respond_shared<T: 'static, F>(self, val: Rc<RefCell<T>>, f: F) where F: Fn(&mut T, &A) + 'static, { self.responders.insert(self.k, move |a: &A| { let mut t = val.borrow_mut(); f(&mut t, a); }); } /// Removes the responder from the receiver. /// This drops anything owned by the responder. pub fn drop_responder(&self) { self.responders.remove(self.k); } /// Spawn a new [`Transmitter`] that sends to this Receiver. pub fn new_trns(&self) -> Transmitter<A> { Transmitter { responders: self.responders.clone(), } } /// Branch a receiver off of the original. /// Each branch will receive from the same transmitter. /// The new branch has no initial response to messages. pub fn branch(&self) -> Receiver<A> { self.responders.clone().recv_from() } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateful fold function. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the new receiver. /// /// Each branch will receive from the same transmitter. pub fn branch_filter_fold<B, X, T, F>(&self, init: X, f: F) -> Receiver<B> where B: 'static, X: Into<T>, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_filter_fold(&tb, init, f); rb } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateful fold function, where the state is a shared /// mutex. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the new receiver. /// /// Each branch will receive from the same transmitter. pub fn branch_filter_fold_shared<B, T, F>(&self, state: Rc<RefCell<T>>, f: F) -> Receiver<B> where B: 'static, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_filter_fold_shared(&tb, state, f); rb } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateful fold function. /// /// All output of the fold function is sent to the new receiver. /// /// Each branch will receive from the same transmitter(s). pub fn branch_fold<B, X, T, F>(&self, init: X, f: F) -> Receiver<B> where B: 'static, X: Into<T>, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_fold(&tb, init, f); rb } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateful fold function, where the state is a shared /// mutex. /// /// All output of the fold function is sent to the new receiver. /// /// Each branch will receive from the same transmitter(s). pub fn branch_fold_shared<B, T, F>(&self, t: Rc<RefCell<T>>, f: F) -> Receiver<B> where B: 'static, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_fold_shared(&tb, t, f); rb } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateless map function. /// /// The map function returns an `Option<B>`, representing an optional message /// to send to the new receiver. /// In the case that the result value of the map function is `None`, no message /// will be sent to the new receiver. /// /// Each branch will receive from the same transmitter. pub fn branch_filter_map<B, F>(&self, f: F) -> Receiver<B> where B: 'static, F: Fn(&A) -> Option<B> + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_filter_map(&tb, f); rb } /// Branch a new receiver off of an original and wire any messages sent to the /// original by using a stateless map function. /// /// All output of the map function is sent to the new receiver. /// /// Each branch will receive from the same transmitter. pub fn branch_map<B, F>(&self, f: F) -> Receiver<B> where B: 'static, F: Fn(&A) -> B + 'static, { let ra = self.branch(); let (tb, rb) = txrx(); ra.forward_map(&tb, f); rb } /// Forwards messages on the given receiver to the given transmitter using a /// stateful fold function, where the state is a shared mutex. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the transmitter. pub fn forward_filter_fold_shared<B, T, F>(self, tx: &Transmitter<B>, var: Rc<RefCell<T>>, f: F) where B: 'static, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let tx = tx.clone(); self.respond(move |a: &A| { let result = { let mut t = var.borrow_mut(); f(&mut t, a) }; result.into_iter().for_each(|b| { tx.send(&b); }); }); } /// Forwards messages on the given receiver to the given transmitter using a /// stateful fold function. /// /// The fold function returns an `Option<B>`. In the case that the value of /// `Option<B>` is `None`, no message will be sent to the transmitter. pub fn forward_filter_fold<B, X, T, F>(self, tx: &Transmitter<B>, init: X, f: F) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> Option<B> + 'static, { let var = Rc::new(RefCell::new(init.into())); self.forward_filter_fold_shared(tx, var, f); } /// Forwards messages on the given receiver to the given transmitter using a /// stateful fold function. All output of the fold /// function is sent to the given transmitter. pub fn forward_fold<B, X, T, F>(self, tx: &Transmitter<B>, init: X, f: F) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> B + 'static, { self.forward_filter_fold(tx, init, move |t: &mut T, a: &A| Some(f(t, a))) } /// Forwards messages on the given receiver to the given transmitter using a /// stateful fold function, where the state is a shared mutex. All output of /// the fold function is sent to the given transmitter. pub fn forward_fold_shared<B, T, F>(self, tx: &Transmitter<B>, t: Rc<RefCell<T>>, f: F) where B: 'static, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { self.forward_filter_fold_shared(tx, t, move |t: &mut T, a: &A| Some(f(t, a))) } /// Forwards messages on the given receiver to the given transmitter using a /// stateless map function. If the map function returns `None` for any messages /// those messages will *not* be sent to the given transmitter. pub fn forward_filter_map<B, F>(self, tx: &Transmitter<B>, f: F) where B: 'static, F: Fn(&A) -> Option<B> + 'static, { self.forward_filter_fold(tx, (), move |&mut (), a| f(a)) } /// Forwards messages on the given receiver to the given transmitter using a /// stateless map function. All output of the map function is sent to the given /// transmitter. pub fn forward_map<B, F>(self, tx: &Transmitter<B>, f: F) where B: 'static, F: Fn(&A) -> B + 'static, { self.forward_filter_map(tx, move |a| Some(f(a))) } /// Forwards messages on the given receiver to the given transmitter using a /// stateful fold function that returns an optional future. The future, if /// returned, is executed. The future results in an `Option<B>`. In the case /// that the value of the future's result is `None`, no message will be sent to /// the transmitter. /// /// Lastly, a clean up function is ran at the completion of the future with its /// result. /// /// To aid in returning a viable future in your fold function, use /// `wrap_future`. // TODO: Examples of fold functions. pub fn forward_filter_fold_async<T, B, X, F, H>(self, tb: &Transmitter<B>, init: X, f: F, h: H) where B: 'static, T: 'static, X: Into<T>, F: Fn(&mut T, &A) -> Option<RecvFuture<B>> + 'static, H: Fn(&mut T, &Option<B>) + 'static, { let state = Rc::new(RefCell::new(init.into())); let cleanup = Rc::new(Box::new(h)); let tb = tb.clone(); self.respond(move |a: &A| { let may_async = { let mut block_state = state.borrow_mut(); f(&mut block_state, a) }; may_async.into_iter().for_each(|block: RecvFuture<B>| { let tb_clone = tb.clone(); let state_clone = state.clone(); let cleanup_clone = cleanup.clone(); let future = async move { let opt: Option<B> = block.await; opt.iter().for_each(|b| tb_clone.send(&b)); let mut inner_state = state_clone.borrow_mut(); cleanup_clone(&mut inner_state, &opt); }; wasm_bindgen_futures::spawn_local(future); }); }); } /// Merge all the receivers into one. Any time a message is received on any /// receiver, it will be sent to the returned receiver. pub fn merge<B: 'static>(rxs: Vec<Receiver<B>>) -> Receiver<B> { let (tx, rx) = txrx(); rxs.into_iter().for_each(|rx_inc| { let tx = tx.clone(); rx_inc.branch().respond(move |a| { tx.send(a); }); }); rx } /// Create a future to await the next message received by this `Receiver`. pub fn message(&self) -> impl Future<Output = A> where A: Clone + 'static, { let var: Rc<RefCell<Option<A>>> = Rc::new(RefCell::new(None)); let var2: Rc<RefCell<Option<A>>> = var.clone(); let waker: Rc<RefCell<Option<Waker>>> = Rc::new(RefCell::new(None)); let waker2 = waker.clone(); self.branch().respond(move |msg| { *var2.borrow_mut() = Some(msg.clone()); waker2 .borrow_mut() .take() .into_iter() .for_each(|waker| waker.wake()); }); MessageFuture { var, waker } } } /// Create a new unlinked `Receiver<T>`. pub fn recv<A>() -> Receiver<A> { Receiver::new() } /// Create a new unlinked `Transmitter<T>`. pub fn trns<A: 'static>() -> Transmitter<A> { Transmitter::new() } /// Create a linked `Transmitter<A>` and `Receiver<A>` pair. pub fn txrx<A: 'static>() -> (Transmitter<A>, Receiver<A>) { let trns = Transmitter::new(); let recv = trns.spawn_recv(); (trns, recv) } /// Create a linked, filtering `Transmitter<A>` and `Receiver<B>` pair with /// internal state. /// /// Using the given filtering fold function, messages sent on the transmitter /// will be folded into the given internal state and output messages may or may /// not be sent to the receiver. /// /// In the case that the return value of the given function is `None`, no message /// will be sent to the receiver. pub fn txrx_filter_fold<A, B, T, F>(t: T, f: F) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_filter_fold(&tb, t, f); (ta, rb) } /// Create a linked, filtering `Transmitter<A>` and `Receiver<B>` pair with /// shared state. /// /// Using the given filtering fold function, messages sent on the transmitter /// will be folded into the given shared state and output messages may or may /// not be sent to the receiver. /// /// In the case that the return value of the given function is `None`, no message /// will be sent to the receiver. pub fn txrx_filter_fold_shared<A, B, T, F>( var: Rc<RefCell<T>>, f: F, ) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, T: 'static, F: Fn(&mut T, &A) -> Option<B> + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_filter_fold_shared(&tb, var, f); (ta, rb) } /// Create a linked `Transmitter<A>` and `Receiver<B>` pair with internal state. /// /// Using the given fold function, messages sent on the transmitter will be /// folded into the given internal state and all output messages will be sent to /// the receiver. pub fn txrx_fold<A, B, T, F>(t: T, f: F) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_fold(&tb, t, f); (ta, rb) } /// Create a linked `Transmitter<A>` and `Receiver<B>` pair with shared state. /// /// Using the given fold function, messages sent on the transmitter are folded /// into the given internal state and all output messages will be sent to the /// receiver. pub fn txrx_fold_shared<A, B, T, F>(t: Rc<RefCell<T>>, f: F) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, T: 'static, F: Fn(&mut T, &A) -> B + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_fold_shared(&tb, t, f); (ta, rb) } /// Create a linked, filtering `Transmitter<A>` and `Receiver<B>` pair. /// /// Using the given filtering map function, messages sent on the transmitter /// are mapped to output messages that may or may not be sent to the receiver. /// /// In the case that the return value of the given function is `None`, no message /// will be sent to the receiver. pub fn txrx_filter_map<A, B, F>(f: F) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, F: Fn(&A) -> Option<B> + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_filter_map(&tb, f); (ta, rb) } /// Create a linked `Transmitter<A>` and `Receiver<B>` pair. /// /// Using the given map function, messages sent on the transmitter are mapped /// to output messages that will be sent to the receiver. pub fn txrx_map<A, B, F>(f: F) -> (Transmitter<A>, Receiver<B>) where A: 'static, B: 'static, F: Fn(&A) -> B + 'static, { let (ta, ra) = txrx(); let (tb, rb) = txrx(); ra.forward_map(&tb, f); (ta, rb) } /// Helper for making thread-safe shared mutable variables. /// /// Use this as a short hand for creating variables to pass to /// the many `*_shared` flavored fold functions in the [txrx](index.html) /// module. pub fn new_shared<A: 'static, X: Into<A>>(init: X) -> Rc<RefCell<A>> { Rc::new(RefCell::new(init.into())) } #[cfg(test)] mod range { #[test] fn range() { let mut n = 0; for i in 0..3 { n = i; } assert_eq!(n, 2); } } #[cfg(test)] mod instant_txrx { use super::*; #[test] fn txrx_test() { let count = Rc::new(RefCell::new(0)); let (tx_unit, rx_unit) = txrx::<()>(); let (tx_i32, rx_i32) = txrx::<i32>(); { let my_count = count.clone(); rx_i32.respond(move |n: &i32| { println!("Got message: {:?}", n); let mut c = my_count.borrow_mut(); *c = *n; }); let mut n = 0; rx_unit.respond(move |()| { n += 1; tx_i32.send(&n); }) } tx_unit.send(&()); tx_unit.send(&()); tx_unit.send(&()); let final_count: i32 = *count.borrow(); assert_eq!(final_count, 3); } #[test] fn wire_txrx() { let tx_unit = Transmitter::<()>::new(); let rx_str = Receiver::<String>::new(); tx_unit.wire_filter_fold(&rx_str, 0, |n: &mut i32, &()| -> Option<String> { *n += 1; if *n > 2 { Some(format!("Passed 3 incoming messages ({})", *n)) } else { None } }); let got_called = Rc::new(RefCell::new(false)); let remote_got_called = got_called.clone(); rx_str.respond(move |s: &String| { println!("got: {:?}", s); let mut called = remote_got_called.borrow_mut(); *called = true; }); tx_unit.send(&()); tx_unit.send(&()); tx_unit.send(&()); let ever_called = *got_called.borrow(); assert!(ever_called); } #[test] fn branch_map() { let (tx, rx) = txrx::<()>(); let ry: Receiver<i32> = rx.branch_map(|_| 0); let done = Rc::new(RefCell::new(false)); let cdone = done.clone(); ry.respond(move |n| { if *n == 0 { *cdone.borrow_mut() = true; } }); tx.send(&()); assert!(*done.borrow()); } }