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
//! # `join!` //! //! **Macros** which provide useful shortcut combinators, combine sync/async chains, support single and multi thread (sync/async) step by step execution of branches, transform tuple of results in result of tuple. //! //! - `join!` macros will just return final values. Use it if you are working with iterators/streams etc. //! - `try_join!` macros will transpose tuple of `Option`s/`Result`s in `Option`/`Result` of tuple. Use it when you are dealing with results or options. If one of branches produces `None`/`Err` at the end of step , next steps execution will be aborted. In case of `async` macro you can only provide `Result`s because `::futures::try_join` doesn't support `Option`s. //! //! [![Docs][docs-badge]][docs-url] //! [![Crates.io][crates-badge]][crates-url] //! [![MIT licensed][mit-badge]][mit-url] //! [![Build Status][travis-badge]][travis-url] //! //! [docs-badge]: https://docs.rs/join/badge.svg //! [docs-url]: https://docs.rs/join //! [crates-badge]: https://img.shields.io/crates/v/join.svg //! [crates-url]: https://crates.io/crates/join //! [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg //! [mit-url]: LICENSE //! [travis-badge]: https://travis-ci.org/olegnn/join.svg?branch=master //! [travis-url]: https://travis-ci.org/olegnn/join //! //! - [Macros](#macros) //! - [Combinators](#combinators) //! - [Nested combinators](#nested-combinators) //! - [Handler](#handler) //! - [Let pattern](#let-pattern) //! - [Block captures](#block-captures) //! - [Demos](#demos) //! - [Single thread examples](#single-thread-combinations) //! - [Sync](#sync-branches) //! - [Async](#futures) //! - [Multi thread examples](#multi-thread-combinations) //! - [Sync](#sync-threads) //! - [Async](#future-tasks) //! - [Detailed steps example](#detailed-steps-example) //! //! ## Macros //! //! - [`try_join!`](macro.join.html) - combines results/options, transposes tuple of results/options in result/option of tuple. //! ```rust //! # use join::*; //! # fn main() { //! assert_eq!(try_join!(Ok::<_,u8>(1), Ok::<_,u8>("2"), Ok::<_,u8>(3.0)), Ok::<_,u8>((1, "2", 3.0))); //! # } //! ``` //! - [`try_join_async!`](macro.try_join_async.html) - combines futures, transposes tuple of results in result of tuple. //! ```rust //! # use join::*; //! # use futures::future::*; //! # #[tokio::main] //! # async fn main() { //! assert_eq!(try_join_async!(ok::<_,u8>(1), ok::<_,u8>("2"), ok::<_,u8>(3.0)).await, Ok::<_,u8>((1, "2", 3.0))); //! # } //! ``` //! - [`try_join_spawn!`](macro.try_join_spawn.html) - spawns [`std::thread`](https://doc.rust-lang.org/std/thread/) per each branch and joins results, transposes tuple of results in result of tuple. //! ```rust //! # use join::*; //! # fn main() { //! assert_eq!(try_join_spawn!(Ok::<_,u8>(1), Ok::<_,u8>("2"), Ok::<_,u8>(3.0)), Ok::<_,u8>((1, "2", 3.0))); //! # } //! ``` //! - [`try_spawn!`](macro.try_spawn.html) - alias for [`try_join_spawn!`](macro.try_join_spawn.html). //! - [`try_join_async_spawn!`](macro.try_join_async_spawn.html) - spawns futures into default `tokio` executor using [`::tokio::spawn`](https://docs.rs/tokio/0.2.0-alpha.6/tokio/fn.spawn.html) per each branch, transposes tuple of results in result of tuple. //! ```rust //! # use join::*; //! # use futures::future::*; //! # #[tokio::main] //! # async fn main() { //! assert_eq!(try_join_async_spawn!(ok::<_,u8>(1), ok::<_,u8>("2"), ok::<_,u8>(3.0)).await, Ok::<_,u8>((1, "2", 3.0))); //! # } //! ``` //! - [`try_async_spawn!`](macro.try_async_spawn.html) - alias for [`try_join_async_spawn!`](macro.try_join_async_spawn.html). //! - [`join!`](macro.join.html) - combines values. //! ```rust //! # use join::*; //! # fn main() { //! assert_eq!(join!(1, "2", 3.0), (1, "2", 3.0)); //! # } //! ``` //! - [`join_async!`](macro.join_async.html) - combines futures. //! ```rust //! # use join::*; //! # use futures::future::*; //! # #[tokio::main] //! # async fn main() { //! assert_eq!(join_async!(ready(1), ready("2"), ready(3.0)).await, (1, "2", 3.0)); //! # } //! ``` //! - [`join_spawn!`](macro.join_spawn.html) - spawns [`std::thread`](https://doc.rust-lang.org/std/thread/) per each branch. //! ```rust //! # use join::*; //! # fn main() { //! assert_eq!(join_spawn!(1, "2", 3.0), (1, "2", 3.0)); //! # } //! ``` //! - [`spawn!`](macro.spawn.html) - alias for [`join_spawn!`](macro.join_spawn.html). //! - [`join_async_spawn!`](macro.join_async_spawn.html) - spawns futures into default `tokio` executor using [`::tokio::spawn`](https://docs.rs/tokio/0.2.0-alpha.6/tokio/fn.spawn.html) per each branch. //! ```rust //! # use join::*; //! # use futures::future::*; //! # #[tokio::main] //! # async fn main() { //! assert_eq!(join_async_spawn!(ready(1), ready("2"), ready(3.0)).await, (1, "2", 3.0)); //! # } //! ``` //! - [`async_spawn!`](macro.async_spawn.html) - alias for [`join_async_spawn!`](macro.join_async_spawn.html). //! //! ## Combinators //! //! - Map: **`|>`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! # let expr = |v| v; //! try_join! { value |> expr }; // => value.map(expr) //! # } //! ``` //! //! - AndThen: **`=>`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! # let expr = |v| Some(v + 1); //! # let result = //! try_join! { value => expr }; // => value.and_then(expr) //! # assert_eq!(result, Some(2)); //! # } //! ``` //! //! - Then: **`->`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! # let expr = |v: Option<u8>| Some(v.unwrap() + 1); //! # let result = //! try_join! { value -> expr }; // => expr(value) //! # assert_eq!(result, Some(2)); //! # } //! ``` //! //! - Filter: **`?>`** //! ```rust //! # use join::join; //! # fn expr(v: &u8) -> bool { *v == 3 } //! # fn main() { //! # let value = vec![1u8, 2, 3].into_iter(); //! # let result = //! join! { value ?> expr }; // => value.filter(expr) //! # assert_eq!(result.collect::<Vec<_>>(), vec![3]); //! # } //! ``` //! //! - Dot: **`..`** or **`>.`** //! ```rust //! # use join::join; //! # fn main() { //! # let value = Some(1u8); //! # let result = //! join! { value .. is_some() }; // => value.is_some() //! # assert_eq!(result, true); //! # let result = //! join! { value >. is_none() }; // => value.is_none() //! # assert_eq!(result, false); //! # } //! ``` //! //! - Or: **`<|`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! # let expr = Some(2u8); //! # let result = //! try_join! { value <| expr }; // => value.or(expr) //! # assert_eq!(result, Some(1)); //! # } //! ``` //! //! - OrElse: **`<=`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = None; //! # let expr = || Some(6); //! # let result = //! try_join! { value <= expr }; // => value.or_else(expr) //! # assert_eq!(result, Some(6)); //! # } //! ``` //! //! - MapErr: **`!>`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Err::<u8,_>(1u8); //! # let expr = |err| err + 1; //! # let result = //! try_join! { value !> expr }; // => value.map_err(expr) //! # assert_eq!(result, Err(2)); //! # } //! ``` //! //! - Collect: **`=>[]`** (type is optional) //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![1u8, 2, 3].into_iter(); //! # let result = //! join! { value =>[] Vec<_> }; // => value.collect::<Vec<_>>() //! # assert_eq!(result, vec![1u8, 2, 3]); //! # let value = vec![1u8, 3, 4].into_iter(); //! let result: Vec<_> = join! { value =>[] }; // => value.collect() //! # assert_eq!(result, vec![1u8, 3, 4]); //! # } //! ``` //! //! - Chain: **`>@>`** //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![1u8].into_iter(); //! # let expr = vec![1u8].into_iter(); //! # let result = //! join! { value >@> expr }; // => value.chain(expr) //! # assert_eq!(result.collect::<Vec<_>>(), vec![1, 1]); //! # } //! ``` //! //! - FindMap: **`?|>@`** //! ```rust //! # use join::join; //! # fn main() { //! # let mut value = vec![1u8, 2, 3, 4].into_iter(); //! # let expr = |v| if v == 4 { Some(v) } else { None }; //! # let result = //! join! { value ?|>@ expr }; // => value.find_map(expr) //! # assert_eq!(result, Some(4)); //! # } //! ``` //! //! - FilterMap: **`?|>`** //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![1u8, 2, 3, 4, 5].into_iter(); //! # let expr = |v| Some(v); //! # let result = //! join! { value ?|> expr }; // => value.filter_map(expr) //! # assert_eq!(result.collect::<Vec<_>>(), vec![1u8, 2, 3, 4, 5]); //! # } //! ``` //! //! - Enumerate: **`|n>`** //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![1u8].into_iter(); //! # let result = //! join! { value |n> }; // => value.enumerate() //! # assert_eq!(result.collect::<Vec<_>>(), vec![(0usize, 1u8)]); //! # } //! ``` //! //! - Partition: **`?&!>`** //! ```rust //! # use join::join; //! # fn filter<'a>(v: &'a u8) -> bool { v % 2 == 0 } //! # fn main() { //! # let mut value = vec![1u8, 2, 3, 4, 5].into_iter(); //! # let expr = filter; //! # let result = //! join! { value ?&!> expr }; // => value.partition(expr) //! # assert_eq!(result, (vec![2, 4], vec![1, 3, 5])); //! # } //! ``` //! //! - Flatten: **`^^>`** //! ```rust //! # use join::join; //! # fn main() { //! # let mut value = vec![vec![1u8]].into_iter(); //! # let result = //! join! { value ^^> }; // => value.flatten() //! # assert_eq!(result.collect::<Vec<_>>(), vec![1u8]); //! # } //! ``` //! //! - Fold: **`^@`** //! ```rust //! # use join::join; //! # fn main() { //! # let mut value = vec![1u8, 2u8].into_iter(); //! # let init_expr = 0; //! # let fn_expr = |a, b| a + b; //! # let result = //! join! { value ^@ init_expr, fn_expr }; // => value.fold(init_expr, fn_expr) //! # assert_eq!(result, 3); //! # } //! ``` //! //! - TryFold: **`?^@`** //! ```rust //! # use join::join; //! # fn main() { //! # let mut value = vec![1u8, 2u8].into_iter(); //! # let init_expr = 0; //! # let fn_expr = |a, b| Ok::<_,u8>(a + b); //! # let result = //! join! { value ?^@ init_expr, fn_expr }; // => value.try_fold(init_expr, fn_expr) //! # assert_eq!(result, Ok(3)); //! # } //! ``` //! //! - Find: **`?@`** //! ```rust //! # use join::try_join; //! # fn filter(v: &u8) -> bool { true } //! # fn main() { //! # let mut value = vec![1u8, 2u8].into_iter(); //! # let expr = filter; //! # let result = //! try_join! { value ?@ expr }; // => value.find(expr) //! # assert_eq!(result, Some(1)); //! # } //! ``` //! //! - Zip: **`>^>`** //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![1u8, 2u8].into_iter(); //! # let expr = vec![1u8, 2u8].into_iter(); //! # let result = //! join! { value >^> expr }; // => value.zip(expr) //! # assert_eq!(result.collect::<Vec<_>>(), vec![(1, 1), (2, 2)]); //! # } //! ``` //! //! - Unzip: **`<->`** (types are optional) //! ```rust //! # use join::join; //! # fn main() { //! # let value = vec![(1u8, 2u8)].into_iter(); //! # let result = //! join! { value <-> _, _, Vec<_>, Vec<_> }; // => value.unzip::<_, _, Vec<_>, Vec<_>>() //! # assert_eq!(result, (vec![1], vec![2])); //! # let value = vec![(1u8, 2u8)].into_iter(); //! let result: (Vec<_>, Vec<_>) = join! { value <-> }; // => value.unzip() //! # assert_eq!(result, (vec![1], vec![2])); //! # } //! ``` //! - Inspect: **`??`** //! ```rust //! # use join::{try_join, try_join_async}; //! # use futures::executor::block_on; //! # fn expr<T: std::fmt::Debug>(v: &T) { println!("{:?}", v); } //! # fn main() { //! # let value = Ok::<_,u8>(1u8); //! # let result = //! try_join! { value ?? expr }; // => (|value| { (expr)(&value); value })(value) // for sync //! # assert_eq!(result, Ok::<_,u8>(1u8)); //! # let value = ::futures::future::ok::<_,u8>(1u8); //! # let result = //! try_join_async! { value ?? expr }; // => value.inspect(expr) for async //! # block_on(async { assert_eq!(result.await, Ok::<_,u8>(1u8)); }); //! # } //! ``` //! //! where `value` is the previous value. //! //! **Every combinator prefixed by `~` will act as deferred action (all actions will wait until completion in every step and only after move to the next one).** //! //! ## Nested combinators //! //! - Wrap: `combinator` **`>>>`** `combinator`(s)... //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(Some(5)); //! # let result = //! try_join! { value => >>> |> |v| v + 2 }; // => value.and_then(|value| value.map(|v| v + 2)) //! # assert_eq!(result, Some(7)); //! # } //! ``` //! Use to create nested constructions like //! ```rust //! # fn main() { //! # let a = Ok::<_,u8>(Ok::<_,u8>(Ok::<_,u8>(4))); //! # let value = //! a.and_then( //! // >>> //! |b| b.and_then( //! // >>> //! |c| c.and_then( //! |v| Ok(v + 2) //! ) //! ) //! ) //! # ; //! # assert_eq!(value, Ok(6)); //! # } //! ``` //! //! - Unwrap: **`<<<`** //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(Some(5)); //! # let result = //! try_join! { //! value //! => >>> //! |> |v| v + 2 //! <<< //! |> |v| Some(v + 4) //! }; // => value.and_then(|value| value.map(|v| v + 2)).map(|v| Some(v + 4)) //! # assert_eq!(result, Some(Some(11))); //! # } //! ``` //! Use to move out of nested constructions //! ```rust //! # fn main() { //! # let a = Ok::<_,u8>(Ok::<_,u8>(Ok::<_,u8>(4))); //! # let value = //! a.and_then( //! // >>> //! |b| b.and_then( //! // >>> //! |c| c.and_then( //! |v| Ok(v + 2) //! ) //! // <<< //! ) //! // <<< //! ).map( //! |v| v + 1 //! ) //! # ; //! # assert_eq!(value, Ok(7)); //! # } //! ``` //! //! //! ## Handler //! //! //! might be one of //! //! - `map` => **Only valid for `try` macros.** Will act as `results.map(|(result0, result1, ..)| handler(result0, result1, ..))` //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! assert_eq!(try_join! { Some(1), Some(2), Some(3), map => |a, b, c| a + b + c }, Some(6)); //! # } //! ``` //! - `and_then` => **Only valid for `try` macros.** Will act as `results.and_then(|(result0, result1, ..)| handler(result0, result1, ..))` //! ```rust //! # use join::try_join; //! # fn main() { //! # let value = Some(1u8); //! assert_eq!(try_join! { Some(1), Some(2), Some(3), and_then => |a, b, c| Some(a + b + c) }, Some(6)); //! # } //! ``` //! - `then` => **Only valid for not `try` macros.** Will be executed in any case, act as `handler(result0, result1, ..)` //! ```rust //! # use join::join; //! # fn main() { //! assert_eq!(join! { Some(1), Some(2), Some(3), then => |a: Option<u8>, b: Option<u8>, c: Option<u8>| Some(a.unwrap() + b.unwrap() + c.unwrap()) }, Some(6)); //! # } //! ``` //! or not specified - then `Result<(result0, result1, ..), Error>` or `Option<(result0, result1, ..)>` will be returned. //! //! ## Custom futures crate path //! //! You can specify custom path (`futures_crate_path`) at the beginning of macro call //! //! ```rust //! use join::try_join_async; //! use futures::future::ok; //! //! #[tokio::main] //! async fn main() { //! let value = try_join_async! { //! futures_crate_path(::futures) //! ok::<_,u8>(2u16) //! }.await.unwrap(); //! //! println!("{}", value); //! } //! ``` //! //! ## Let pattern //! //! You can specify `let` pattern for each branch in order to share result with other branches, or in case if you need to have `mut` value between steps. //! //! ```rust //! # use join::*; //! # fn main() { //! assert_eq!(try_join! { //! let mut branch_0 = Ok::<_,u8>(1) ~|> |v| v + 1, //! let branch_1 = Ok::<_,u8>(2) ~|> { let value_0 = branch_0.as_ref().unwrap(); move |v| v + value_0 }, //! map => |b_0, b_1| b_0 * b_1 //! }.unwrap(), 6); //! # } //! ``` //! //! ## Block captures //! //! In order to capture variables (for ex. values of other branches in example above) you can pass block statements instead of functions: //! ```rust //! # use join::*; //! # fn main() { //! let mut some_value = Some("capture me"); //! assert_eq!(try_join! { //! Some(0) |> |v| { //! // assign `None` to some_value in step expr //! some_value = None; //! v //! } |> { //! // capture value before step and get str len //! let captured_len = some_value.as_ref().unwrap().len(); //! move |v| v + captured_len //! } //! }.unwrap(), 10); //! # } //! ``` //! These blocks will be placed before actual step expressions. //! //! ## Demos //! //! Using this macro you can write things like //! //! ```rust //! #![recursion_limit = "256"] //! //! use rand::prelude::*; //! use std::sync::Arc; //! use join::try_join_spawn; //! //! // Problem: generate vecs filled by random numbers in parallel, make some operations on them in parallel, //! // find max of each vec in parallel and find final max of 3 vecs //! //! // Solution: //! fn main() { //! // Branches will be executed in parallel, each in its own thread //! let max = try_join_spawn! { //! let branch_0 = //! generate_random_vec(1000, 10000000u64) //! .into_iter() //! // Multiply every element by itself //! |> power2 //! // Filter even values //! ?> is_even //! // Collect values into `Vec<_>` //! =>[] Vec<_> //! // Use `Arc` to share data with branch 1 //! -> Arc::new -> Some //! // Find max and clone its value //! ~=> >>> ..iter().max() |> Clone::clone, //! generate_random_vec(10000, 100000000000000f64) //! .into_iter() //! // Extract sqrt from every element //! |> get_sqrt //! -> Some //! ~=> >>> // Add index in order to compare with the values of branch_0 (call `enumerate`) //! |n> //! |> { //! // Get data from branch 0 by cloning arc //! let branch_0 = branch_0.as_ref().unwrap().clone(); //! let len = branch_0.len(); //! // Compare every element of branch 1 with element of branch_0 //! // with the same index and take min //! move |(index, value)| //! if index < len && value as u64 > branch_0[index] { //! branch_0[index] //! } else { //! value as u64 //! } //! }..max(), //! generate_random_vec(100000, 100000u32) //! .into_iter() //! -> Some //! ~=> >>> ..max(), //! and_then => |max0, max1, max2| //! // Find final max //! [max0, max1, max2 as u64].iter().max().map(Clone::clone) //! } //! .unwrap(); //! println!("Max: {}", max); //! } //! //! fn generate_random_vec<T>(size: usize, max: T) -> Vec<T> //! where //! T: From<u8> //! + rand::distributions::uniform::SampleUniform //! + rand::distributions::uniform::SampleBorrow<T> //! + Copy, //! { //! let mut rng = rand::thread_rng(); //! (0..size) //! .map(|_| rng.gen_range(T::from(0u8), max)) //! .collect() //! } //! //! fn is_even<T>(value: &T) -> bool //! where //! T: std::ops::Rem<Output = T> + std::cmp::PartialEq + From<u8> + Copy //! { //! *value % 2u8.into() == 0u8.into() //! } //! //! fn get_sqrt<T>(value: T) -> T //! where //! T: Into<f64>, //! f64: Into<T>, //! { //! let value_f64: f64 = value.into(); //! value_f64.sqrt().into() //! } //! //! fn power2<T>(value: T) -> T //! where //! T: std::ops::Mul<Output = T> + Copy, //! { //! value * value //! } //! ``` //! //! And like this //! //! ```rust no_run //! #![recursion_limit="1024"] //! //! use join::try_join_async; //! use futures::stream::{iter, Stream}; //! use reqwest::Client; //! use futures::future::{try_join_all, ok, ready}; //! use failure::{format_err, Error}; //! //! #[tokio::main] //! async fn main() { //! println!( //! "{} {}\n{}", //! "Hello.\nThis's is the game where winner is player, which number is closest to", //! "the max count of links (starting with `https://`) found on one of random pages.", //! "You play against random generator (0-500)." //! ); //! //! enum GameResult { //! Won, //! Lost, //! Draw //! } //! //! let client = Client::new(); //! //! let game = try_join_async! { //! // Make requests to several sites //! // and calculate count of links starting from `https://` //! get_urls_to_calculate_link_count() //! |> { //! // If pass block statement instead of fn, it will be placed before current step, //! // so it will us allow to capture some variables from context //! let ref client = client; //! move |url| //! // `try_join_async!` wraps its content into `Box::pin(async move { })` //! try_join_async! { //! client //! .get(url).send() //! => |value| value.text() //! => |body| ok((url, body.matches("https://").collect::<Vec<_>>().len())) //! } //! } //! // Collect values into `Vec<_>` //! =>[] Vec<_> //! |> Ok //! => try_join_all //! !> |err| format_err!("Error retrieving pages to calculate links: {:#?}", err) //! => |results| //! ok( //! results //! .into_iter() //! .max_by_key(|(_, link_count)| link_count.clone()) //! .unwrap() //! ) //! // It waits for input in stdin before log max links count //! ~?? |result| { //! result //! .as_ref() //! .map( //! |(url, count)| { //! let split = url.to_owned().split('/').collect::<Vec<_>>(); //! let domain_name = split.get(2).unwrap_or(&url); //! println!("Max `https://` link count found on `{}`: {}", domain_name, count) //! } //! ) //! .unwrap_or(()); //! }, //! // Concurrently it makes request to the site which generates random number //! get_url_to_get_random_number() //! -> ok //! => { //! // If pass block statement instead of fn, it will be placed before current step, //! // so it will allow us to capture some variables from context //! let ref client = client; //! let map_parse_error = //! |value| //! move |err| //! format_err!("Failed to parse random number: {:#?}, value: {}", err, value); //! move |url| //! try_join_async! { //! client //! .get(url) //! .send() //! => |value| value.text() //! !> |err| format_err!("Error retrieving random number: {:#?}", err) //! => |value| ok(value[..value.len() - 1].to_owned()) // remove \n from `154\n` //! => |value| //! ready( //! value //! .parse::<u16>() //! .map_err(map_parse_error(value)) //! ) //! } //! } //! // It waits for input in stdin before log random value //! ~?? |random| { //! random //! .as_ref() //! .map(|number| println!("Random: {}", number)) //! .unwrap_or(()); //! }, //! // Concurrently it reads value from stdin //! read_number_from_stdin(), //! // Finally, when we will have all results, we can decide, who is winner //! map => |(_url, link_count), random_number, number_from_stdin| { //! let random_diff = (link_count as i32 - random_number as i32).abs(); //! let stdin_diff = (link_count as i32 - number_from_stdin as i32).abs(); //! match () { //! _ if random_diff > stdin_diff => GameResult::Won, //! _ if random_diff < stdin_diff => GameResult::Lost, //! _ => GameResult::Draw //! } //! } //! }; //! //! let _ = game.await.map( //! |result| //! println!( //! "You {}", //! match result { //! GameResult::Won => "won!", //! GameResult::Lost => "lose...", //! _ => "have the same result as random generator!" //! } //! ) //! ).unwrap_or_else(|error| eprintln!("Error: {:#?}", error)); //! } //! //! fn get_urls_to_calculate_link_count() -> impl Stream<Item = &'static str> { //! iter( //! vec![ //! "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=random&grnnamespace=0&prop=revisions|images&rvprop=content&grnlimit=100", //! "https://github.com/explore", //! "https://twitter.com/search?f=tweets&vertical=news&q=%23news&src=unkn" //! ] //! ) //! } //! //! fn get_url_to_get_random_number() -> &'static str { //! "https://www.random.org/integers/?num=1&min=0&max=500&col=1&base=10&format=plain&rnd=new" //! } //! //! async fn read_number_from_stdin() -> Result<u16, Error> { //! use tokio::*; //! use futures::stream::StreamExt; //! //! let map_parse_error = //! |value| //! move |error| //! format_err!("Value from stdin isn't a correct `u16`: {:?}, input: {}", error, value); //! //! let mut result; //! let mut reader = codec::FramedRead::new(io::BufReader::new(io::stdin()), codec::LinesCodec::new()); //! //! while { //! println!("Please, enter number (`u16`)"); //! //! let next = reader.next(); //! //! result = try_join_async! { //! next //! |> |value| value.ok_or(format_err!("Unexpected end of input")) //! => >>> //! !> |err| format_err!("Failed to apply codec: {:?}", err) -> ready //! <<< //! => |value| //! ready( //! value //! .parse() //! .map_err(map_parse_error(value)) //! ) //! !> |error| { eprintln!("Error: {:#?}", error); error} //! }.await; //! //! result.is_err() //! } {} //! //! result //! } //! ``` //! //! ## Single thread combinations //! //! ### Sync branches //! //! Converts input in series of chained results and joins them step by step. //! //! ```rust //! use std::error::Error; //! use join::try_join; //! //! type Result<T> = std::result::Result<T, Box<dyn Error>>; //! //! fn action_1() -> Result<u16> { //! Ok(1) //! } //! //! fn action_2() -> Result<u8> { //! Ok(2) //! } //! //! fn main() { //! let sum = try_join! { //! // action_1(), //! action_1(), //! //! // action_2().map(|v| v as u16), //! action_2() |> |v| v as u16, //! //! // action_2().map(|v| v as u16 + 1).and_then(|v| Ok(v * 4)), //! action_2() |> |v| v as u16 + 1 => |v| Ok(v * 4), //! //! // action_1().and_then(|_| Err("5".into())).or(Ok(2)), //! action_1() => |_| Err("5".into()) <| Ok(2), //! //! map => |a, b, c, d| a + b + c + d //! }.expect("Failed to calculate sum"); //! //! println!("Calculated: {}", sum); //! } //! ``` //! //! ### Futures //! //! Each branch will represent future chain. All branches will be joined using `::futures::join!`/`::futures::try_join!` macro and `join_async!`/`try_join_async!` will return `unpolled` future. //! //! ```rust //! #![recursion_limit="256"] //! //! use std::error::Error; //! use join::try_join_async; //! use futures::future::{ok, err}; //! //! type Result<T> = std::result::Result<T, Box<dyn Error>>; //! //! async fn action_1() -> Result<u16> { //! Ok(1) //! } //! async fn action_2() -> Result<u8> { //! Ok(2) //! } //! //! #[tokio::main] //! async fn main() { //! // Branches will be executed concurrently //! let sum = try_join_async! { //! // action_1(), //! action_1(), //! //! // action_2().and_then(|v| ok(v as u16)), //! action_2() => |v| ok(v as u16), //! //! // action_2().map(|v| v.map(|v| v as u16 + 1)).and_then(|v| ok(v * 4u16)), //! action_2() |> |v| v.map(|v| v as u16 + 1) => |v| ok(v * 4u16), //! //! // action_1().and_then(|_| err("5".into())).or_else(|_| ok(2u16)), //! action_1() => |_| err("5".into()) <= |_| ok(2u16), //! //! and_then => |a, b, c, d| ok(a + b + c + d) //! }.await.expect("Failed to calculate sum"); //! //! println!("Calculated: {}", sum); //! } //! ``` //! //! ## Multi thread combinations //! //! To execute several tasks in parallel you could use `join_spawn!` (`spawn!`) for sync tasks //! and `join_async_spawn!` (`async_spawn!`) for futures. Since `join_async`already provides concurrent futures execution in one thread, `join_async_spawn!` spawns every branch into `tokio` executor, so they will be evaluated in multi threaded executor. //! //! ### Sync threads //! //! `join_spawn` spawns one `::std::thread` per each step of each branch (number of branches is the max thread count at the time). //! //! ```rust //! //! use std::error::Error; //! use join::try_join_spawn; //! //! type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>; //! //! fn action_1() -> Result<usize> { //! Ok(1) //! } //! //! fn action_2() -> Result<u16> { //! Ok(2) //! } //! //! fn main() { //! // Branches will be executed in parallel //! let sum = try_join_spawn! { //! // thread::spawn(move || action_1()), //! action_1(), //! //! // thread::spawn(move || action_2().map(|v| v as usize)), //! action_2() |> |v| v as usize, //! //! // thread::spawn(move || action_2().map(|v| v as usize + 1).and_then(|v| Ok(v * 4))), //! action_2() |> |v| v as usize + 1 => |v| Ok(v * 4), //! //! // thread::spawn(move || action_1().and_then(|_| Err("5".into())).or(Ok(2))), //! action_1() => |_| Err("5".into()) <| Ok(2), //! //! map => |a, b, c, d| a + b + c + d //! }.expect("Failed to calculate sum"); //! //! println!("Calculated: {}", sum); //! } //! ``` //! //! *Thread names* //! //! In runtime thread's name will be constructed from name of parent thread and join_%branch_index%. //! //! Example code with many branches: //! //! ```rust //! extern crate join; //! //! use std::thread; //! //! use join::try_join_spawn; //! //! fn get_current_thread_name() -> String { //! thread::current().name().unwrap().to_owned() //! } //! //! fn print_branch_thread_name(index: &Result<usize, ()>) { //! println!("Branch: {}. Thread name: {}.", index.unwrap(), get_current_thread_name()); //! } //! //! fn main() { //! let _ = try_join_spawn! { //! Ok(0) ?? print_branch_thread_name, //! Ok(1) ?? print_branch_thread_name, //! try_join_spawn! { //! Ok(2) ?? print_branch_thread_name, //! try_join_spawn! { //! Ok(3) ?? print_branch_thread_name, //! } //! } //! }.unwrap(); //! } //! //! // Branch: 0. Thread name: main_join_0. //! // Branch: 1. Thread name: main_join_1. //! // Branch: 2. Thread name: main_join_2_join_0. //! // Branch: 3. Thread name: main_join_2_join_1_join_0. //! // Order could be different. //! ``` //! //! ### Future tasks //! //! [`join_async_spawn!`](macro.join_async_spawn.html) uses [`::tokio::spawn`](https://docs.rs/tokio/0.2.0-alpha.6/tokio/fn.spawn.html) function to spawn futures so it should be done inside `tokio` runtime. //! //! ```rust //! #![recursion_limit="256"] //! //! use std::error::Error; //! use join::try_join_async_spawn; //! use futures::future::{ok, err}; //! //! type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>; //! //! async fn action_1() -> Result<u16> { //! Ok(1) //! } //! //! async fn action_2() -> Result<u8> { //! Ok(2) //! } //! //! #[tokio::main] //! async fn main() { //! // Branches will be executed concurrently, in multi thread executor //! let sum = try_join_async_spawn! { //! // tokio::spawn(Box::pin(action_1())) //! action_1(), //! //! // tokio::spawn(Box::pin(action_2().and_then(|v| ok(v as u16)))) //! action_2() => |v| ok(v as u16), //! //! // tokio::spawn(Box::pin(action_2().map(|v| v.map(|v| v as u16 + 1)).and_then(|v| ok(v * 4u16)))) //! action_2() |> |v| v.map(|v| v as u16 + 1) => |v| ok(v * 4u16), //! //! // tokio::spawn(Box::pin(action_1().and_then(|_| err("5".into())).or_else(|_| ok(2u16)))) //! action_1() => |_| err("5".into()) <= |_| ok(2u16), //! //! and_then => |a, b, c, d| ok(a + b + c + d) //! }.await.expect("Failed to calculate sum"); //! //! println!("Calculated: {}", sum); //! } //! ``` //! //! ## Detailed steps example //! //! By separating chain in actions, you will make actions wait for completion of all of them in current step before go to the next step. //! //! ```rust //! #![recursion_limit="256"] //! //! use std::error::Error; //! use join::try_join; //! //! type Result<T> = std::result::Result<T, Box<dyn Error + Send + Sync>>; //! //! fn action_1() -> Result<u16> { //! Ok(1) //! } //! //! fn action_2() -> Result<u8> { //! Ok(2) //! } //! //! fn main() { //! let sum = try_join! { //! action_1(), //! let result_1 = action_2() ~|> |v| v as u16 + 1, //! action_2() ~|> { //! // `result_1` now is the result of `action_2()` [Ok(1u8)] //! let result_1 = result_1.as_ref().ok().map(Clone::clone); //! move |v| { //! if result_1.is_some() { //! v as u16 + 1 //! } else { //! unreachable!() //! } //! } //! } ~=> { //! // `result_1` now is the result of `|v| v as u16 + 1` [Ok(2u16)] //! let result_1 = result_1.as_ref().ok().map(Clone::clone); //! move |v| { //! if let Some(result_1) = result_1 { //! Ok(v * 4 + result_1) //! } else { //! unreachable!() //! } //! } //! }, //! action_1() ~=> |_| Err("5".into()) <| Ok(2), //! map => |a, b, c, d| a + b + c + d //! }.expect("Failed to calculate sum"); //! println!("Calculated: {}", sum); //! } //! ``` extern crate join_export; extern crate proc_macro_hack; extern crate proc_macro_nested; use proc_macro_hack::proc_macro_hack; /// /// Use to combine results. /// /// ```rust /// extern crate join; /// /// use join::try_join; /// /// fn main() { /// let product = try_join! { /// Ok::<_,u8>(2) |> |v| v + 2, /// Ok::<_,u8>(3), /// Ok::<_,u8>(4), /// map => |a, b, c| a * b * c /// }.unwrap(); /// /// assert_eq!(product, 48); /// } /// ``` /// #[proc_macro_hack(support_nested)] pub use join_export::try_join; /// /// Use to combine futures. /// /// ```rust /// #![recursion_limit="256"] /// /// extern crate join; /// extern crate futures; /// /// use join::try_join_async; /// use futures::future::ok; /// /// #[tokio::main] /// async fn main() { /// let product = try_join_async! { /// ok::<_,u8>(2u16) => |v| ok::<_,u8>(v + 2u16), /// ok::<_,u8>(3u16), /// ok::<_,u8>(4u16), /// map => |a, b, c| a * b * c /// }.await.unwrap(); /// /// assert_eq!(product, 48); /// } /// ``` /// #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::try_join_async; /// /// Use to spawn [`::std::thread`](https://doc.rust-lang.org/std/thread/) per each step of each branch. /// /// ```rust /// extern crate join; /// /// use join::try_join_spawn; /// /// fn main() { /// let product = try_join_spawn! { /// Ok::<_,u8>(2) |> |v| v + 2 ?? |_| { /// println!("Hello from parallel world!"); /// ::std::thread::sleep(::std::time::Duration::from_secs(1)); /// println!("I'm done."); /// }, /// Ok::<_,u8>(3) ?? |_| { /// println!("Hello from parallel world again!"); /// ::std::thread::sleep(::std::time::Duration::from_secs(2)); /// println!("Me too."); /// }, /// Ok::<_,u8>(4), /// map => |a, b, c| a * b * c /// }.unwrap(); /// /// assert_eq!(product, 48); /// } ///``` #[proc_macro_hack(support_nested)] pub use join_export::try_join_spawn; /// /// Alias for [`try_join_spawn!`](macro.try_join_spawn.html). /// #[proc_macro_hack(support_nested)] pub use join_export::try_spawn; /// /// Use to spawn [`::tokio::spawn`](https://docs.rs/tokio/0.2.0-alpha.6/tokio/fn.spawn.html) per each step of each branch. /// ```rust /// #![recursion_limit="512"] /// /// extern crate join; /// extern crate futures; /// extern crate tokio; /// extern crate futures_timer; /// /// use join::try_join_async_spawn; /// use futures::future::ok; /// use futures_timer::Delay; /// use std::time::Duration; /// /// #[tokio::main] /// async fn main() { /// let product = try_join_async_spawn! { /// ok::<_,u8>(2u16) |> |v| Ok::<_,u8>(v.unwrap() + 2u16) => |v| async move { /// println!("Hello from parallel world!"); /// Delay::new(Duration::from_secs(1)).await; /// println!("I'm done."); /// Ok(v) /// }, /// ok::<_,u8>(3u16) => |v| async move { /// println!("Hello from parallel world again!"); /// Delay::new(Duration::from_secs(2)).await; /// println!("Me too."); /// Ok(v) /// }, /// ok::<_,u8>(4u16), /// map => |a, b, c| a * b * c /// }.await.unwrap(); /// /// assert_eq!(product, 48); /// } ///``` #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::try_join_async_spawn; /// /// Alias for [`try_join_async_spawn!`](macro.try_join_async_spawn.html). /// #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::try_async_spawn; /// /// Use to combine sync values. It produces tuple of values or single value in case of 1 branch. /// /// ```rust /// extern crate join; /// /// use join::join; /// /// fn main() { /// let filtered: Vec<_> = join! { vec![1,2,3].into_iter() ?> |v| v % 2 == 0 =>[] }; /// assert_eq!(filtered, vec![2]); /// } /// ``` /// #[proc_macro_hack(support_nested)] pub use join_export::join; /// /// Use to combine futures. It produces tuple of values or single value in case of 1 branch. /// /// ```rust /// #![recursion_limit="256"] /// /// extern crate join; /// extern crate futures; /// /// use join::join_async; /// use futures::future::{ready}; /// use futures::stream::iter; /// /// #[tokio::main] /// async fn main() { /// let filtered: Vec<_> = join_async! { iter(vec![1u8,2,3]) ?> |v| ready(v % 2 == 0) =>[] }.await; /// assert_eq!(filtered, vec![2]); /// } /// ``` /// #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::join_async; /// /// Use to spawn [`::std::thread`](https://doc.rust-lang.org/std/thread/) per each step of each branch. /// /// ```rust /// extern crate join; /// /// use join::join_spawn; /// /// fn main() { /// let filtered: Vec<_> = join_spawn! { vec![1,2,3].into_iter() ?> |v| v % 2 == 0 =>[] }; /// assert_eq!(filtered, vec![2]); /// } ///``` #[proc_macro_hack(support_nested)] pub use join_export::join_spawn; /// /// Alias for [`join_spawn!`](macro.join_spawn.html). /// #[proc_macro_hack(support_nested)] pub use join_export::spawn; /// /// Use to spawn futures using [`::tokio::spawn`](https://docs.rs/tokio/0.2.0-alpha.6/tokio/fn.spawn.html) per each step of each branch. /// ```rust /// #![recursion_limit="256"] /// /// extern crate join; /// extern crate futures; /// /// use join::join_async_spawn; /// use futures::future::ready; /// use futures::stream::{iter, StreamExt}; /// /// #[tokio::main] /// async fn main() { /// let filtered: Vec<_> = join_async_spawn! { iter(vec![1u8,2,3]) ?> |v| ready(v % 2 == 0) =>[] }.await; /// assert_eq!(filtered, vec![2]); /// } ///``` #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::join_async_spawn; /// /// Alias for [`join_async_spawn!`](macro.join_async_spawn.html). /// #[proc_macro_hack(support_nested, internal_macro_calls = 20)] pub use join_export::async_spawn;