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 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! Parallel async tasks and async task runners.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]
use std::{
fmt,
future::{Future, IntoFuture},
hash::Hash,
mem, panic,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
task::Poll,
};
#[doc(no_inline)]
pub use parking_lot;
use parking_lot::Mutex;
mod crate_util;
use crate::crate_util::PanicResult;
use zng_app_context::{app_local, LocalContext};
use zng_time::Deadline;
use zng_var::{response_done_var, response_var, AnyVar, ResponseVar, VarValue};
#[cfg(test)]
pub mod tests;
#[doc(no_inline)]
pub use rayon;
/// Async filesystem primitives.
///
/// This module is the [async-fs](https://docs.rs/async-fs) crate re-exported for convenience.
pub mod fs {
#[doc(inline)]
pub use async_fs::*;
}
pub mod channel;
pub mod io;
mod ui;
pub mod http;
pub mod ipc;
mod rayon_ctx;
pub use rayon_ctx::*;
pub use ui::*;
mod progress;
pub use progress::*;
/// Spawn a parallel async task, this function is not blocking and the `task` starts executing immediately.
///
/// # Parallel
///
/// The task runs in the primary [`rayon`] thread-pool, every [`poll`](Future::poll) happens inside a call to `rayon::spawn`.
///
/// You can use parallel iterators, `join` or any of rayon's utilities inside `task` to make it multi-threaded,
/// otherwise it will run in a single thread at a time, still not blocking the UI.
///
/// The [`rayon`] crate is re-exported in `task::rayon` for convenience and compatibility.
///
/// # Async
///
/// The `task` is also a future so you can `.await`, after each `.await` the task continues executing in whatever `rayon` thread
/// is free, so the `task` should either be doing CPU intensive work or awaiting, blocking IO operations
/// block the thread from being used by other tasks reducing overall performance. You can use [`wait`] for IO
/// or blocking operations and for networking you can use any of the async crates, as long as they start their own *event reactor*.
///
/// The `task` lives inside the [`Waker`] when awaiting and inside `rayon::spawn` when running.
///
/// # Examples
///
/// ```
/// # use zng_task::{self as task, *, rayon::iter::*};
/// # use zng_var::*;
/// # struct SomeStruct { sum_response: ResponseVar<usize> }
/// # impl SomeStruct {
/// fn on_event(&mut self) {
/// let (responder, response) = response_var();
/// self.sum_response = response;
///
/// task::spawn(async move {
/// let r = (0..1000).into_par_iter().map(|i| i * i).sum();
///
/// responder.respond(r);
/// });
/// }
///
/// fn on_update(&mut self) {
/// if let Some(result) = self.sum_response.rsp_new() {
/// println!("sum of squares 0..1000: {result}");
/// }
/// }
/// # }
/// ```
///
/// The example uses the `rayon` parallel iterator to compute a result and uses a [`response_var`] to send the result to the UI.
/// The task captures the caller [`LocalContext`] so the response variable will set correctly.
///
/// Note that this function is the most basic way to spawn a parallel task where you must setup channels to the rest of the app yourself,
/// you can use [`respond`] to avoid having to manually set a response, or [`run`] to `.await` the result.
///
/// # Panic Handling
///
/// If the `task` panics the panic message is logged as an error, the panic is otherwise ignored.
///
/// # Unwind Safety
///
/// This function disables the [unwind safety validation], meaning that in case of a panic shared
/// data can end-up in an invalid, but still memory safe, state. If you are worried about that only use
/// poisoning mutexes or atomics to mutate shared data or use [`run_catch`] to detect a panic or [`run`]
/// to propagate a panic.
///
/// [unwind safety validation]: std::panic::UnwindSafe
/// [`Waker`]: std::task::Waker
/// [`rayon`]: https://docs.rs/rayon
/// [`LocalContext`]: zng_app_context::LocalContext
/// [`response_var`]: zng_var::response_var
pub fn spawn<F>(task: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = ()> + Send + 'static,
{
Arc::new(RayonTask {
ctx: LocalContext::capture(),
fut: Mutex::new(Some(Box::pin(task.into_future()))),
})
.poll()
}
/// Polls the `task` once immediately on the calling thread, if the `task` is pending, continues execution in [`spawn`].
pub fn poll_spawn<F>(task: impl IntoFuture<IntoFuture = F>)
where
F: Future<Output = ()> + Send + 'static,
{
struct PollRayonTask {
fut: Mutex<Option<(RayonSpawnFut, Option<LocalContext>)>>,
}
impl PollRayonTask {
// start task in calling thread
fn poll(self: Arc<Self>) {
let mut task = self.fut.lock();
let (mut t, _) = task.take().unwrap();
let waker = self.clone().into();
match t.as_mut().poll(&mut std::task::Context::from_waker(&waker)) {
Poll::Ready(()) => {}
Poll::Pending => {
let ctx = LocalContext::capture();
*task = Some((t, Some(ctx)));
}
}
}
}
impl std::task::Wake for PollRayonTask {
fn wake(self: Arc<Self>) {
// continue task in spawn threads
if let Some((task, Some(ctx))) = self.fut.lock().take() {
Arc::new(RayonTask {
ctx,
fut: Mutex::new(Some(Box::pin(task))),
})
.poll();
}
}
}
Arc::new(PollRayonTask {
fut: Mutex::new(Some((Box::pin(task.into_future()), None))),
})
.poll()
}
type RayonSpawnFut = Pin<Box<dyn Future<Output = ()> + Send>>;
// A future that is its own waker that polls inside rayon spawn tasks.
struct RayonTask {
ctx: LocalContext,
fut: Mutex<Option<RayonSpawnFut>>,
}
impl RayonTask {
fn poll(self: Arc<Self>) {
rayon::spawn(move || {
// this `Option<Fut>` dance is used to avoid a `poll` after `Ready` or panic.
let mut task = self.fut.lock();
if let Some(mut t) = task.take() {
let waker = self.clone().into();
// load app context
self.ctx.clone().with_context(move || {
let r = panic::catch_unwind(panic::AssertUnwindSafe(move || {
// poll future
if t.as_mut().poll(&mut std::task::Context::from_waker(&waker)).is_pending() {
// not done
*task = Some(t);
}
}));
if let Err(p) = r {
tracing::error!("panic in `task::spawn`: {}", crate_util::panic_str(&p));
}
});
}
})
}
}
impl std::task::Wake for RayonTask {
fn wake(self: Arc<Self>) {
self.poll()
}
}
/// Rayon join with local context.
///
/// This function captures the [`LocalContext`] of the calling thread and propagates it to the threads that run the
/// operations.
///
/// See `rayon::join` for more details about join.
///
/// [`LocalContext`]: zng_app_context::LocalContext
pub fn join<A, B, RA, RB>(op_a: A, op_b: B) -> (RA, RB)
where
A: FnOnce() -> RA + Send,
B: FnOnce() -> RB + Send,
RA: Send,
RB: Send,
{
self::join_context(move |_| op_a(), move |_| op_b())
}
/// Rayon join context with local context.
///
/// This function captures the [`LocalContext`] of the calling thread and propagates it to the threads that run the
/// operations.
///
/// See `rayon::join_context` for more details about join.
///
/// [`LocalContext`]: zng_app_context::LocalContext
pub fn join_context<A, B, RA, RB>(op_a: A, op_b: B) -> (RA, RB)
where
A: FnOnce(rayon::FnContext) -> RA + Send,
B: FnOnce(rayon::FnContext) -> RB + Send,
RA: Send,
RB: Send,
{
let ctx = LocalContext::capture();
let ctx = &ctx;
rayon::join_context(
move |a| {
if a.migrated() {
ctx.clone().with_context(|| op_a(a))
} else {
op_a(a)
}
},
move |b| {
if b.migrated() {
ctx.clone().with_context(|| op_b(b))
} else {
op_b(b)
}
},
)
}
/// Rayon scope with local context.
///
/// This function captures the [`LocalContext`] of the calling thread and propagates it to the threads that run the
/// operations.
///
/// See `rayon::scope` for more details about scope.
///
/// [`LocalContext`]: zng_app_context::LocalContext
pub fn scope<'scope, OP, R>(op: OP) -> R
where
OP: FnOnce(ScopeCtx<'_, 'scope>) -> R + Send,
R: Send,
{
let ctx = LocalContext::capture();
// Cast `&'_ ctx` to `&'scope ctx` to "inject" the context in the scope.
// Is there a better way to do this? I hope so.
//
// SAFETY:
// * We are extending `'_` to `'scope`, that is one of the documented valid usages of `transmute`.
// * No use after free because `rayon::scope` joins all threads before returning and we only drop `ctx` after.
let ctx_ref: &'_ LocalContext = &ctx;
let ctx_scope_ref: &'scope LocalContext = unsafe { std::mem::transmute(ctx_ref) };
let r = rayon::scope(move |s| {
op(ScopeCtx {
scope: s,
ctx: ctx_scope_ref,
})
});
drop(ctx);
r
}
/// Represents a fork-join scope which can be used to spawn any number of tasks that run in the caller's thread context.
///
/// See [`scope`] for more details.
#[derive(Clone, Copy, Debug)]
pub struct ScopeCtx<'a, 'scope: 'a> {
scope: &'a rayon::Scope<'scope>,
ctx: &'scope LocalContext,
}
impl<'a, 'scope: 'a> ScopeCtx<'a, 'scope> {
/// Spawns a job into the fork-join scope `self`. The job runs in the captured thread context.
///
/// See `rayon::Scope::spawn` for more details.
pub fn spawn<F>(self, f: F)
where
F: FnOnce(ScopeCtx<'_, 'scope>) + Send + 'scope,
{
let ctx = self.ctx;
self.scope
.spawn(move |s| ctx.clone().with_context(move || f(ScopeCtx { scope: s, ctx })));
}
}
/// Spawn a parallel async task that can also be `.await` for the task result.
///
/// # Parallel
///
/// The task runs in the primary [`rayon`] thread-pool, every [`poll`](Future::poll) happens inside a call to `rayon::spawn`.
///
/// You can use parallel iterators, `join` or any of rayon's utilities inside `task` to make it multi-threaded,
/// otherwise it will run in a single thread at a time, still not blocking the UI.
///
/// The [`rayon`] crate is re-exported in `task::rayon` for convenience and compatibility.
///
/// # Async
///
/// The `task` is also a future so you can `.await`, after each `.await` the task continues executing in whatever `rayon` thread
/// is free, so the `task` should either be doing CPU intensive work or awaiting, blocking IO operations
/// block the thread from being used by other tasks reducing overall performance. You can use [`wait`] for IO
/// or blocking operations and for networking you can use any of the async crates, as long as they start their own *event reactor*.
///
/// The `task` lives inside the [`Waker`] when awaiting and inside `rayon::spawn` when running.
///
/// # Examples
///
/// ```
/// # use zng_task::{self as task, rayon::iter::*};
/// # struct SomeStruct { sum: usize }
/// # async fn read_numbers() -> Vec<usize> { vec![] }
/// # impl SomeStruct {
/// async fn on_event(&mut self) {
/// self.sum = task::run(async {
/// read_numbers().await.par_iter().map(|i| i * i).sum()
/// }).await;
/// }
/// # }
/// ```
///
/// The example `.await` for some numbers and then uses a parallel iterator to compute a result, this all runs in parallel
/// because it is inside a `run` task. The task result is then `.await` inside one of the UI async tasks. Note that the
/// task captures the caller [`LocalContext`] so you can interact with variables and UI services directly inside the task too.
///
/// # Cancellation
///
/// The task starts running immediately, awaiting the returned future merely awaits for a message from the worker threads and
/// that means the `task` future is not owned by the returned future. Usually to *cancel* a future you only need to drop it,
/// in this task dropping the returned future will only drop the `task` once it reaches a `.await` point and detects that the
/// result channel is disconnected.
///
/// If you want to deterministically known that the `task` was cancelled use a cancellation signal.
///
/// # Panic Propagation
///
/// If the `task` panics the panic is resumed in the awaiting thread using [`resume_unwind`]. You
/// can use [`run_catch`] to get the panic as an error instead.
///
/// [`resume_unwind`]: panic::resume_unwind
/// [`Waker`]: std::task::Waker
/// [`rayon`]: https://docs.rs/rayon
/// [`LocalContext`]: zng_app_context::LocalContext
pub async fn run<R, T>(task: impl IntoFuture<IntoFuture = T>) -> R
where
R: Send + 'static,
T: Future<Output = R> + Send + 'static,
{
match run_catch(task).await {
Ok(r) => r,
Err(p) => panic::resume_unwind(p),
}
}
/// Like [`run`] but catches panics.
///
/// This task works the same and has the same utility as [`run`], except if returns panic messages
/// as an error instead of propagating the panic.
///
/// # Unwind Safety
///
/// This function disables the [unwind safety validation], meaning that in case of a panic shared
/// data can end-up in an invalid, but still memory safe, state. If you are worried about that only use
/// poisoning mutexes or atomics to mutate shared data or discard all shared data used in the `task`
/// if this function returns an error.
///
/// [unwind safety validation]: std::panic::UnwindSafe
pub async fn run_catch<R, T>(task: impl IntoFuture<IntoFuture = T>) -> PanicResult<R>
where
R: Send + 'static,
T: Future<Output = R> + Send + 'static,
{
type Fut<R> = Pin<Box<dyn Future<Output = R> + Send>>;
// A future that is its own waker that polls inside the rayon primary thread-pool.
struct RayonCatchTask<R> {
ctx: LocalContext,
fut: Mutex<Option<Fut<R>>>,
sender: flume::Sender<PanicResult<R>>,
}
impl<R: Send + 'static> RayonCatchTask<R> {
fn poll(self: Arc<Self>) {
let sender = self.sender.clone();
if sender.is_disconnected() {
return; // cancel.
}
rayon::spawn(move || {
// this `Option<Fut>` dance is used to avoid a `poll` after `Ready` or panic.
let mut task = self.fut.lock();
if let Some(mut t) = task.take() {
let waker = self.clone().into();
let mut cx = std::task::Context::from_waker(&waker);
self.ctx.clone().with_context(|| {
let r = panic::catch_unwind(panic::AssertUnwindSafe(|| t.as_mut().poll(&mut cx)));
match r {
Ok(Poll::Ready(r)) => {
drop(task);
let _ = sender.send(Ok(r));
}
Ok(Poll::Pending) => {
*task = Some(t);
}
Err(p) => {
drop(task);
let _ = sender.send(Err(p));
}
}
});
}
})
}
}
impl<R: Send + 'static> std::task::Wake for RayonCatchTask<R> {
fn wake(self: Arc<Self>) {
self.poll()
}
}
let (sender, receiver) = channel::bounded(1);
Arc::new(RayonCatchTask {
ctx: LocalContext::capture(),
fut: Mutex::new(Some(Box::pin(task.into_future()))),
sender: sender.into(),
})
.poll();
receiver.recv().await.unwrap()
}
/// Spawn a parallel async task that will send its result to a [`ResponseVar<R>`].
///
/// The [`run`] documentation explains how `task` is *parallel* and *async*. The `task` starts executing immediately.
///
/// # Examples
///
/// ```
/// # use zng_task::{self as task, rayon::iter::*};
/// # use zng_var::*;
/// # struct SomeStruct { sum_response: ResponseVar<usize> }
/// # async fn read_numbers() -> Vec<usize> { vec![] }
/// # impl SomeStruct {
/// fn on_event(&mut self) {
/// self.sum_response = task::respond(async {
/// read_numbers().await.par_iter().map(|i| i * i).sum()
/// });
/// }
///
/// fn on_update(&mut self) {
/// if let Some(result) = self.sum_response.rsp_new() {
/// println!("sum of squares: {result}");
/// }
/// }
/// # }
/// ```
///
/// The example `.await` for some numbers and then uses a parallel iterator to compute a result. The result is send to
/// `sum_response` that is a [`ResponseVar<R>`].
///
/// # Cancellation
///
/// Dropping the [`ResponseVar<R>`] does not cancel the `task`, it will still run to completion.
///
/// # Panic Handling
///
/// If the `task` panics the panic is logged as an error and resumed in the response var modify closure.
///
/// [`resume_unwind`]: panic::resume_unwind
/// [`ResponseVar<R>`]: zng_var::ResponseVar
/// [`response_var`]: zng_var::response_var
pub fn respond<R, F>(task: F) -> ResponseVar<R>
where
R: VarValue,
F: Future<Output = R> + Send + 'static,
{
type Fut<R> = Pin<Box<dyn Future<Output = R> + Send>>;
let (responder, response) = response_var();
// A future that is its own waker that polls inside the rayon primary thread-pool.
struct RayonRespondTask<R: VarValue> {
ctx: LocalContext,
fut: Mutex<Option<Fut<R>>>,
responder: zng_var::ResponderVar<R>,
}
impl<R: VarValue> RayonRespondTask<R> {
fn poll(self: Arc<Self>) {
let responder = self.responder.clone();
if responder.strong_count() == 2 {
return; // cancel.
}
rayon::spawn(move || {
// this `Option<Fut>` dance is used to avoid a `poll` after `Ready` or panic.
let mut task = self.fut.lock();
if let Some(mut t) = task.take() {
let waker = self.clone().into();
let mut cx = std::task::Context::from_waker(&waker);
self.ctx.clone().with_context(|| {
let r = panic::catch_unwind(panic::AssertUnwindSafe(|| t.as_mut().poll(&mut cx)));
match r {
Ok(Poll::Ready(r)) => {
drop(task);
responder.respond(r);
}
Ok(Poll::Pending) => {
*task = Some(t);
}
Err(p) => {
tracing::error!("panic in `task::respond`: {}", crate_util::panic_str(&p));
drop(task);
responder.modify(move |_| panic::resume_unwind(p));
}
}
});
}
})
}
}
impl<R: VarValue> std::task::Wake for RayonRespondTask<R> {
fn wake(self: Arc<Self>) {
self.poll()
}
}
Arc::new(RayonRespondTask {
ctx: LocalContext::capture(),
fut: Mutex::new(Some(Box::pin(task))),
responder,
})
.poll();
response
}
/// Polls the `task` once immediately on the calling thread, if the `task` is ready returns the response already set,
/// if the `task` is pending continues execution like [`respond`].
pub fn poll_respond<R, F>(task: impl IntoFuture<IntoFuture = F>) -> ResponseVar<R>
where
R: VarValue,
F: Future<Output = R> + Send + 'static,
{
enum QuickResponse<R: VarValue> {
Quick(Option<R>),
Response(zng_var::ResponderVar<R>),
}
let task = task.into_future();
let q = Arc::new(Mutex::new(QuickResponse::Quick(None)));
poll_spawn(zng_clone_move::async_clmv!(q, {
let rsp = task.await;
match &mut *q.lock() {
QuickResponse::Quick(q) => *q = Some(rsp),
QuickResponse::Response(r) => r.respond(rsp),
}
}));
let mut q = q.lock();
match &mut *q {
QuickResponse::Quick(q) if q.is_some() => response_done_var(q.take().unwrap()),
_ => {
let (responder, response) = response_var();
*q = QuickResponse::Response(responder);
response
}
}
}
/// Create a parallel `task` that blocks awaiting for an IO operation, the `task` starts on the first `.await`.
///
/// # Parallel
///
/// The `task` runs in the [`blocking`] thread-pool which is optimized for awaiting blocking operations.
/// If the `task` is computation heavy you should use [`run`] and then `wait` inside that task for the
/// parts that are blocking.
///
/// # Examples
///
/// ```
/// # fn main() { }
/// # use zng_task as task;
/// # async fn example() {
/// task::wait(|| std::fs::read_to_string("file.txt")).await
/// # ; }
/// ```
///
/// The example reads a file, that is a blocking file IO operation, most of the time is spend waiting for the operating system,
/// so we offload this to a `wait` task. The task can be `.await` inside a [`run`] task or inside one of the UI tasks
/// like in a async event handler.
///
/// # Async Read/Write
///
/// For [`std::io::Read`] and [`std::io::Write`] operations you can also use [`io`] and [`fs`] alternatives when you don't
/// have or want the full file in memory or when you want to apply multiple operations to the file.
///
/// # Panic Propagation
///
/// If the `task` panics the panic is resumed in the awaiting thread using [`resume_unwind`]. You
/// can use [`wait_catch`] to get the panic as an error instead.
///
/// [`blocking`]: https://docs.rs/blocking
/// [`resume_unwind`]: panic::resume_unwind
pub async fn wait<T, F>(task: F) -> T
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
match wait_catch(task).await {
Ok(r) => r,
Err(p) => panic::resume_unwind(p),
}
}
/// Like [`wait`] but catches panics.
///
/// This task works the same and has the same utility as [`wait`], except if returns panic messages
/// as an error instead of propagating the panic.
///
/// # Unwind Safety
///
/// This function disables the [unwind safety validation], meaning that in case of a panic shared
/// data can end-up in an invalid, but still memory safe, state. If you are worried about that only use
/// poisoning mutexes or atomics to mutate shared data or discard all shared data used in the `task`
/// if this function returns an error.
///
/// [unwind safety validation]: std::panic::UnwindSafe
pub async fn wait_catch<T, F>(task: F) -> PanicResult<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
let mut ctx = LocalContext::capture();
blocking::unblock(move || ctx.with_context(move || panic::catch_unwind(panic::AssertUnwindSafe(task)))).await
}
/// Fire and forget a [`wait`] task. The `task` starts executing immediately.
///
/// # Panic Handling
///
/// If the `task` panics the panic message is logged as an error, the panic is otherwise ignored.
///
/// # Unwind Safety
///
/// This function disables the [unwind safety validation], meaning that in case of a panic shared
/// data can end-up in an invalid (still memory safe) state. If you are worried about that only use
/// poisoning mutexes or atomics to mutate shared data or use [`wait_catch`] to detect a panic or [`wait`]
/// to propagate a panic.
///
/// [unwind safety validation]: std::panic::UnwindSafe
pub fn spawn_wait<F>(task: F)
where
F: FnOnce() + Send + 'static,
{
spawn(async move {
if let Err(p) = wait_catch(task).await {
tracing::error!("parallel `spawn_wait` task panicked: {}", crate_util::panic_str(&p))
}
});
}
/// Like [`spawn_wait`], but the task will send its result to a [`ResponseVar<R>`].
///
/// # Cancellation
///
/// Dropping the [`ResponseVar<R>`] does not cancel the `task`, it will still run to completion.
///
/// # Panic Handling
///
/// If the `task` panics the panic is logged as an error and resumed in the response var modify closure.
pub fn wait_respond<R, F>(task: F) -> ResponseVar<R>
where
R: VarValue,
F: FnOnce() -> R + Send + 'static,
{
let (responder, response) = response_var();
spawn_wait(move || match panic::catch_unwind(panic::AssertUnwindSafe(task)) {
Ok(r) => responder.respond(r),
Err(p) => {
tracing::error!("panic in `task::wait_respond`: {}", crate_util::panic_str(&p));
responder.modify(move |_| panic::resume_unwind(p))
}
});
response
}
/// Blocks the thread until the `task` future finishes.
///
/// This function is useful for implementing async tests, using it in an app will probably cause
/// the app to stop responding.
///
/// The crate [`futures-lite`] is used to execute the task.
///
/// # Examples
///
/// Test a [`run`] call:
///
/// ```
/// use zng_task as task;
/// # use zng_unit::*;
/// # async fn foo(u: u8) -> Result<u8, ()> { task::deadline(1.ms()).await; Ok(u) }
///
/// #[test]
/// # fn __() { }
/// pub fn run_ok() {
/// let r = task::block_on(task::run(async {
/// foo(32).await
/// }));
///
/// # let value =
/// r.expect("foo(32) was not Ok");
/// # assert_eq!(32, value);
/// }
/// # run_ok();
/// ```
///
/// [`futures-lite`]: https://docs.rs/futures-lite/
pub fn block_on<F>(task: impl IntoFuture<IntoFuture = F>) -> F::Output
where
F: Future,
{
futures_lite::future::block_on(task.into_future())
}
/// Continuous poll the `task` until if finishes.
///
/// This function is useful for implementing some async tests only, futures don't expect to be polled
/// continuously. This function is only available in test builds.
#[cfg(any(test, doc, feature = "test_util"))]
pub fn spin_on<F>(task: impl IntoFuture<IntoFuture = F>) -> F::Output
where
F: Future,
{
use std::pin::pin;
let mut task = pin!(task.into_future());
block_on(future_fn(|cx| match task.as_mut().poll(cx) {
Poll::Ready(r) => Poll::Ready(r),
Poll::Pending => {
cx.waker().wake_by_ref();
Poll::Pending
}
}))
}
/// Executor used in async doc tests.
///
/// If `spin` is `true` the [`spin_on`] executor is used with a timeout of 500 milliseconds.
/// IF `spin` is `false` the [`block_on`] executor is used with a timeout of 5 seconds.
#[cfg(any(test, doc, feature = "test_util"))]
pub fn doc_test<F>(spin: bool, task: impl IntoFuture<IntoFuture = F>) -> F::Output
where
F: Future,
{
use zng_unit::TimeUnits;
if spin {
spin_on(with_deadline(task, 500.ms())).expect("async doc-test timeout")
} else {
block_on(with_deadline(task, 5.secs())).expect("async doc-test timeout")
}
}
/// A future that is [`Pending`] once and wakes the current task.
///
/// After the first `.await` the future is always [`Ready`] and on the first `.await` it calls [`wake`].
///
/// [`Pending`]: std::task::Poll::Pending
/// [`Ready`]: std::task::Poll::Ready
/// [`wake`]: std::task::Waker::wake
pub async fn yield_now() {
struct YieldNowFut(bool);
impl Future for YieldNowFut {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
YieldNowFut(false).await
}
/// A future that is [`Pending`] until the `deadline` is reached.
///
/// # Examples
///
/// Await 5 seconds in a [`spawn`] parallel task:
///
/// ```
/// use zng_task as task;
/// use zng_unit::*;
///
/// task::spawn(async {
/// println!("waiting 5 seconds..");
/// task::deadline(5.secs()).await;
/// println!("5 seconds elapsed.")
/// });
/// ```
///
/// The future runs on an app provider timer executor, or on the [`futures_timer`] by default.
///
/// Note that deadlines from [`Duration`](std::time::Duration) starts *counting* at the moment this function is called,
/// not at the moment of the first `.await` call.
///
/// [`Pending`]: std::task::Poll::Pending
/// [`futures_timer`]: https://docs.rs/futures-timer
pub fn deadline(deadline: impl Into<Deadline>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
let deadline = deadline.into();
if zng_app_context::LocalContext::current_app().is_some() {
DEADLINE_SV.read().0(deadline)
} else {
default_deadline(deadline)
}
}
app_local! {
static DEADLINE_SV: (DeadlineService, bool) = const { (default_deadline, false) };
}
type DeadlineService = fn(Deadline) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>>;
fn default_deadline(deadline: Deadline) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
if let Some(timeout) = deadline.time_left() {
Box::pin(futures_timer::Delay::new(timeout))
} else {
Box::pin(std::future::ready(()))
}
}
/// Deadline APP integration.
#[expect(non_camel_case_types)]
pub struct DEADLINE_APP;
impl DEADLINE_APP {
/// Called by the app implementer to setup the [`deadline`] executor.
///
/// If no app calls this the [`futures_timer`] executor is used.
///
/// [`futures_timer`]: https://docs.rs/futures-timer
///
/// # Panics
///
/// Panics if called more than once for the same app.
pub fn init_deadline_service(&self, service: DeadlineService) {
let (prev, already_set) = mem::replace(&mut *DEADLINE_SV.write(), (service, true));
if already_set {
*DEADLINE_SV.write() = (prev, true);
panic!("deadline service already inited for this app");
}
}
}
/// Implements a [`Future`] from a closure.
///
/// # Examples
///
/// A future that is ready with a closure returns `Some(R)`.
///
/// ```
/// use zng_task as task;
/// use std::task::Poll;
///
/// async fn ready_some<R>(mut closure: impl FnMut() -> Option<R>) -> R {
/// task::future_fn(|cx| {
/// match closure() {
/// Some(r) => Poll::Ready(r),
/// None => Poll::Pending
/// }
/// }).await
/// }
/// ```
pub async fn future_fn<T, F>(fn_: F) -> T
where
F: FnMut(&mut std::task::Context) -> Poll<T>,
{
struct PollFn<F>(F);
impl<F> Unpin for PollFn<F> {}
impl<T, F: FnMut(&mut std::task::Context<'_>) -> Poll<T>> Future for PollFn<F> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
(self.0)(cx)
}
}
PollFn(fn_).await
}
/// Error when [`with_deadline`] reach a time limit before a task finishes.
#[derive(Debug, Clone, Copy)]
pub struct DeadlineError {}
impl fmt::Display for DeadlineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "reached deadline")
}
}
impl std::error::Error for DeadlineError {}
/// Add a [`deadline`] to a future.
///
/// Returns the `fut` output or [`DeadlineError`] if the deadline elapses first.
pub async fn with_deadline<O, F: Future<Output = O>>(
fut: impl IntoFuture<IntoFuture = F>,
deadline: impl Into<Deadline>,
) -> Result<F::Output, DeadlineError> {
let deadline = deadline.into();
any!(async { Ok(fut.await) }, async {
self::deadline(deadline).await;
Err(DeadlineError {})
})
.await
}
/// <span data-del-macro-root></span> A future that *zips* other futures.
///
/// The macro input is a comma separated list of future expressions. The macro output is a future
/// that when ".awaited" produces a tuple of results in the same order as the inputs.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// # Examples
///
/// Await for three different futures to complete:
///
/// ```
/// use zng_task as task;
///
/// # task::doc_test(false, async {
/// let (a, b, c) = task::all!(
/// task::run(async { 'a' }),
/// task::wait(|| "b"),
/// async { b"c" }
/// ).await;
/// # });
/// ```
#[macro_export]
macro_rules! all {
($fut0:expr $(,)?) => { $crate::__all! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__all! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__all; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __all {
($($ident:ident: $fut:expr;)+) => {
{
$(let mut $ident = (Some($fut), None);)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
let mut pending = false;
$(
if let Some(fut) = $ident.0.as_mut() {
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut fut = unsafe { std::pin::Pin::new_unchecked(fut) };
if let Poll::Ready(r) = fut.as_mut().poll(cx) {
$ident.0 = None;
$ident.1 = Some(r);
} else {
pending = true;
}
}
)+
if pending {
Poll::Pending
} else {
Poll::Ready(($($ident.1.take().unwrap()),+))
}
})
}
}
}
/// <span data-del-macro-root></span> A future that awaits for the first future that is ready.
///
/// The macro input is comma separated list of future expressions, the futures must
/// all have the same output type. The macro output is a future that when ".awaited" produces
/// a single output type instance returned by the first input future that completes.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// If two futures are ready at the same time the result of the first future in the input list is used.
/// After one future is ready the other futures are not polled again and are dropped.
///
/// # Examples
///
/// Await for the first of three futures to complete:
///
/// ```
/// use zng_task as task;
/// use zng_unit::*;
///
/// # task::doc_test(false, async {
/// let r = task::any!(
/// task::run(async { task::deadline(300.ms()).await; 'a' }),
/// task::wait(|| 'b'),
/// async { task::deadline(300.ms()).await; 'c' }
/// ).await;
///
/// assert_eq!('b', r);
/// # });
/// ```
#[macro_export]
macro_rules! any {
($fut0:expr $(,)?) => { $crate::__any! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__any! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__any; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __any {
($($ident:ident: $fut:expr;)+) => {
{
$(let mut $ident = $fut;)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
$(
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut $ident = unsafe { std::pin::Pin::new_unchecked(&mut $ident) };
if let Poll::Ready(r) = $ident.as_mut().poll(cx) {
return Poll::Ready(r)
}
)+
Poll::Pending
})
}
}
}
#[doc(hidden)]
pub use zng_task_proc_macros::task_any_all as __proc_any_all;
/// <span data-del-macro-root></span> A future that waits for the first future that is ready with an `Ok(T)` result.
///
/// The macro input is comma separated list of future expressions, the futures must
/// all have the same output `Result<T, E>` type, but each can have a different `E`. The macro output is a future
/// that when ".awaited" produces a single output of type `Result<T, (E0, E1, ..)>` that is `Ok(T)` if any of the futures
/// is `Ok(T)` or is `Err((E0, E1, ..))` is all futures are `Err`.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// If two futures are ready and `Ok(T)` at the same time the result of the first future in the input list is used.
/// After one future is ready and `Ok(T)` the other futures are not polled again and are dropped. After a future
/// is ready and `Err(E)` it is also not polled again and dropped.
///
/// # Examples
///
/// Await for the first of three futures to complete with `Ok`:
///
/// ```
/// use zng_task as task;
/// # #[derive(Debug, PartialEq)]
/// # pub struct FooError;
/// # task::doc_test(false, async {
/// let r = task::any_ok!(
/// task::run(async { Err::<char, _>("error") }),
/// task::wait(|| Ok::<_, FooError>('b')),
/// async { Err::<char, _>(FooError) }
/// ).await;
///
/// assert_eq!(Ok('b'), r);
/// # });
/// ```
#[macro_export]
macro_rules! any_ok {
($fut0:expr $(,)?) => { $crate::__any_ok! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__any_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__any_ok; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __any_ok {
($($ident:ident: $fut: expr;)+) => {
{
$(let mut $ident = (Some($fut), None);)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
let mut pending = false;
$(
if let Some(fut) = $ident.0.as_mut() {
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut fut = unsafe { std::pin::Pin::new_unchecked(fut) };
if let Poll::Ready(r) = fut.as_mut().poll(cx) {
match r {
Ok(r) => return Poll::Ready(Ok(r)),
Err(e) => {
$ident.0 = None;
$ident.1 = Some(e);
}
}
} else {
pending = true;
}
}
)+
if pending {
Poll::Pending
} else {
Poll::Ready(Err((
$($ident.1.take().unwrap()),+
)))
}
})
}
}
}
/// <span data-del-macro-root></span> A future that is ready when any of the futures is ready and `Some(T)`.
///
/// The macro input is comma separated list of future expressions, the futures must
/// all have the same output `Option<T>` type. The macro output is a future that when ".awaited" produces
/// a single output type instance returned by the first input future that completes with a `Some`.
/// If all futures complete with a `None` the output is `None`.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// If two futures are ready and `Some(T)` at the same time the result of the first future in the input list is used.
/// After one future is ready and `Some(T)` the other futures are not polled again and are dropped. After a future
/// is ready and `None` it is also not polled again and dropped.
///
/// # Examples
///
/// Await for the first of three futures to complete with `Some`:
///
/// ```
/// use zng_task as task;
/// # task::doc_test(false, async {
/// let r = task::any_some!(
/// task::run(async { None::<char> }),
/// task::wait(|| Some('b')),
/// async { None::<char> }
/// ).await;
///
/// assert_eq!(Some('b'), r);
/// # });
/// ```
#[macro_export]
macro_rules! any_some {
($fut0:expr $(,)?) => { $crate::__any_some! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__any_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__any_some; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __any_some {
($($ident:ident: $fut: expr;)+) => {
{
$(let mut $ident = Some($fut);)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
let mut pending = false;
$(
if let Some(fut) = $ident.as_mut() {
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut fut = unsafe { std::pin::Pin::new_unchecked(fut) };
if let Poll::Ready(r) = fut.as_mut().poll(cx) {
if let Some(r) = r {
return Poll::Ready(Some(r));
}
$ident = None;
} else {
pending = true;
}
}
)+
if pending {
Poll::Pending
} else {
Poll::Ready(None)
}
})
}
}
}
/// <span data-del-macro-root></span> A future that is ready when all futures are ready with an `Ok(T)` result or
/// any future is ready with an `Err(E)` result.
///
/// The output type is `Result<(T0, T1, ..), E>`, the `Ok` type is a tuple with all the `Ok` values, the error
/// type is the first error encountered, the input futures must have the same `Err` type but can have different
/// `Ok` types.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// If two futures are ready and `Err(E)` at the same time the result of the first future in the input list is used.
/// After one future is ready and `Err(T)` the other futures are not polled again and are dropped. After a future
/// is ready it is also not polled again and dropped.
///
/// # Examples
///
/// Await for the first of three futures to complete with `Ok(T)`:
///
/// ```
/// use zng_task as task;
/// # #[derive(Debug, PartialEq)]
/// # struct FooError;
/// # task::doc_test(false, async {
/// let r = task::all_ok!(
/// task::run(async { Ok::<_, FooError>('a') }),
/// task::wait(|| Ok::<_, FooError>('b')),
/// async { Ok::<_, FooError>('c') }
/// ).await;
///
/// assert_eq!(Ok(('a', 'b', 'c')), r);
/// # });
/// ```
///
/// And in if any completes with `Err(E)`:
///
/// ```
/// use zng_task as task;
/// # #[derive(Debug, PartialEq)]
/// # struct FooError;
/// # task::doc_test(false, async {
/// let r = task::all_ok!(
/// task::run(async { Ok('a') }),
/// task::wait(|| Err::<char, _>(FooError)),
/// async { Ok('c') }
/// ).await;
///
/// assert_eq!(Err(FooError), r);
/// # });
#[macro_export]
macro_rules! all_ok {
($fut0:expr $(,)?) => { $crate::__all_ok! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__all_ok! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__all_ok; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __all_ok {
($($ident:ident: $fut: expr;)+) => {
{
$(let mut $ident = (Some($fut), None);)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
let mut pending = false;
$(
if let Some(fut) = $ident.0.as_mut() {
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut fut = unsafe { std::pin::Pin::new_unchecked(fut) };
if let Poll::Ready(r) = fut.as_mut().poll(cx) {
match r {
Ok(r) => {
$ident.0 = None;
$ident.1 = Some(r);
},
Err(e) => return Poll::Ready(Err(e)),
}
} else {
pending = true;
}
}
)+
if pending {
Poll::Pending
} else {
Poll::Ready(Ok((
$($ident.1.take().unwrap()),+
)))
}
})
}
}
}
/// <span data-del-macro-root></span> A future that is ready when all futures are ready with `Some(T)` or when any
/// is future ready with `None`.
///
/// The macro input is comma separated list of future expressions, the futures must
/// all have the `Option<T>` output type, but each can have a different `T`. The macro output is a future that when ".awaited"
/// produces `Some<(T0, T1, ..)>` if all futures where `Some(T)` or `None` if any of the futures where `None`.
///
/// At least one input future is required and any number of futures is accepted. For more than
/// eight futures a proc-macro is used which may cause code auto-complete to stop working in
/// some IDEs.
///
/// After one future is ready and `None` the other futures are not polled again and are dropped. After a future
/// is ready it is also not polled again and dropped.
///
/// # Examples
///
/// Await for the first of three futures to complete with `Some`:
///
/// ```
/// use zng_task as task;
/// # task::doc_test(false, async {
/// let r = task::all_some!(
/// task::run(async { Some('a') }),
/// task::wait(|| Some('b')),
/// async { Some('c') }
/// ).await;
///
/// assert_eq!(Some(('a', 'b', 'c')), r);
/// # });
/// ```
///
/// Completes with `None` if any future completes with `None`:
///
/// ```
/// # use zng_task as task;
/// # task::doc_test(false, async {
/// let r = task::all_some!(
/// task::run(async { Some('a') }),
/// task::wait(|| None::<char>),
/// async { Some('b') }
/// ).await;
///
/// assert_eq!(None, r);
/// # });
/// ```
#[macro_export]
macro_rules! all_some {
($fut0:expr $(,)?) => { $crate::__all_some! { fut0: $fut0; } };
($fut0:expr, $fut1:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
}
};
($fut0:expr, $fut1:expr, $fut2:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
}
};
($fut0:expr, $fut1:expr, $fut2:expr, $fut3:expr, $fut4:expr, $fut5:expr, $fut6:expr, $fut7:expr $(,)?) => {
$crate::__all_some! {
fut0: $fut0;
fut1: $fut1;
fut2: $fut2;
fut3: $fut3;
fut4: $fut4;
fut5: $fut5;
fut6: $fut6;
fut7: $fut7;
}
};
($($fut:expr),+ $(,)?) => { $crate::__proc_any_all!{ $crate::__all_some; $($fut),+ } }
}
#[doc(hidden)]
#[macro_export]
macro_rules! __all_some {
($($ident:ident: $fut: expr;)+) => {
{
$(let mut $ident = (Some($fut), None);)+
$crate::future_fn(move |cx| {
use std::task::Poll;
use std::future::Future;
let mut pending = false;
$(
if let Some(fut) = $ident.0.as_mut() {
// SAFETY: the closure owns $ident and is an exclusive borrow inside a
// Future::poll call, so it will not move.
let mut fut = unsafe { std::pin::Pin::new_unchecked(fut) };
if let Poll::Ready(r) = fut.as_mut().poll(cx) {
if r.is_none() {
return Poll::Ready(None);
}
$ident.0 = None;
$ident.1 = r;
} else {
pending = true;
}
}
)+
if pending {
Poll::Pending
} else {
Poll::Ready(Some((
$($ident.1.take().unwrap()),+
)))
}
})
}
}
}
/// A future that will await until [`set`] is called.
///
/// # Examples
///
/// Spawns a parallel task that only writes to stdout after the main thread sets the signal:
///
/// ```
/// use zng_task::{self as task, *};
/// use zng_clone_move::async_clmv;
///
/// let signal = SignalOnce::default();
///
/// task::spawn(async_clmv!(signal, {
/// signal.await;
/// println!("After Signal!");
/// }));
///
/// signal.set();
/// ```
///
/// [`set`]: SignalOnce::set
#[derive(Default, Clone)]
pub struct SignalOnce(Arc<SignalInner>);
impl fmt::Debug for SignalOnce {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SignalOnce({})", self.is_set())
}
}
impl PartialEq for SignalOnce {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for SignalOnce {}
impl Hash for SignalOnce {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state)
}
}
impl SignalOnce {
/// New unsigned.
pub fn new() -> Self {
Self::default()
}
/// New signaled.
pub fn new_set() -> Self {
let s = Self::new();
s.set();
s
}
/// If the signal was set.
pub fn is_set(&self) -> bool {
self.0.signaled.load(Ordering::Relaxed)
}
/// Sets the signal and awakes listeners.
pub fn set(&self) {
if !self.0.signaled.swap(true, Ordering::Relaxed) {
let listeners = mem::take(&mut *self.0.listeners.lock());
for listener in listeners {
listener.wake();
}
}
}
}
impl Future for SignalOnce {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<()> {
if self.as_ref().is_set() {
Poll::Ready(())
} else {
let mut listeners = self.0.listeners.lock();
let waker = cx.waker();
if !listeners.iter().any(|w| w.will_wake(waker)) {
listeners.push(waker.clone());
}
Poll::Pending
}
}
}
#[derive(Default)]
struct SignalInner {
signaled: AtomicBool,
listeners: Mutex<Vec<std::task::Waker>>,
}
/// A [`Waker`] that dispatches a wake call to multiple other wakers.
///
/// This is useful for sharing one wake source with multiple [`Waker`] clients that may not be all
/// known at the moment the first request is made.
///
/// [`Waker`]: std::task::Waker
#[derive(Clone)]
pub struct McWaker(Arc<WakeVec>);
#[derive(Default)]
struct WakeVec(Mutex<Vec<std::task::Waker>>);
impl WakeVec {
fn push(&self, waker: std::task::Waker) -> bool {
let mut v = self.0.lock();
let return_waker = v.is_empty();
v.push(waker);
return_waker
}
fn cancel(&self) {
let mut v = self.0.lock();
debug_assert!(!v.is_empty(), "called cancel on an empty McWaker");
v.clear();
}
}
impl std::task::Wake for WakeVec {
fn wake(self: Arc<Self>) {
for w in mem::take(&mut *self.0.lock()) {
w.wake();
}
}
}
impl McWaker {
/// New empty waker.
pub fn empty() -> Self {
Self(Arc::new(WakeVec::default()))
}
/// Register a `waker` to wake once when `self` awakes.
///
/// Returns `Some(self as waker)` if `self` was previously empty, if `None` is returned [`Poll::Pending`] must
/// be returned, if a waker is returned the shared resource must be polled using the waker, if the shared resource
/// is ready [`cancel`] must be called.
///
/// [`cancel`]: Self::cancel
pub fn push(&self, waker: std::task::Waker) -> Option<std::task::Waker> {
if self.0.push(waker) {
Some(self.0.clone().into())
} else {
None
}
}
/// Clear current registered wakers.
pub fn cancel(&self) {
self.0.cancel()
}
}