What changed, and why it matters
This commit introduces a new asynchronous task engine into the BitBox02 firmware. It vendors third-party Rust libraries (async-task, concurrent-queue, crossbeam-utils) and adds a custom executor plus a small demo that shows an orientation screen and a delay. There is no indication in the commit message, diff, or supplied references that this change fixes or introduces a security vulnerability; it appears to be a routine architectural/feature addition.
No security action required. Treat as a normal feature commit. If auditing the new async engine for security later, focus on executor correctness, waker/reference-counting soundness, and safe FFI boundaries between C and Rust.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit adds an initial async runtime: vendored crates async-task 4.7.1, concurrent-queue, and crossbeam-utils; a new bitbox-executor crate; delay bindings; and integration in the Rust main loop and orientation workflow. The diff is almost entirely new third-party code and plumbing. No security-relevant bug fixes, bounds checks, cryptographic changes, or incident disclosures are present in the provided materials.
Changed components
src/rust/bitbox-executorsrc/rust/bitbox02-rust/src/main_loop.rssrc/rust/bitbox02-rust/src/workflow/orientation_screen.rssrc/rust/bitbox02/src/delay.rssrc/rust/bitbox02/src/ui/ui.rsexternal/vendor/async-taskexternal/vendor/concurrent-queueexternal/vendor/crossbeam-utilsInspect captured patch +16609 / −178
diff --git a/external/vendor/async-task/.cargo-checksum.json b/external/vendor/async-task/.cargo-checksum.json
new file mode 100644
index 0000000..09c7726
--- /dev/null
+++ b/external/vendor/async-task/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"06e5796b3db8767807a59ab26c05cc4cd16b3be327edea4c6407f172db41ce7b","CHANGELOG.md":"8433fdce250bdc1864320a7eaab940261a9d74c9fdd42d97591d4708a81831f6","Cargo.lock":"724f4923c3a914b938ee5769bbf9bc35cd7261d129406fae00777a5e66e79416","Cargo.toml":"1ee0e30526e13349dafcd286676747fbbe1b6e876ec28dafa735ae0f603600e7","Cargo.toml.orig":"d94de6be0f8ab5af18a17337a6d93c6adeb47f28cf917b9ba0c709cff9095390","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"91a65b44a1692a16fa2d2f5bb424e78177f0c0ca0051e93db20443568377d5e5","benches/spawn.rs":"9272992dbc058734be04e4b1c0c92fa16f62eebe062c2ce74bbedfae1ce36689","examples/spawn-local.rs":"729d6b8ef55fad9387e8912567160766fb00c3880a7acbdcab7316aefe7811c3","examples/spawn-on-thread.rs":"90c5ffcbe11b847a9201a83ac2f036bf1721dfe971708781a0769ef8354e87c9","examples/spawn.rs":"360c86d609eea98333ba6284ebf8eeb73acc651f07d30b0dd5879757b4bf6125","examples/with-metadata.rs":"c5cb1f101d7320df6d7b6e3a82d5483b94b2e47523387a910facf5c390e535e3","src/header.rs":"d7486c5528b7fb4b372e66e73923747efe052d1318edc6a0797f00fa20b0b2e3","src/lib.rs":"195df753931d1259f6325789f111e79b833432c2925b7f8a90d94ab82b6cd9fe","src/raw.rs":"5879172e761591fee44293537ed134f794c42c873afdd5ccb1107a8dc7ccce6c","src/runnable.rs":"e12bec98bc1aa2f10194c85c7b022807cd5e1abd95a37db93bd5b06ced8d1a28","src/state.rs":"73ec4b98e8519faad882c1ee19711066a9e2a9b2cf9441436f145c8597e2b93d","src/task.rs":"8899dc897b21220a19134ae3755eefefeda55f18a56e32145c2a97d69be60fb6","src/utils.rs":"bc6a0073b07f50f3495962b77afd64c38a0b4ec4e5f2d7e875f72e92254a7dd3","tests/basic.rs":"081729ff928214edcdc2550644708e2571f127e59afc24fdc8af94e2e2cc441c","tests/cancel.rs":"6ffd2e52e3846e20b5221b1509fe718e187652302e8723c9751c1c7921109201","tests/join.rs":"47ae65d842d658a0d8f821535e67160a906f8182373f1780f364314371f99bae","tests/metadata.rs":"33b1d406d4f834671524cbc0c27edb6d6fb95ef16440c24329dfb1aff0db5e76","tests/panic.rs":"d5bd73f8d697277ed0a8193769e3a88989285deff08a111f3b149fd1aa760e65","tests/ready.rs":"45c8562bbbe3837f22129b42ffef734be4572366ff3c3ce6aae1e593f558d429","tests/waker_panic.rs":"6f1ac597ab8df2a8452eface16dec48a150d87770fd6afc3965f36f6c84a7dbb","tests/waker_pending.rs":"8b65a64d00fb3f2e33b8ed9db296b9a2aa8110a44eba7a899bab8dfecb902f5a","tests/waker_ready.rs":"abbc78ecb291e894f6805b18ca3c2945b3f2bc9da6ec918ffa5ab9d27a759b5a"},"package":"8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"}
\ No newline at end of file
diff --git a/external/vendor/async-task/.cargo_vcs_info.json b/external/vendor/async-task/.cargo_vcs_info.json
new file mode 100644
index 0000000..0f2f0f8
--- /dev/null
+++ b/external/vendor/async-task/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "3065c372e1ef1611230195ad7f3aae80ffde8261"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
diff --git a/external/vendor/async-task/CHANGELOG.md b/external/vendor/async-task/CHANGELOG.md
new file mode 100644
index 0000000..0324dca
--- /dev/null
+++ b/external/vendor/async-task/CHANGELOG.md
@@ -0,0 +1,112 @@
+# Version 4.7.1
+
+- Improve the panic message for when a task is polled after completion. (#73)
+
+# Version 4.7.0
+
+- Add `from_raw` and `into_raw` functions for `Runnable` to ease passing it
+ across an FFI boundary. (#65)
+
+# Version 4.6.0
+
+- Bump MSRV to 1.57. (#63)
+- Task layout computation failures are now a compile-time error instead of a
+ runtime abort. (#63)
+
+# Version 4.5.0
+
+- Add a `portable-atomic` feature that enables the usage of fallback primitives for CPUs without atomics. (#58)
+
+# Version 4.4.1
+
+- Clarify safety documentation for `spawn_unchecked`. (#49)
+
+# Version 4.4.0
+
+- Ensure that the allocation doesn't exceed `isize::MAX` (#32)
+- Add `FallibleTask::is_finished()` (#34)
+- Add a metadata generic parameter to tasks (#33)
+- Add panic propagation to tasks (#37)
+- Add a way to tell if the task was woken while running from the schedule function (#42)
+
+# Version 4.3.0
+
+- Bump MSRV to Rust 1.47. (#30)
+- Evaluate the layouts for the tasks at compile time. (#30)
+- Add layout_info field to TaskVTable so that debuggers can decode raw tasks. (#29)
+
+# Version 4.2.0
+
+- Add `Task::is_finished`. (#19)
+
+# Version 4.1.0
+
+- Add `FallibleTask`. (#21)
+
+# Version 4.0.3
+
+- Document the return value of `Runnable::run()` better.
+
+# Version 4.0.2
+
+- Nits in the docs.
+
+# Version 4.0.1
+
+- Nits in the docs.
+
+# Version 4.0.0
+
+- Rename `Task` to `Runnable`.
+- Rename `JoinHandle` to `Task`.
+- Cancel `Task` on drop.
+- Add `Task::detach()` and `Task::cancel()`.
+- Add `spawn_unchecked()`.
+
+# Version 3.0.0
+
+- Use `ThreadId` in `spawn_local` because OS-provided IDs can get recycled.
+- Add `std` feature to `Cargo.toml`.
+
+# Version 2.1.1
+
+- Allocate large futures on the heap.
+
+# Version 2.1.0
+
+- `JoinHandle` now only evaluates after the task's future has been dropped.
+
+# Version 2.0.0
+
+- Return `true` in `Task::run()`.
+
+# Version 1.3.1
+
+- Make `spawn_local` available only on unix and windows.
+
+# Version 1.3.0
+
+- Add `waker_fn`.
+
+# Version 1.2.1
+
+- Add the `no-std` category to the package.
+
+# Version 1.2.0
+
+- The crate is now marked with `#![no_std]`.
+- Add `Task::waker` and `JoinHandle::waker`.
+- Add `Task::into_raw` and `Task::from_raw`.
+
+# Version 1.1.1
+
+- Fix a use-after-free bug where the schedule function is dropped while running.
+
+# Version 1.1.0
+
+- If a task is dropped or canceled outside the `run` method, it gets re-scheduled.
+- Add `spawn_local` constructor.
+
+# Version 1.0.0
+
+- Initial release
diff --git a/external/vendor/async-task/Cargo.lock b/external/vendor/async-task/Cargo.lock
new file mode 100644
index 0000000..109a580
--- /dev/null
+++ b/external/vendor/async-task/Cargo.lock
@@ -0,0 +1,665 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "async-channel"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ca33f4bc4ed1babef42cad36cc1f51fa88be00420404e5b1e80ab1b18f7678c"
+dependencies = [
+ "concurrent-queue",
+ "event-listener 4.0.1",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-executor"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17ae5ebefcc48e7452b4987947920dac9450be1110cadf34d1b8c116bdbaf97c"
+dependencies = [
+ "async-lock 3.2.0",
+ "async-task 4.7.0",
+ "concurrent-queue",
+ "fastrand",
+ "futures-lite",
+ "slab",
+]
+
+[[package]]
+name = "async-fs"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc19683171f287921f2405677dd2ed2549c3b3bda697a563ebc3a121ace2aba1"
+dependencies = [
+ "async-lock 3.2.0",
+ "blocking",
+ "futures-lite",
+]
+
+[[package]]
+name = "async-io"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6afaa937395a620e33dc6a742c593c01aced20aa376ffb0f628121198578ccc7"
+dependencies = [
+ "async-lock 3.2.0",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix",
+ "slab",
+ "tracing",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "async-lock"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b"
+dependencies = [
+ "event-listener 2.5.3",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7125e42787d53db9dd54261812ef17e937c95a51e4d291373b670342fa44310c"
+dependencies = [
+ "event-listener 4.0.1",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-net"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"
+dependencies = [
+ "async-io",
+ "blocking",
+ "futures-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a53fc6301894e04a92cb2584fedde80cb25ba8e02d9dc39d4a87d036e22f397d"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock 3.2.0",
+ "async-signal",
+ "async-task 4.7.0",
+ "blocking",
+ "cfg-if",
+ "event-listener 5.3.0",
+ "futures-lite",
+ "rustix",
+ "tracing",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e47d90f65a225c4527103a8d747001fc56e375203592b25ad103e1ca13124c5"
+dependencies = [
+ "async-io",
+ "async-lock 2.8.0",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbb36e985947064623dbd357f727af08ffd077f93d696782f3c56365fa2e2799"
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+dependencies = [
+ "atomic-waker",
+ "easy-parallel",
+ "flaky_test",
+ "flume",
+ "futures-lite",
+ "once_cell",
+ "pin-project-lite",
+ "portable-atomic",
+ "smol",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+
+[[package]]
+name = "bitflags"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
+
+[[package]]
+name = "blocking"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a37913e8dc4ddcc604f0c6d3bf2887c995153af3611de9e23c352b44c1b9118"
+dependencies = [
+ "async-channel",
+ "async-lock 3.2.0",
+ "async-task 4.7.0",
+ "fastrand",
+ "futures-io",
+ "futures-lite",
+ "piper",
+ "tracing",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "concurrent-queue"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d16048cd947b08fa32c24458a22f5dc5e835264f689f4f5653210c69fd107363"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c06d96137f14f244c37f989d9fff8f95e6c18b918e71f36638f8c49112e4c78f"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "easy-parallel"
+version = "3.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2afbb9b0aef60e4f0d2b18129b6c0dff035a6f7dbbd17c2f38c1432102ee223c"
+
+[[package]]
+name = "errno"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "event-listener"
+version = "2.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
+
+[[package]]
+name = "event-listener"
+version = "4.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84f2cdcf274580f2d63697192d744727b3198894b1bf02923643bf59e2c26712"
+dependencies = [
+ "concurrent-queue",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d9944b8ca13534cdfb2800775f8dd4902ff3fc75a50101466decadfdf322a24"
+dependencies = [
+ "concurrent-queue",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "958e4d70b6d5e81971bebec42271ec641e7ff4e170a6fa605f2b8a8b65cb97d3"
+dependencies = [
+ "event-listener 4.0.1",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
+
+[[package]]
+name = "flaky_test"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046caa1f23d7f751fc4ead3d6669a77fa5fc6cf6074960ddeb6a0b0a5b83c8da"
+dependencies = [
+ "flaky_test_impl",
+ "futures-util",
+]
+
+[[package]]
+name = "flaky_test_impl"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85e35909c2f0552fdae5b40f1e95a7da12afb58c1f2f455a12c216c58d869abe"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "flume"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55ac459de2512911e4b674ce33cf20befaba382d05b62b008afc1c8b57cbf181"
+dependencies = [
+ "spin",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb1d22c66e66d9d72e1758f0bd7d4fd0bee04cad842ee34587d68c07e45d088c"
+
+[[package]]
+name = "futures-io"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bf34a163b5c4c52d0478a4d757da8fb65cabef42ba90515efee0f6f9fa45aaa"
+
+[[package]]
+name = "futures-lite"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aeee267a1883f7ebef3700f262d2d54de95dfaf38189015a74fdc4e0c7ad8143"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "futures-task"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
+
+[[package]]
+name = "futures-util"
+version = "0.3.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a19526d624e703a3179b3d322efec918b6246ea0fa51d41124525f00f1cc8104"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456"
+
+[[package]]
+name = "lock_api"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+
+[[package]]
+name = "parking"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb813b8af86854136c6922af0598d719255ecb2179515e6e7730d468f05c9cae"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "piper"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "668d31b1c4eba19242f2088b2bf3316b82ca31082a8335764db4e083db7485d4"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
+[[package]]
+name = "polling"
+version = "3.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf63fa624ab313c11656b4cda960bfc46c410187ad493c41f6ba2d8c1e991c9e"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "pin-project-lite",
+ "rustix",
+ "tracing",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.70"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39278fbbf5fb4f646ce651690877f89d1c5811a3d4acb27700c1cb3cdb78fd3b"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smol"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e635339259e51ef85ac7aa29a1cd991b957047507288697a690e80ab97d07cad"
+dependencies = [
+ "async-channel",
+ "async-executor",
+ "async-fs",
+ "async-io",
+ "async-lock 3.2.0",
+ "async-net",
+ "async-process",
+ "blocking",
+ "futures-lite",
+]
+
+[[package]]
+name = "spin"
+version = "0.9.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
+dependencies = [
+ "lock_api",
+]
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tracing"
+version = "0.1.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "windows-sys"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+dependencies = [
+ "windows-targets 0.48.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.0",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
+dependencies = [
+ "windows_aarch64_gnullvm 0.48.5",
+ "windows_aarch64_msvc 0.48.5",
+ "windows_i686_gnu 0.48.5",
+ "windows_i686_msvc 0.48.5",
+ "windows_x86_64_gnu 0.48.5",
+ "windows_x86_64_gnullvm 0.48.5",
+ "windows_x86_64_msvc 0.48.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.0",
+ "windows_aarch64_msvc 0.52.0",
+ "windows_i686_gnu 0.52.0",
+ "windows_i686_msvc 0.52.0",
+ "windows_x86_64_gnu 0.52.0",
+ "windows_x86_64_gnullvm 0.52.0",
+ "windows_x86_64_msvc 0.52.0",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"
diff --git a/external/vendor/async-task/Cargo.toml b/external/vendor/async-task/Cargo.toml
new file mode 100644
index 0000000..7719f42
--- /dev/null
+++ b/external/vendor/async-task/Cargo.toml
@@ -0,0 +1,67 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.57"
+name = "async-task"
+version = "4.7.1"
+authors = ["Stjepan Glavina <stjepang@gmail.com>"]
+exclude = ["/.*"]
+description = "Task abstraction for building executors"
+readme = "README.md"
+keywords = [
+ "futures",
+ "task",
+ "executor",
+ "spawn",
+]
+categories = [
+ "asynchronous",
+ "concurrency",
+ "no-std",
+]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/async-task"
+
+[dependencies.portable-atomic]
+version = "1"
+optional = true
+default-features = false
+
+[dev-dependencies.atomic-waker]
+version = "1"
+
+[dev-dependencies.easy-parallel]
+version = "3"
+
+[dev-dependencies.flaky_test]
+version = "0.2"
+
+[dev-dependencies.flume]
+version = "0.11"
+default-features = false
+
+[dev-dependencies.futures-lite]
+version = "2.0.0"
+
+[dev-dependencies.once_cell]
+version = "1"
+
+[dev-dependencies.pin-project-lite]
+version = "0.2.10"
+
+[dev-dependencies.smol]
+version = "2"
+
+[features]
+default = ["std"]
+std = []
diff --git a/external/vendor/async-task/Cargo.toml.orig b/external/vendor/async-task/Cargo.toml.orig
new file mode 100644
index 0000000..7779a6a
--- /dev/null
+++ b/external/vendor/async-task/Cargo.toml.orig
@@ -0,0 +1,37 @@
+[package]
+name = "async-task"
+# When publishing a new version:
+# - Update CHANGELOG.md
+# - Create "v4.x.y" git tag
+version = "4.7.1"
+authors = ["Stjepan Glavina <stjepang@gmail.com>"]
+edition = "2021"
+rust-version = "1.57"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/async-task"
+description = "Task abstraction for building executors"
+keywords = ["futures", "task", "executor", "spawn"]
+categories = ["asynchronous", "concurrency", "no-std"]
+exclude = ["/.*"]
+
+[features]
+default = ["std"]
+std = []
+
+[dependencies]
+# Uses portable-atomic polyfill atomics on targets without them
+portable-atomic = { version = "1", optional = true, default-features = false }
+
+[dev-dependencies]
+atomic-waker = "1"
+easy-parallel = "3"
+flaky_test = "0.2"
+flume = { version = "0.11", default-features = false }
+futures-lite = "2.0.0"
+once_cell = "1"
+pin-project-lite = "0.2.10"
+smol = "2"
+
+# rewrite dependencies to use the this version of async-task when running tests
+[patch.crates-io]
+async-task = { path = "." }
diff --git a/external/vendor/async-task/LICENSE-APACHE b/external/vendor/async-task/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/external/vendor/async-task/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/external/vendor/async-task/LICENSE-MIT b/external/vendor/async-task/LICENSE-MIT
new file mode 100644
index 0000000..31aa793
--- /dev/null
+++ b/external/vendor/async-task/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/external/vendor/async-task/README.md b/external/vendor/async-task/README.md
new file mode 100644
index 0000000..7044c9d
--- /dev/null
+++ b/external/vendor/async-task/README.md
@@ -0,0 +1,69 @@
+# async-task
+
+[](
+https://github.com/smol-rs/async-task/actions)
+[](
+https://github.com/smol-rs/async-task)
+[](
+https://crates.io/crates/async-task)
+[](
+https://docs.rs/async-task)
+
+Task abstraction for building executors.
+
+To spawn a future onto an executor, we first need to allocate it on the heap and keep some
+state attached to it. The state indicates whether the future is ready for polling, waiting to
+be woken up, or completed. Such a stateful future is called a *task*.
+
+All executors have a queue that holds scheduled tasks:
+
+```rust
+let (sender, receiver) = flume::unbounded();
+```
+
+A task is created using either `spawn()`, `spawn_local()`, or `spawn_unchecked()` which
+return a `Runnable` and a `Task`:
+
+```rust
+// A future that will be spawned.
+let future = async { 1 + 2 };
+
+// A function that schedules the task when it gets woken up.
+let schedule = move |runnable| sender.send(runnable).unwrap();
+
+// Construct a task.
+let (runnable, task) = async_task::spawn(future, schedule);
+
+// Push the task into the queue by invoking its schedule function.
+runnable.schedule();
+```
+
+The `Runnable` is used to poll the task's future, and the `Task` is used to await its
+output.
+
+Finally, we need a loop that takes scheduled tasks from the queue and runs them:
+
+```rust
+for runnable in receiver {
+ runnable.run();
+}
+```
+
+Method `run()` polls the task's future once. Then, the `Runnable`
+vanishes and only reappears when its `Waker` wakes the task, thus
+scheduling it to be run again.
+
+## License
+
+Licensed under either of
+
+ * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
+ * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
+
+at your option.
+
+#### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
+dual licensed as above, without any additional terms or conditions.
diff --git a/external/vendor/async-task/benches/spawn.rs b/external/vendor/async-task/benches/spawn.rs
new file mode 100644
index 0000000..75d059e
--- /dev/null
+++ b/external/vendor/async-task/benches/spawn.rs
@@ -0,0 +1,22 @@
+#![feature(test)]
+
+extern crate test;
+
+use smol::future;
+use test::Bencher;
+
+#[bench]
+fn task_create(b: &mut Bencher) {
+ b.iter(|| {
+ let _ = async_task::spawn(async {}, drop);
+ });
+}
+
+#[bench]
+fn task_run(b: &mut Bencher) {
+ b.iter(|| {
+ let (runnable, task) = async_task::spawn(async {}, drop);
+ runnable.run();
+ future::block_on(task);
+ });
+}
diff --git a/external/vendor/async-task/examples/spawn-local.rs b/external/vendor/async-task/examples/spawn-local.rs
new file mode 100644
index 0000000..a9da1b4
--- /dev/null
+++ b/external/vendor/async-task/examples/spawn-local.rs
@@ -0,0 +1,73 @@
+//! A simple single-threaded executor that can spawn non-`Send` futures.
+
+use std::cell::Cell;
+use std::future::Future;
+use std::rc::Rc;
+
+use async_task::{Runnable, Task};
+
+thread_local! {
+ // A queue that holds scheduled tasks.
+ static QUEUE: (flume::Sender<Runnable>, flume::Receiver<Runnable>) = flume::unbounded();
+}
+
+/// Spawns a future on the executor.
+fn spawn<F, T>(future: F) -> Task<T>
+where
+ F: Future<Output = T> + 'static,
+ T: 'static,
+{
+ // Create a task that is scheduled by pushing itself into the queue.
+ let schedule = |runnable| QUEUE.with(|(s, _)| s.send(runnable).unwrap());
+ let (runnable, task) = async_task::spawn_local(future, schedule);
+
+ // Schedule the task by pushing it into the queue.
+ runnable.schedule();
+
+ task
+}
+
+/// Runs a future to completion.
+fn run<F, T>(future: F) -> T
+where
+ F: Future<Output = T> + 'static,
+ T: 'static,
+{
+ // Spawn a task that sends its result through a channel.
+ let (s, r) = flume::unbounded();
+ spawn(async move { drop(s.send(future.await)) }).detach();
+
+ loop {
+ // If the original task has completed, return its result.
+ if let Ok(val) = r.try_recv() {
+ return val;
+ }
+
+ // Otherwise, take a task from the queue and run it.
+ QUEUE.with(|(_, r)| r.recv().unwrap().run());
+ }
+}
+
+fn main() {
+ let val = Rc::new(Cell::new(0));
+
+ // Run a future that increments a non-`Send` value.
+ run({
+ let val = val.clone();
+ async move {
+ // Spawn a future that increments the value.
+ let task = spawn({
+ let val = val.clone();
+ async move {
+ val.set(dbg!(val.get()) + 1);
+ }
+ });
+
+ val.set(dbg!(val.get()) + 1);
+ task.await;
+ }
+ });
+
+ // The value should be 2 at the end of the program.
+ dbg!(val.get());
+}
diff --git a/external/vendor/async-task/examples/spawn-on-thread.rs b/external/vendor/async-task/examples/spawn-on-thread.rs
new file mode 100644
index 0000000..b0ec2f2
--- /dev/null
+++ b/external/vendor/async-task/examples/spawn-on-thread.rs
@@ -0,0 +1,53 @@
+//! A function that runs a future to completion on a dedicated thread.
+
+use std::future::Future;
+use std::sync::Arc;
+use std::thread;
+
+use async_task::Task;
+use smol::future;
+
+/// Spawns a future on a new dedicated thread.
+///
+/// The returned task can be used to await the output of the future.
+fn spawn_on_thread<F, T>(future: F) -> Task<T>
+where
+ F: Future<Output = T> + Send + 'static,
+ T: Send + 'static,
+{
+ // Create a channel that holds the task when it is scheduled for running.
+ let (sender, receiver) = flume::unbounded();
+ let sender = Arc::new(sender);
+ let s = Arc::downgrade(&sender);
+
+ // Wrap the future into one that disconnects the channel on completion.
+ let future = async move {
+ // When the inner future completes, the sender gets dropped and disconnects the channel.
+ let _sender = sender;
+ future.await
+ };
+
+ // Create a task that is scheduled by sending it into the channel.
+ let schedule = move |runnable| s.upgrade().unwrap().send(runnable).unwrap();
+ let (runnable, task) = async_task::spawn(future, schedule);
+
+ // Schedule the task by sending it into the channel.
+ runnable.schedule();
+
+ // Spawn a thread running the task to completion.
+ thread::spawn(move || {
+ // Keep taking the task from the channel and running it until completion.
+ for runnable in receiver {
+ runnable.run();
+ }
+ });
+
+ task
+}
+
+fn main() {
+ // Spawn a future on a dedicated thread.
+ future::block_on(spawn_on_thread(async {
+ println!("Hello, world!");
+ }));
+}
diff --git a/external/vendor/async-task/examples/spawn.rs b/external/vendor/async-task/examples/spawn.rs
new file mode 100644
index 0000000..3a64811
--- /dev/null
+++ b/external/vendor/async-task/examples/spawn.rs
@@ -0,0 +1,48 @@
+//! A simple single-threaded executor.
+
+use std::future::Future;
+use std::panic::catch_unwind;
+use std::thread;
+
+use async_task::{Runnable, Task};
+use once_cell::sync::Lazy;
+use smol::future;
+
+/// Spawns a future on the executor.
+fn spawn<F, T>(future: F) -> Task<T>
+where
+ F: Future<Output = T> + Send + 'static,
+ T: Send + 'static,
+{
+ // A queue that holds scheduled tasks.
+ static QUEUE: Lazy<flume::Sender<Runnable>> = Lazy::new(|| {
+ let (sender, receiver) = flume::unbounded::<Runnable>();
+
+ // Start the executor thread.
+ thread::spawn(|| {
+ for runnable in receiver {
+ // Ignore panics inside futures.
+ let _ignore_panic = catch_unwind(|| runnable.run());
+ }
+ });
+
+ sender
+ });
+
+ // Create a task that is scheduled by pushing it into the queue.
+ let schedule = |runnable| QUEUE.send(runnable).unwrap();
+ let (runnable, task) = async_task::spawn(future, schedule);
+
+ // Schedule the task by pushing it into the queue.
+ runnable.schedule();
+
+ task
+}
+
+fn main() {
+ // Spawn a future and await its result.
+ let task = spawn(async {
+ println!("Hello, world!");
+ });
+ future::block_on(task);
+}
diff --git a/external/vendor/async-task/examples/with-metadata.rs b/external/vendor/async-task/examples/with-metadata.rs
new file mode 100644
index 0000000..ed84e31
--- /dev/null
+++ b/external/vendor/async-task/examples/with-metadata.rs
@@ -0,0 +1,145 @@
+//! A single threaded executor that uses shortest-job-first scheduling.
+
+use std::cell::RefCell;
+use std::collections::BinaryHeap;
+use std::pin::Pin;
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::{Duration, Instant};
+use std::{cell::Cell, future::Future};
+
+use async_task::{Builder, Runnable, Task};
+use pin_project_lite::pin_project;
+use smol::{channel, future};
+
+struct ByDuration(Runnable<DurationMetadata>);
+
+impl ByDuration {
+ fn duration(&self) -> Duration {
+ self.0.metadata().inner.get()
+ }
+}
+
+impl PartialEq for ByDuration {
+ fn eq(&self, other: &Self) -> bool {
+ self.duration() == other.duration()
+ }
+}
+
+impl Eq for ByDuration {}
+
+impl PartialOrd for ByDuration {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for ByDuration {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.duration().cmp(&other.duration()).reverse()
+ }
+}
+
+pin_project! {
+ #[must_use = "futures do nothing unless you `.await` or poll them"]
+ struct MeasureRuntime<'a, F> {
+ #[pin]
+ f: F,
+ duration: &'a Cell<Duration>
+ }
+}
+
+impl<'a, F: Future> Future for MeasureRuntime<'a, F> {
+ type Output = F::Output;
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ let this = self.project();
+ let duration_cell: &Cell<Duration> = this.duration;
+ let start = Instant::now();
+ let res = F::poll(this.f, cx);
+ let new_duration = Instant::now() - start;
+ duration_cell.set(duration_cell.get() / 2 + new_duration / 2);
+ res
+ }
+}
+
+pub struct DurationMetadata {
+ inner: Cell<Duration>,
+}
+
+thread_local! {
+ // A queue that holds scheduled tasks.
+ static QUEUE: RefCell<BinaryHeap<ByDuration>> = RefCell::new(BinaryHeap::new());
+}
+
+fn make_future_fn<'a, F>(
+ future: F,
+) -> impl (FnOnce(&'a DurationMetadata) -> MeasureRuntime<'a, F>) {
+ move |duration_meta| MeasureRuntime {
+ f: future,
+ duration: &duration_meta.inner,
+ }
+}
+
+fn ensure_safe_schedule<F: Send + Sync + 'static>(f: F) -> F {
+ f
+}
+
+/// Spawns a future on the executor.
+pub fn spawn<F, T>(future: F) -> Task<T, DurationMetadata>
+where
+ F: Future<Output = T> + 'static,
+ T: 'static,
+{
+ let spawn_thread_id = thread::current().id();
+ // Create a task that is scheduled by pushing it into the queue.
+ let schedule = ensure_safe_schedule(move |runnable| {
+ if thread::current().id() != spawn_thread_id {
+ panic!("Task would be run on a different thread than spawned on.");
+ }
+ QUEUE.with(move |queue| queue.borrow_mut().push(ByDuration(runnable)));
+ });
+ let future_fn = make_future_fn(future);
+ let (runnable, task) = unsafe {
+ Builder::new()
+ .metadata(DurationMetadata {
+ inner: Cell::new(Duration::default()),
+ })
+ .spawn_unchecked(future_fn, schedule)
+ };
+
+ // Schedule the task by pushing it into the queue.
+ runnable.schedule();
+
+ task
+}
+
+pub fn block_on<F>(future: F)
+where
+ F: Future<Output = ()> + 'static,
+{
+ let task = spawn(future);
+ while !task.is_finished() {
+ let Some(runnable) = QUEUE.with(|queue| queue.borrow_mut().pop()) else {
+ thread::yield_now();
+ continue;
+ };
+ runnable.0.run();
+ }
+}
+
+fn main() {
+ // Spawn a future and await its result.
+ block_on(async {
+ let (sender, receiver) = channel::bounded(1);
+ let world = spawn(async move {
+ receiver.recv().await.unwrap();
+ println!("world.")
+ });
+ let hello = spawn(async move {
+ sender.send(()).await.unwrap();
+ print!("Hello, ")
+ });
+ future::zip(hello, world).await;
+ });
+}
diff --git a/external/vendor/async-task/src/header.rs b/external/vendor/async-task/src/header.rs
new file mode 100644
index 0000000..ee84035
--- /dev/null
+++ b/external/vendor/async-task/src/header.rs
@@ -0,0 +1,177 @@
+use core::cell::UnsafeCell;
+use core::fmt;
+use core::task::Waker;
+
+#[cfg(not(feature = "portable-atomic"))]
+use core::sync::atomic::AtomicUsize;
+use core::sync::atomic::Ordering;
+#[cfg(feature = "portable-atomic")]
+use portable_atomic::AtomicUsize;
+
+use crate::raw::TaskVTable;
+use crate::state::*;
+use crate::utils::abort_on_panic;
+
+/// The header of a task.
+///
+/// This header is stored in memory at the beginning of the heap-allocated task.
+pub(crate) struct Header<M> {
+ /// Current state of the task.
+ ///
+ /// Contains flags representing the current state and the reference count.
+ pub(crate) state: AtomicUsize,
+
+ /// The task that is blocked on the `Task` handle.
+ ///
+ /// This waker needs to be woken up once the task completes or is closed.
+ pub(crate) awaiter: UnsafeCell<Option<Waker>>,
+
+ /// The virtual table.
+ ///
+ /// In addition to the actual waker virtual table, it also contains pointers to several other
+ /// methods necessary for bookkeeping the heap-allocated task.
+ pub(crate) vtable: &'static TaskVTable,
+
+ /// Metadata associated with the task.
+ ///
+ /// This metadata may be provided to the user.
+ pub(crate) metadata: M,
+
+ /// Whether or not a panic that occurs in the task should be propagated.
+ #[cfg(feature = "std")]
+ pub(crate) propagate_panic: bool,
+}
+
+impl<M> Header<M> {
+ /// Notifies the awaiter blocked on this task.
+ ///
+ /// If the awaiter is the same as the current waker, it will not be notified.
+ #[inline]
+ pub(crate) fn notify(&self, current: Option<&Waker>) {
+ if let Some(w) = self.take(current) {
+ abort_on_panic(|| w.wake());
+ }
+ }
+
+ /// Takes the awaiter blocked on this task.
+ ///
+ /// If there is no awaiter or if it is the same as the current waker, returns `None`.
+ #[inline]
+ pub(crate) fn take(&self, current: Option<&Waker>) -> Option<Waker> {
+ // Set the bit indicating that the task is notifying its awaiter.
+ let state = self.state.fetch_or(NOTIFYING, Ordering::AcqRel);
+
+ // If the task was not notifying or registering an awaiter...
+ if state & (NOTIFYING | REGISTERING) == 0 {
+ // Take the waker out.
+ let waker = unsafe { (*self.awaiter.get()).take() };
+
+ // Unset the bit indicating that the task is notifying its awaiter.
+ self.state
+ .fetch_and(!NOTIFYING & !AWAITER, Ordering::Release);
+
+ // Finally, notify the waker if it's different from the current waker.
+ if let Some(w) = waker {
+ match current {
+ None => return Some(w),
+ Some(c) if !w.will_wake(c) => return Some(w),
+ Some(_) => abort_on_panic(|| drop(w)),
+ }
+ }
+ }
+
+ None
+ }
+
+ /// Registers a new awaiter blocked on this task.
+ ///
+ /// This method is called when `Task` is polled and it has not yet completed.
+ #[inline]
+ pub(crate) fn register(&self, waker: &Waker) {
+ // Load the state and synchronize with it.
+ let mut state = self.state.fetch_or(0, Ordering::Acquire);
+
+ loop {
+ // There can't be two concurrent registrations because `Task` can only be polled
+ // by a unique pinned reference.
+ debug_assert!(state & REGISTERING == 0);
+
+ // If we're in the notifying state at this moment, just wake and return without
+ // registering.
+ if state & NOTIFYING != 0 {
+ abort_on_panic(|| waker.wake_by_ref());
+ return;
+ }
+
+ // Mark the state to let other threads know we're registering a new awaiter.
+ match self.state.compare_exchange_weak(
+ state,
+ state | REGISTERING,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ state |= REGISTERING;
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+
+ // Put the waker into the awaiter field.
+ unsafe {
+ abort_on_panic(|| (*self.awaiter.get()) = Some(waker.clone()));
+ }
+
+ // This variable will contain the newly registered waker if a notification comes in before
+ // we complete registration.
+ let mut waker = None;
+
+ loop {
+ // If there was a notification, take the waker out of the awaiter field.
+ if state & NOTIFYING != 0 {
+ if let Some(w) = unsafe { (*self.awaiter.get()).take() } {
+ abort_on_panic(|| waker = Some(w));
+ }
+ }
+
+ // The new state is not being notified nor registered, but there might or might not be
+ // an awaiter depending on whether there was a concurrent notification.
+ let new = if waker.is_none() {
+ (state & !NOTIFYING & !REGISTERING) | AWAITER
+ } else {
+ state & !NOTIFYING & !REGISTERING & !AWAITER
+ };
+
+ match self
+ .state
+ .compare_exchange_weak(state, new, Ordering::AcqRel, Ordering::Acquire)
+ {
+ Ok(_) => break,
+ Err(s) => state = s,
+ }
+ }
+
+ // If there was a notification during registration, wake the awaiter now.
+ if let Some(w) = waker {
+ abort_on_panic(|| w.wake());
+ }
+ }
+}
+
+impl<M: fmt::Debug> fmt::Debug for Header<M> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let state = self.state.load(Ordering::SeqCst);
+
+ f.debug_struct("Header")
+ .field("scheduled", &(state & SCHEDULED != 0))
+ .field("running", &(state & RUNNING != 0))
+ .field("completed", &(state & COMPLETED != 0))
+ .field("closed", &(state & CLOSED != 0))
+ .field("awaiter", &(state & AWAITER != 0))
+ .field("task", &(state & TASK != 0))
+ .field("ref_count", &(state / REFERENCE))
+ .field("metadata", &self.metadata)
+ .finish()
+ }
+}
diff --git a/external/vendor/async-task/src/lib.rs b/external/vendor/async-task/src/lib.rs
new file mode 100644
index 0000000..c8f6702
--- /dev/null
+++ b/external/vendor/async-task/src/lib.rs
@@ -0,0 +1,118 @@
+//! Task abstraction for building executors.
+//!
+//! To spawn a future onto an executor, we first need to allocate it on the heap and keep some
+//! state attached to it. The state indicates whether the future is ready for polling, waiting to
+//! be woken up, or completed. Such a stateful future is called a *task*.
+//!
+//! All executors have a queue that holds scheduled tasks:
+//!
+//! ```
+//! let (sender, receiver) = flume::unbounded();
+//! #
+//! # // A future that will get spawned.
+//! # let future = async { 1 + 2 };
+//! #
+//! # // A function that schedules the task when it gets woken up.
+//! # let schedule = move |runnable| sender.send(runnable).unwrap();
+//! #
+//! # // Create a task.
+//! # let (runnable, task) = async_task::spawn(future, schedule);
+//! ```
+//!
+//! A task is created using either [`spawn()`], [`spawn_local()`], or [`spawn_unchecked()`] which
+//! return a [`Runnable`] and a [`Task`]:
+//!
+//! ```
+//! # let (sender, receiver) = flume::unbounded();
+//! #
+//! // A future that will be spawned.
+//! let future = async { 1 + 2 };
+//!
+//! // A function that schedules the task when it gets woken up.
+//! let schedule = move |runnable| sender.send(runnable).unwrap();
+//!
+//! // Construct a task.
+//! let (runnable, task) = async_task::spawn(future, schedule);
+//!
+//! // Push the task into the queue by invoking its schedule function.
+//! runnable.schedule();
+//! ```
+//!
+//! The [`Runnable`] is used to poll the task's future, and the [`Task`] is used to await its
+//! output.
+//!
+//! Finally, we need a loop that takes scheduled tasks from the queue and runs them:
+//!
+//! ```no_run
+//! # let (sender, receiver) = flume::unbounded();
+//! #
+//! # // A future that will get spawned.
+//! # let future = async { 1 + 2 };
+//! #
+//! # // A function that schedules the task when it gets woken up.
+//! # let schedule = move |runnable| sender.send(runnable).unwrap();
+//! #
+//! # // Create a task.
+//! # let (runnable, task) = async_task::spawn(future, schedule);
+//! #
+//! # // Push the task into the queue by invoking its schedule function.
+//! # runnable.schedule();
+//! #
+//! for runnable in receiver {
+//! runnable.run();
+//! }
+//! ```
+//!
+//! Method [`run()`][`Runnable::run()`] polls the task's future once. Then, the [`Runnable`]
+//! vanishes and only reappears when its [`Waker`][`core::task::Waker`] wakes the task, thus
+//! scheduling it to be run again.
+
+#![no_std]
+#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
+#![doc(test(attr(deny(rust_2018_idioms, warnings))))]
+#![doc(test(attr(allow(unused_extern_crates, unused_variables))))]
+#![doc(
+ html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
+)]
+#![doc(
+ html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
+)]
+
+extern crate alloc;
+#[cfg(feature = "std")]
+extern crate std;
+
+/// We can't use `?` in const contexts yet, so this macro acts
+/// as a workaround.
+macro_rules! leap {
+ ($x: expr) => {{
+ match ($x) {
+ Some(val) => val,
+ None => return None,
+ }
+ }};
+}
+
+macro_rules! leap_unwrap {
+ ($x: expr) => {{
+ match ($x) {
+ Some(val) => val,
+ None => panic!("called `Option::unwrap()` on a `None` value"),
+ }
+ }};
+}
+
+mod header;
+mod raw;
+mod runnable;
+mod state;
+mod task;
+mod utils;
+
+pub use crate::runnable::{
+ spawn, spawn_unchecked, Builder, Runnable, Schedule, ScheduleInfo, WithInfo,
+};
+pub use crate::task::{FallibleTask, Task};
+
+#[cfg(feature = "std")]
+pub use crate::runnable::spawn_local;
diff --git a/external/vendor/async-task/src/raw.rs b/external/vendor/async-task/src/raw.rs
new file mode 100644
index 0000000..7a45dad
--- /dev/null
+++ b/external/vendor/async-task/src/raw.rs
@@ -0,0 +1,756 @@
+use alloc::alloc::Layout as StdLayout;
+use core::cell::UnsafeCell;
+use core::future::Future;
+use core::mem::{self, ManuallyDrop};
+use core::pin::Pin;
+use core::ptr::NonNull;
+use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
+
+#[cfg(not(feature = "portable-atomic"))]
+use core::sync::atomic::AtomicUsize;
+use core::sync::atomic::Ordering;
+#[cfg(feature = "portable-atomic")]
+use portable_atomic::AtomicUsize;
+
+use crate::header::Header;
+use crate::runnable::{Schedule, ScheduleInfo};
+use crate::state::*;
+use crate::utils::{abort, abort_on_panic, max, Layout};
+use crate::Runnable;
+
+#[cfg(feature = "std")]
+pub(crate) type Panic = alloc::boxed::Box<dyn core::any::Any + Send + 'static>;
+
+#[cfg(not(feature = "std"))]
+pub(crate) type Panic = core::convert::Infallible;
+
+/// The vtable for a task.
+pub(crate) struct TaskVTable {
+ /// Schedules the task.
+ pub(crate) schedule: unsafe fn(*const (), ScheduleInfo),
+
+ /// Drops the future inside the task.
+ pub(crate) drop_future: unsafe fn(*const ()),
+
+ /// Returns a pointer to the output stored after completion.
+ pub(crate) get_output: unsafe fn(*const ()) -> *const (),
+
+ /// Drops the task reference (`Runnable` or `Waker`).
+ pub(crate) drop_ref: unsafe fn(ptr: *const ()),
+
+ /// Destroys the task.
+ pub(crate) destroy: unsafe fn(*const ()),
+
+ /// Runs the task.
+ pub(crate) run: unsafe fn(*const ()) -> bool,
+
+ /// Creates a new waker associated with the task.
+ pub(crate) clone_waker: unsafe fn(ptr: *const ()) -> RawWaker,
+
+ /// The memory layout of the task. This information enables
+ /// debuggers to decode raw task memory blobs. Do not remove
+ /// the field, even if it appears to be unused.
+ #[allow(unused)]
+ pub(crate) layout_info: &'static TaskLayout,
+}
+
+/// Memory layout of a task.
+///
+/// This struct contains the following information:
+///
+/// 1. How to allocate and deallocate the task.
+/// 2. How to access the fields inside the task.
+#[derive(Clone, Copy)]
+pub(crate) struct TaskLayout {
+ /// Memory layout of the whole task.
+ pub(crate) layout: StdLayout,
+
+ /// Offset into the task at which the schedule function is stored.
+ pub(crate) offset_s: usize,
+
+ /// Offset into the task at which the future is stored.
+ pub(crate) offset_f: usize,
+
+ /// Offset into the task at which the output is stored.
+ pub(crate) offset_r: usize,
+}
+
+/// Raw pointers to the fields inside a task.
+pub(crate) struct RawTask<F, T, S, M> {
+ /// The task header.
+ pub(crate) header: *const Header<M>,
+
+ /// The schedule function.
+ pub(crate) schedule: *const S,
+
+ /// The future.
+ pub(crate) future: *mut F,
+
+ /// The output of the future.
+ pub(crate) output: *mut Result<T, Panic>,
+}
+
+impl<F, T, S, M> Copy for RawTask<F, T, S, M> {}
+
+impl<F, T, S, M> Clone for RawTask<F, T, S, M> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<F, T, S, M> RawTask<F, T, S, M> {
+ const TASK_LAYOUT: TaskLayout = Self::eval_task_layout();
+
+ /// Computes the memory layout for a task.
+ #[inline]
+ const fn eval_task_layout() -> TaskLayout {
+ // Compute the layouts for `Header`, `S`, `F`, and `T`.
+ let layout_header = Layout::new::<Header<M>>();
+ let layout_s = Layout::new::<S>();
+ let layout_f = Layout::new::<F>();
+ let layout_r = Layout::new::<Result<T, Panic>>();
+
+ // Compute the layout for `union { F, T }`.
+ let size_union = max(layout_f.size(), layout_r.size());
+ let align_union = max(layout_f.align(), layout_r.align());
+ let layout_union = Layout::from_size_align(size_union, align_union);
+
+ // Compute the layout for `Header` followed `S` and `union { F, T }`.
+ let layout = layout_header;
+ let (layout, offset_s) = leap_unwrap!(layout.extend(layout_s));
+ let (layout, offset_union) = leap_unwrap!(layout.extend(layout_union));
+ let offset_f = offset_union;
+ let offset_r = offset_union;
+
+ TaskLayout {
+ layout: unsafe { layout.into_std() },
+ offset_s,
+ offset_f,
+ offset_r,
+ }
+ }
+}
+
+impl<F, T, S, M> RawTask<F, T, S, M>
+where
+ F: Future<Output = T>,
+ S: Schedule<M>,
+{
+ const RAW_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
+ Self::clone_waker,
+ Self::wake,
+ Self::wake_by_ref,
+ Self::drop_waker,
+ );
+
+ /// Allocates a task with the given `future` and `schedule` function.
+ ///
+ /// It is assumed that initially only the `Runnable` and the `Task` exist.
+ pub(crate) fn allocate<'a, Gen: FnOnce(&'a M) -> F>(
+ future: Gen,
+ schedule: S,
+ builder: crate::Builder<M>,
+ ) -> NonNull<()>
+ where
+ F: 'a,
+ M: 'a,
+ {
+ // Compute the layout of the task for allocation. Abort if the computation fails.
+ //
+ // n.b. notgull: task_layout now automatically aborts instead of panicking
+ let task_layout = Self::task_layout();
+
+ unsafe {
+ // Allocate enough space for the entire task.
+ let ptr = match NonNull::new(alloc::alloc::alloc(task_layout.layout) as *mut ()) {
+ None => abort(),
+ Some(p) => p,
+ };
+
+ let raw = Self::from_ptr(ptr.as_ptr());
+
+ let crate::Builder {
+ metadata,
+ #[cfg(feature = "std")]
+ propagate_panic,
+ } = builder;
+
+ // Write the header as the first field of the task.
+ (raw.header as *mut Header<M>).write(Header {
+ state: AtomicUsize::new(SCHEDULED | TASK | REFERENCE),
+ awaiter: UnsafeCell::new(None),
+ vtable: &TaskVTable {
+ schedule: Self::schedule,
+ drop_future: Self::drop_future,
+ get_output: Self::get_output,
+ drop_ref: Self::drop_ref,
+ destroy: Self::destroy,
+ run: Self::run,
+ clone_waker: Self::clone_waker,
+ layout_info: &Self::TASK_LAYOUT,
+ },
+ metadata,
+ #[cfg(feature = "std")]
+ propagate_panic,
+ });
+
+ // Write the schedule function as the third field of the task.
+ (raw.schedule as *mut S).write(schedule);
+
+ // Generate the future, now that the metadata has been pinned in place.
+ let future = abort_on_panic(|| future(&(*raw.header).metadata));
+
+ // Write the future as the fourth field of the task.
+ raw.future.write(future);
+
+ ptr
+ }
+ }
+
+ /// Creates a `RawTask` from a raw task pointer.
+ #[inline]
+ pub(crate) fn from_ptr(ptr: *const ()) -> Self {
+ let task_layout = Self::task_layout();
+ let p = ptr as *const u8;
+
+ unsafe {
+ Self {
+ header: p as *const Header<M>,
+ schedule: p.add(task_layout.offset_s) as *const S,
+ future: p.add(task_layout.offset_f) as *mut F,
+ output: p.add(task_layout.offset_r) as *mut Result<T, Panic>,
+ }
+ }
+ }
+
+ /// Returns the layout of the task.
+ #[inline]
+ fn task_layout() -> TaskLayout {
+ Self::TASK_LAYOUT
+ }
+ /// Wakes a waker.
+ unsafe fn wake(ptr: *const ()) {
+ // This is just an optimization. If the schedule function has captured variables, then
+ // we'll do less reference counting if we wake the waker by reference and then drop it.
+ if mem::size_of::<S>() > 0 {
+ Self::wake_by_ref(ptr);
+ Self::drop_waker(ptr);
+ return;
+ }
+
+ let raw = Self::from_ptr(ptr);
+
+ let mut state = (*raw.header).state.load(Ordering::Acquire);
+
+ loop {
+ // If the task is completed or closed, it can't be woken up.
+ if state & (COMPLETED | CLOSED) != 0 {
+ // Drop the waker.
+ Self::drop_waker(ptr);
+ break;
+ }
+
+ // If the task is already scheduled, we just need to synchronize with the thread that
+ // will run the task by "publishing" our current view of the memory.
+ if state & SCHEDULED != 0 {
+ // Update the state without actually modifying it.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ state,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // Drop the waker.
+ Self::drop_waker(ptr);
+ break;
+ }
+ Err(s) => state = s,
+ }
+ } else {
+ // Mark the task as scheduled.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ state | SCHEDULED,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // If the task is not yet scheduled and isn't currently running, now is the
+ // time to schedule it.
+ if state & RUNNING == 0 {
+ // Schedule the task.
+ Self::schedule(ptr, ScheduleInfo::new(false));
+ } else {
+ // Drop the waker.
+ Self::drop_waker(ptr);
+ }
+
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ /// Wakes a waker by reference.
+ unsafe fn wake_by_ref(ptr: *const ()) {
+ let raw = Self::from_ptr(ptr);
+
+ let mut state = (*raw.header).state.load(Ordering::Acquire);
+
+ loop {
+ // If the task is completed or closed, it can't be woken up.
+ if state & (COMPLETED | CLOSED) != 0 {
+ break;
+ }
+
+ // If the task is already scheduled, we just need to synchronize with the thread that
+ // will run the task by "publishing" our current view of the memory.
+ if state & SCHEDULED != 0 {
+ // Update the state without actually modifying it.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ state,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => break,
+ Err(s) => state = s,
+ }
+ } else {
+ // If the task is not running, we can schedule right away.
+ let new = if state & RUNNING == 0 {
+ (state | SCHEDULED) + REFERENCE
+ } else {
+ state | SCHEDULED
+ };
+
+ // Mark the task as scheduled.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ new,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // If the task is not running, now is the time to schedule.
+ if state & RUNNING == 0 {
+ // If the reference count overflowed, abort.
+ if state > isize::MAX as usize {
+ abort();
+ }
+
+ // Schedule the task. There is no need to call `Self::schedule(ptr)`
+ // because the schedule function cannot be destroyed while the waker is
+ // still alive.
+ let task = Runnable::from_raw(NonNull::new_unchecked(ptr as *mut ()));
+ (*raw.schedule).schedule(task, ScheduleInfo::new(false));
+ }
+
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ /// Clones a waker.
+ unsafe fn clone_waker(ptr: *const ()) -> RawWaker {
+ let raw = Self::from_ptr(ptr);
+
+ // Increment the reference count. With any kind of reference-counted data structure,
+ // relaxed ordering is appropriate when incrementing the counter.
+ let state = (*raw.header).state.fetch_add(REFERENCE, Ordering::Relaxed);
+
+ // If the reference count overflowed, abort.
+ if state > isize::MAX as usize {
+ abort();
+ }
+
+ RawWaker::new(ptr, &Self::RAW_WAKER_VTABLE)
+ }
+
+ /// Drops a waker.
+ ///
+ /// This function will decrement the reference count. If it drops down to zero, the associated
+ /// `Task` has been dropped too, and the task has not been completed, then it will get
+ /// scheduled one more time so that its future gets dropped by the executor.
+ #[inline]
+ unsafe fn drop_waker(ptr: *const ()) {
+ let raw = Self::from_ptr(ptr);
+
+ // Decrement the reference count.
+ let new = (*raw.header).state.fetch_sub(REFERENCE, Ordering::AcqRel) - REFERENCE;
+
+ // If this was the last reference to the task and the `Task` has been dropped too,
+ // then we need to decide how to destroy the task.
+ if new & !(REFERENCE - 1) == 0 && new & TASK == 0 {
+ if new & (COMPLETED | CLOSED) == 0 {
+ // If the task was not completed nor closed, close it and schedule one more time so
+ // that its future gets dropped by the executor.
+ (*raw.header)
+ .state
+ .store(SCHEDULED | CLOSED | REFERENCE, Ordering::Release);
+ Self::schedule(ptr, ScheduleInfo::new(false));
+ } else {
+ // Otherwise, destroy the task right away.
+ Self::destroy(ptr);
+ }
+ }
+ }
+
+ /// Drops a task reference (`Runnable` or `Waker`).
+ ///
+ /// This function will decrement the reference count. If it drops down to zero and the
+ /// associated `Task` handle has been dropped too, then the task gets destroyed.
+ #[inline]
+ unsafe fn drop_ref(ptr: *const ()) {
+ let raw = Self::from_ptr(ptr);
+
+ // Decrement the reference count.
+ let new = (*raw.header).state.fetch_sub(REFERENCE, Ordering::AcqRel) - REFERENCE;
+
+ // If this was the last reference to the task and the `Task` has been dropped too,
+ // then destroy the task.
+ if new & !(REFERENCE - 1) == 0 && new & TASK == 0 {
+ Self::destroy(ptr);
+ }
+ }
+
+ /// Schedules a task for running.
+ ///
+ /// This function doesn't modify the state of the task. It only passes the task reference to
+ /// its schedule function.
+ unsafe fn schedule(ptr: *const (), info: ScheduleInfo) {
+ let raw = Self::from_ptr(ptr);
+
+ // If the schedule function has captured variables, create a temporary waker that prevents
+ // the task from getting deallocated while the function is being invoked.
+ let _waker;
+ if mem::size_of::<S>() > 0 {
+ _waker = Waker::from_raw(Self::clone_waker(ptr));
+ }
+
+ let task = Runnable::from_raw(NonNull::new_unchecked(ptr as *mut ()));
+ (*raw.schedule).schedule(task, info);
+ }
+
+ /// Drops the future inside a task.
+ #[inline]
+ unsafe fn drop_future(ptr: *const ()) {
+ let raw = Self::from_ptr(ptr);
+
+ // We need a safeguard against panics because the destructor can panic.
+ abort_on_panic(|| {
+ raw.future.drop_in_place();
+ })
+ }
+
+ /// Returns a pointer to the output inside a task.
+ unsafe fn get_output(ptr: *const ()) -> *const () {
+ let raw = Self::from_ptr(ptr);
+ raw.output as *const ()
+ }
+
+ /// Cleans up task's resources and deallocates it.
+ ///
+ /// The schedule function will be dropped, and the task will then get deallocated.
+ /// The task must be closed before this function is called.
+ #[inline]
+ unsafe fn destroy(ptr: *const ()) {
+ let raw = Self::from_ptr(ptr);
+ let task_layout = Self::task_layout();
+
+ // We need a safeguard against panics because destructors can panic.
+ abort_on_panic(|| {
+ // Drop the header along with the metadata.
+ (raw.header as *mut Header<M>).drop_in_place();
+
+ // Drop the schedule function.
+ (raw.schedule as *mut S).drop_in_place();
+ });
+
+ // Finally, deallocate the memory reserved by the task.
+ alloc::alloc::dealloc(ptr as *mut u8, task_layout.layout);
+ }
+
+ /// Runs a task.
+ ///
+ /// If polling its future panics, the task will be closed and the panic will be propagated into
+ /// the caller.
+ unsafe fn run(ptr: *const ()) -> bool {
+ let raw = Self::from_ptr(ptr);
+
+ // Create a context from the raw task pointer and the vtable inside the its header.
+ let waker = ManuallyDrop::new(Waker::from_raw(RawWaker::new(ptr, &Self::RAW_WAKER_VTABLE)));
+ let cx = &mut Context::from_waker(&waker);
+
+ let mut state = (*raw.header).state.load(Ordering::Acquire);
+
+ // Update the task's state before polling its future.
+ loop {
+ // If the task has already been closed, drop the task reference and return.
+ if state & CLOSED != 0 {
+ // Drop the future.
+ Self::drop_future(ptr);
+
+ // Mark the task as unscheduled.
+ let state = (*raw.header).state.fetch_and(!SCHEDULED, Ordering::AcqRel);
+
+ // Take the awaiter out.
+ let mut awaiter = None;
+ if state & AWAITER != 0 {
+ awaiter = (*raw.header).take(None);
+ }
+
+ // Drop the task reference.
+ Self::drop_ref(ptr);
+
+ // Notify the awaiter that the future has been dropped.
+ if let Some(w) = awaiter {
+ abort_on_panic(|| w.wake());
+ }
+ return false;
+ }
+
+ // Mark the task as unscheduled and running.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ (state & !SCHEDULED) | RUNNING,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // Update the state because we're continuing with polling the future.
+ state = (state & !SCHEDULED) | RUNNING;
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+
+ // Poll the inner future, but surround it with a guard that closes the task in case polling
+ // panics.
+ // If available, we should also try to catch the panic so that it is propagated correctly.
+ let guard = Guard(raw);
+
+ // Panic propagation is not available for no_std.
+ #[cfg(not(feature = "std"))]
+ let poll = <F as Future>::poll(Pin::new_unchecked(&mut *raw.future), cx).map(Ok);
+
+ #[cfg(feature = "std")]
+ let poll = {
+ // Check if we should propagate panics.
+ if (*raw.header).propagate_panic {
+ // Use catch_unwind to catch the panic.
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ <F as Future>::poll(Pin::new_unchecked(&mut *raw.future), cx)
+ })) {
+ Ok(Poll::Ready(v)) => Poll::Ready(Ok(v)),
+ Ok(Poll::Pending) => Poll::Pending,
+ Err(e) => Poll::Ready(Err(e)),
+ }
+ } else {
+ <F as Future>::poll(Pin::new_unchecked(&mut *raw.future), cx).map(Ok)
+ }
+ };
+
+ mem::forget(guard);
+
+ match poll {
+ Poll::Ready(out) => {
+ // Replace the future with its output.
+ Self::drop_future(ptr);
+ raw.output.write(out);
+
+ // The task is now completed.
+ loop {
+ // If the `Task` is dropped, we'll need to close it and drop the output.
+ let new = if state & TASK == 0 {
+ (state & !RUNNING & !SCHEDULED) | COMPLETED | CLOSED
+ } else {
+ (state & !RUNNING & !SCHEDULED) | COMPLETED
+ };
+
+ // Mark the task as not running and completed.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ new,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // If the `Task` is dropped or if the task was closed while running,
+ // now it's time to drop the output.
+ if state & TASK == 0 || state & CLOSED != 0 {
+ // Drop the output.
+ abort_on_panic(|| raw.output.drop_in_place());
+ }
+
+ // Take the awaiter out.
+ let mut awaiter = None;
+ if state & AWAITER != 0 {
+ awaiter = (*raw.header).take(None);
+ }
+
+ // Drop the task reference.
+ Self::drop_ref(ptr);
+
+ // Notify the awaiter that the future has been dropped.
+ if let Some(w) = awaiter {
+ abort_on_panic(|| w.wake());
+ }
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ Poll::Pending => {
+ let mut future_dropped = false;
+
+ // The task is still not completed.
+ loop {
+ // If the task was closed while running, we'll need to unschedule in case it
+ // was woken up and then destroy it.
+ let new = if state & CLOSED != 0 {
+ state & !RUNNING & !SCHEDULED
+ } else {
+ state & !RUNNING
+ };
+
+ if state & CLOSED != 0 && !future_dropped {
+ // The thread that closed the task didn't drop the future because it was
+ // running so now it's our responsibility to do so.
+ Self::drop_future(ptr);
+ future_dropped = true;
+ }
+
+ // Mark the task as not running.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ new,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(state) => {
+ // If the task was closed while running, we need to notify the awaiter.
+ // If the task was woken up while running, we need to schedule it.
+ // Otherwise, we just drop the task reference.
+ if state & CLOSED != 0 {
+ // Take the awaiter out.
+ let mut awaiter = None;
+ if state & AWAITER != 0 {
+ awaiter = (*raw.header).take(None);
+ }
+
+ // Drop the task reference.
+ Self::drop_ref(ptr);
+
+ // Notify the awaiter that the future has been dropped.
+ if let Some(w) = awaiter {
+ abort_on_panic(|| w.wake());
+ }
+ } else if state & SCHEDULED != 0 {
+ // The thread that woke the task up didn't reschedule it because
+ // it was running so now it's our responsibility to do so.
+ Self::schedule(ptr, ScheduleInfo::new(true));
+ return true;
+ } else {
+ // Drop the task reference.
+ Self::drop_ref(ptr);
+ }
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ return false;
+
+ /// A guard that closes the task if polling its future panics.
+ struct Guard<F, T, S, M>(RawTask<F, T, S, M>)
+ where
+ F: Future<Output = T>,
+ S: Schedule<M>;
+
+ impl<F, T, S, M> Drop for Guard<F, T, S, M>
+ where
+ F: Future<Output = T>,
+ S: Schedule<M>,
+ {
+ fn drop(&mut self) {
+ let raw = self.0;
+ let ptr = raw.header as *const ();
+
+ unsafe {
+ let mut state = (*raw.header).state.load(Ordering::Acquire);
+
+ loop {
+ // If the task was closed while running, then unschedule it, drop its
+ // future, and drop the task reference.
+ if state & CLOSED != 0 {
+ // The thread that closed the task didn't drop the future because it
+ // was running so now it's our responsibility to do so.
+ RawTask::<F, T, S, M>::drop_future(ptr);
+
+ // Mark the task as not running and not scheduled.
+ (*raw.header)
+ .state
+ .fetch_and(!RUNNING & !SCHEDULED, Ordering::AcqRel);
+
+ // Take the awaiter out.
+ let mut awaiter = None;
+ if state & AWAITER != 0 {
+ awaiter = (*raw.header).take(None);
+ }
+
+ // Drop the task reference.
+ RawTask::<F, T, S, M>::drop_ref(ptr);
+
+ // Notify the awaiter that the future has been dropped.
+ if let Some(w) = awaiter {
+ abort_on_panic(|| w.wake());
+ }
+ break;
+ }
+
+ // Mark the task as not running, not scheduled, and closed.
+ match (*raw.header).state.compare_exchange_weak(
+ state,
+ (state & !RUNNING & !SCHEDULED) | CLOSED,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(state) => {
+ // Drop the future because the task is now closed.
+ RawTask::<F, T, S, M>::drop_future(ptr);
+
+ // Take the awaiter out.
+ let mut awaiter = None;
+ if state & AWAITER != 0 {
+ awaiter = (*raw.header).take(None);
+ }
+
+ // Drop the task reference.
+ RawTask::<F, T, S, M>::drop_ref(ptr);
+
+ // Notify the awaiter that the future has been dropped.
+ if let Some(w) = awaiter {
+ abort_on_panic(|| w.wake());
+ }
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/external/vendor/async-task/src/runnable.rs b/external/vendor/async-task/src/runnable.rs
new file mode 100644
index 0000000..25d44dc
--- /dev/null
+++ b/external/vendor/async-task/src/runnable.rs
@@ -0,0 +1,945 @@
+use core::fmt;
+use core::future::Future;
+use core::marker::PhantomData;
+use core::mem;
+use core::ptr::NonNull;
+use core::sync::atomic::Ordering;
+use core::task::Waker;
+
+use alloc::boxed::Box;
+
+use crate::header::Header;
+use crate::raw::RawTask;
+use crate::state::*;
+use crate::Task;
+
+mod sealed {
+ use super::*;
+ pub trait Sealed<M> {}
+
+ impl<M, F> Sealed<M> for F where F: Fn(Runnable<M>) {}
+
+ impl<M, F> Sealed<M> for WithInfo<F> where F: Fn(Runnable<M>, ScheduleInfo) {}
+}
+
+/// A builder that creates a new task.
+#[derive(Debug)]
+pub struct Builder<M> {
+ /// The metadata associated with the task.
+ pub(crate) metadata: M,
+
+ /// Whether or not a panic that occurs in the task should be propagated.
+ #[cfg(feature = "std")]
+ pub(crate) propagate_panic: bool,
+}
+
+impl<M: Default> Default for Builder<M> {
+ fn default() -> Self {
+ Builder::new().metadata(M::default())
+ }
+}
+
+/// Extra scheduling information that can be passed to the scheduling function.
+///
+/// The data source of this struct is directly from the actual implementation
+/// of the crate itself, different from [`Runnable`]'s metadata, which is
+/// managed by the caller.
+///
+/// # Examples
+///
+/// ```
+/// use async_task::{Runnable, ScheduleInfo, WithInfo};
+/// use std::sync::{Arc, Mutex};
+///
+/// // The future inside the task.
+/// let future = async {
+/// println!("Hello, world!");
+/// };
+///
+/// // If the task gets woken up while running, it will be sent into this channel.
+/// let (s, r) = flume::unbounded();
+/// // Otherwise, it will be placed into this slot.
+/// let lifo_slot = Arc::new(Mutex::new(None));
+/// let schedule = move |runnable: Runnable, info: ScheduleInfo| {
+/// if info.woken_while_running {
+/// s.send(runnable).unwrap()
+/// } else {
+/// let last = lifo_slot.lock().unwrap().replace(runnable);
+/// if let Some(last) = last {
+/// s.send(last).unwrap()
+/// }
+/// }
+/// };
+///
+/// // Create the actual scheduler to be spawned with some future.
+/// let scheduler = WithInfo(schedule);
+/// // Create a task with the future and the scheduler.
+/// let (runnable, task) = async_task::spawn(future, scheduler);
+/// ```
+#[derive(Debug, Copy, Clone)]
+#[non_exhaustive]
+pub struct ScheduleInfo {
+ /// Indicates whether the task gets woken up while running.
+ ///
+ /// It is set to true usually because the task has yielded itself to the
+ /// scheduler.
+ pub woken_while_running: bool,
+}
+
+impl ScheduleInfo {
+ pub(crate) fn new(woken_while_running: bool) -> Self {
+ ScheduleInfo {
+ woken_while_running,
+ }
+ }
+}
+
+/// The trait for scheduling functions.
+pub trait Schedule<M = ()>: sealed::Sealed<M> {
+ /// The actual scheduling procedure.
+ fn schedule(&self, runnable: Runnable<M>, info: ScheduleInfo);
+}
+
+impl<M, F> Schedule<M> for F
+where
+ F: Fn(Runnable<M>),
+{
+ fn schedule(&self, runnable: Runnable<M>, _: ScheduleInfo) {
+ self(runnable)
+ }
+}
+
+/// Pass a scheduling function with more scheduling information - a.k.a.
+/// [`ScheduleInfo`].
+///
+/// Sometimes, it's useful to pass the runnable's state directly to the
+/// scheduling function, such as whether it's woken up while running. The
+/// scheduler can thus use the information to determine its scheduling
+/// strategy.
+///
+/// The data source of [`ScheduleInfo`] is directly from the actual
+/// implementation of the crate itself, different from [`Runnable`]'s metadata,
+/// which is managed by the caller.
+///
+/// # Examples
+///
+/// ```
+/// use async_task::{ScheduleInfo, WithInfo};
+/// use std::sync::{Arc, Mutex};
+///
+/// // The future inside the task.
+/// let future = async {
+/// println!("Hello, world!");
+/// };
+///
+/// // If the task gets woken up while running, it will be sent into this channel.
+/// let (s, r) = flume::unbounded();
+/// // Otherwise, it will be placed into this slot.
+/// let lifo_slot = Arc::new(Mutex::new(None));
+/// let schedule = move |runnable, info: ScheduleInfo| {
+/// if info.woken_while_running {
+/// s.send(runnable).unwrap()
+/// } else {
+/// let last = lifo_slot.lock().unwrap().replace(runnable);
+/// if let Some(last) = last {
+/// s.send(last).unwrap()
+/// }
+/// }
+/// };
+///
+/// // Create a task with the future and the schedule function.
+/// let (runnable, task) = async_task::spawn(future, WithInfo(schedule));
+/// ```
+#[derive(Debug)]
+pub struct WithInfo<F>(pub F);
+
+impl<F> From<F> for WithInfo<F> {
+ fn from(value: F) -> Self {
+ WithInfo(value)
+ }
+}
+
+impl<M, F> Schedule<M> for WithInfo<F>
+where
+ F: Fn(Runnable<M>, ScheduleInfo),
+{
+ fn schedule(&self, runnable: Runnable<M>, info: ScheduleInfo) {
+ (self.0)(runnable, info)
+ }
+}
+
+impl Builder<()> {
+ /// Creates a new task builder.
+ ///
+ /// By default, this task builder has no metadata. Use the [`metadata`] method to
+ /// set the metadata.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use async_task::Builder;
+ ///
+ /// let (runnable, task) = Builder::new().spawn(|()| async {}, |_| {});
+ /// ```
+ pub fn new() -> Builder<()> {
+ Builder {
+ metadata: (),
+ #[cfg(feature = "std")]
+ propagate_panic: false,
+ }
+ }
+
+ /// Adds metadata to the task.
+ ///
+ /// In certain cases, it may be useful to associate some metadata with a task. For instance,
+ /// you may want to associate a name with a task, or a priority for a priority queue. This
+ /// method allows the user to attach arbitrary metadata to a task that is available through
+ /// the [`Runnable`] or the [`Task`].
+ ///
+ /// # Examples
+ ///
+ /// This example creates an executor that associates a "priority" number with each task, and
+ /// then runs the tasks in order of priority.
+ ///
+ /// ```
+ /// use async_task::{Builder, Runnable};
+ /// use once_cell::sync::Lazy;
+ /// use std::cmp;
+ /// use std::collections::BinaryHeap;
+ /// use std::sync::Mutex;
+ ///
+ /// # smol::future::block_on(async {
+ /// /// A wrapper around a `Runnable<usize>` that implements `Ord` so that it can be used in a
+ /// /// priority queue.
+ /// struct TaskWrapper(Runnable<usize>);
+ ///
+ /// impl PartialEq for TaskWrapper {
+ /// fn eq(&self, other: &Self) -> bool {
+ /// self.0.metadata() == other.0.metadata()
+ /// }
+ /// }
+ ///
+ /// impl Eq for TaskWrapper {}
+ ///
+ /// impl PartialOrd for TaskWrapper {
+ /// fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
+ /// Some(self.cmp(other))
+ /// }
+ /// }
+ ///
+ /// impl Ord for TaskWrapper {
+ /// fn cmp(&self, other: &Self) -> cmp::Ordering {
+ /// self.0.metadata().cmp(other.0.metadata())
+ /// }
+ /// }
+ ///
+ /// static EXECUTOR: Lazy<Mutex<BinaryHeap<TaskWrapper>>> = Lazy::new(|| {
+ /// Mutex::new(BinaryHeap::new())
+ /// });
+ ///
+ /// let schedule = |runnable| {
+ /// EXECUTOR.lock().unwrap().push(TaskWrapper(runnable));
+ /// };
+ ///
+ /// // Spawn a few tasks with different priorities.
+ /// let spawn_task = move |priority| {
+ /// let (runnable, task) = Builder::new().metadata(priority).spawn(
+ /// move |_| async move { priority },
+ /// schedule,
+ /// );
+ /// runnable.schedule();
+ /// task
+ /// };
+ ///
+ /// let t1 = spawn_task(1);
+ /// let t2 = spawn_task(2);
+ /// let t3 = spawn_task(3);
+ ///
+ /// // Run the tasks in order of priority.
+ /// let mut metadata_seen = vec![];
+ /// while let Some(TaskWrapper(runnable)) = EXECUTOR.lock().unwrap().pop() {
+ /// metadata_seen.push(*runnable.metadata());
+ /// runnable.run();
+ /// }
+ ///
+ /// assert_eq!(metadata_seen, vec![3, 2, 1]);
+ /// assert_eq!(t1.await, 1);
+ /// assert_eq!(t2.await, 2);
+ /// assert_eq!(t3.await, 3);
+ /// # });
+ /// ```
+ pub fn metadata<M>(self, metadata: M) -> Builder<M> {
+ Builder {
+ metadata,
+ #[cfg(feature = "std")]
+ propagate_panic: self.propagate_panic,
+ }
+ }
+}
+
+impl<M> Builder<M> {
+ /// Propagates panics that occur in the task.
+ ///
+ /// When this is `true`, panics that occur in the task will be propagated to the caller of
+ /// the [`Task`]. When this is false, no special action is taken when a panic occurs in the
+ /// task, meaning that the caller of [`Runnable::run`] will observe a panic.
+ ///
+ /// This is only available when the `std` feature is enabled. By default, this is `false`.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use async_task::Builder;
+ /// use futures_lite::future::poll_fn;
+ /// use std::future::Future;
+ /// use std::panic;
+ /// use std::pin::Pin;
+ /// use std::task::{Context, Poll};
+ ///
+ /// fn did_panic<F: FnOnce()>(f: F) -> bool {
+ /// panic::catch_unwind(panic::AssertUnwindSafe(f)).is_err()
+ /// }
+ ///
+ /// # smol::future::block_on(async {
+ /// let (runnable1, mut task1) = Builder::new()
+ /// .propagate_panic(true)
+ /// .spawn(|()| async move { panic!() }, |_| {});
+ ///
+ /// let (runnable2, mut task2) = Builder::new()
+ /// .propagate_panic(false)
+ /// .spawn(|()| async move { panic!() }, |_| {});
+ ///
+ /// assert!(!did_panic(|| { runnable1.run(); }));
+ /// assert!(did_panic(|| { runnable2.run(); }));
+ ///
+ /// let waker = poll_fn(|cx| Poll::Ready(cx.waker().clone())).await;
+ /// let mut cx = Context::from_waker(&waker);
+ /// assert!(did_panic(|| { let _ = Pin::new(&mut task1).poll(&mut cx); }));
+ /// assert!(did_panic(|| { let _ = Pin::new(&mut task2).poll(&mut cx); }));
+ /// # });
+ /// ```
+ #[cfg(feature = "std")]
+ pub fn propagate_panic(self, propagate_panic: bool) -> Builder<M> {
+ Builder {
+ metadata: self.metadata,
+ propagate_panic,
+ }
+ }
+
+ /// Creates a new task.
+ ///
+ /// The returned [`Runnable`] is used to poll the `future`, and the [`Task`] is used to await its
+ /// output.
+ ///
+ /// Method [`run()`][`Runnable::run()`] polls the task's future once. Then, the [`Runnable`]
+ /// vanishes and only reappears when its [`Waker`] wakes the task, thus scheduling it to be run
+ /// again.
+ ///
+ /// When the task is woken, its [`Runnable`] is passed to the `schedule` function.
+ /// The `schedule` function should not attempt to run the [`Runnable`] nor to drop it. Instead, it
+ /// should push it into a task queue so that it can be processed later.
+ ///
+ /// If you need to spawn a future that does not implement [`Send`] or isn't `'static`, consider
+ /// using [`spawn_local()`] or [`spawn_unchecked()`] instead.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use async_task::Builder;
+ ///
+ /// // The future inside the task.
+ /// let future = async {
+ /// println!("Hello, world!");
+ /// };
+ ///
+ /// // A function that schedules the task when it gets woken up.
+ /// let (s, r) = flume::unbounded();
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with the future and the schedule function.
+ /// let (runnable, task) = Builder::new().spawn(|()| future, schedule);
+ /// ```
+ pub fn spawn<F, Fut, S>(self, future: F, schedule: S) -> (Runnable<M>, Task<Fut::Output, M>)
+ where
+ F: FnOnce(&M) -> Fut,
+ Fut: Future + Send + 'static,
+ Fut::Output: Send + 'static,
+ S: Schedule<M> + Send + Sync + 'static,
+ {
+ unsafe { self.spawn_unchecked(future, schedule) }
+ }
+
+ /// Creates a new thread-local task.
+ ///
+ /// This function is same as [`spawn()`], except it does not require [`Send`] on `future`. If the
+ /// [`Runnable`] is used or dropped on another thread, a panic will occur.
+ ///
+ /// This function is only available when the `std` feature for this crate is enabled.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use async_task::{Builder, Runnable};
+ /// use flume::{Receiver, Sender};
+ /// use std::rc::Rc;
+ ///
+ /// thread_local! {
+ /// // A queue that holds scheduled tasks.
+ /// static QUEUE: (Sender<Runnable>, Receiver<Runnable>) = flume::unbounded();
+ /// }
+ ///
+ /// // Make a non-Send future.
+ /// let msg: Rc<str> = "Hello, world!".into();
+ /// let future = async move {
+ /// println!("{}", msg);
+ /// };
+ ///
+ /// // A function that schedules the task when it gets woken up.
+ /// let s = QUEUE.with(|(s, _)| s.clone());
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with the future and the schedule function.
+ /// let (runnable, task) = Builder::new().spawn_local(move |()| future, schedule);
+ /// ```
+ #[cfg(feature = "std")]
+ pub fn spawn_local<F, Fut, S>(
+ self,
+ future: F,
+ schedule: S,
+ ) -> (Runnable<M>, Task<Fut::Output, M>)
+ where
+ F: FnOnce(&M) -> Fut,
+ Fut: Future + 'static,
+ Fut::Output: 'static,
+ S: Schedule<M> + Send + Sync + 'static,
+ {
+ use std::mem::ManuallyDrop;
+ use std::pin::Pin;
+ use std::task::{Context, Poll};
+ use std::thread::{self, ThreadId};
+
+ #[inline]
+ fn thread_id() -> ThreadId {
+ std::thread_local! {
+ static ID: ThreadId = thread::current().id();
+ }
+ ID.try_with(|id| *id)
+ .unwrap_or_else(|_| thread::current().id())
+ }
+
+ struct Checked<F> {
+ id: ThreadId,
+ inner: ManuallyDrop<F>,
+ }
+
+ impl<F> Drop for Checked<F> {
+ fn drop(&mut self) {
+ assert!(
+ self.id == thread_id(),
+ "local task dropped by a thread that didn't spawn it"
+ );
+ unsafe {
+ ManuallyDrop::drop(&mut self.inner);
+ }
+ }
+ }
+
+ impl<F: Future> Future for Checked<F> {
+ type Output = F::Output;
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ assert!(
+ self.id == thread_id(),
+ "local task polled by a thread that didn't spawn it"
+ );
+ unsafe { self.map_unchecked_mut(|c| &mut *c.inner).poll(cx) }
+ }
+ }
+
+ // Wrap the future into one that checks which thread it's on.
+ let future = move |meta| {
+ let future = future(meta);
+
+ Checked {
+ id: thread_id(),
+ inner: ManuallyDrop::new(future),
+ }
+ };
+
+ unsafe { self.spawn_unchecked(future, schedule) }
+ }
+
+ /// Creates a new task without [`Send`], [`Sync`], and `'static` bounds.
+ ///
+ /// This function is same as [`spawn()`], except it does not require [`Send`], [`Sync`], and
+ /// `'static` on `future` and `schedule`.
+ ///
+ /// # Safety
+ ///
+ /// - If `Fut` is not [`Send`], its [`Runnable`] must be used and dropped on the original
+ /// thread.
+ /// - If `Fut` is not `'static`, borrowed non-metadata variables must outlive its [`Runnable`].
+ /// - If `schedule` is not [`Send`] and [`Sync`], all instances of the [`Runnable`]'s [`Waker`]
+ /// must be used and dropped on the original thread.
+ /// - If `schedule` is not `'static`, borrowed variables must outlive all instances of the
+ /// [`Runnable`]'s [`Waker`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use async_task::Builder;
+ ///
+ /// // The future inside the task.
+ /// let future = async {
+ /// println!("Hello, world!");
+ /// };
+ ///
+ /// // If the task gets woken up, it will be sent into this channel.
+ /// let (s, r) = flume::unbounded();
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with the future and the schedule function.
+ /// let (runnable, task) = unsafe { Builder::new().spawn_unchecked(move |()| future, schedule) };
+ /// ```
+ pub unsafe fn spawn_unchecked<'a, F, Fut, S>(
+ self,
+ future: F,
+ schedule: S,
+ ) -> (Runnable<M>, Task<Fut::Output, M>)
+ where
+ F: FnOnce(&'a M) -> Fut,
+ Fut: Future + 'a,
+ S: Schedule<M>,
+ M: 'a,
+ {
+ // Allocate large futures on the heap.
+ let ptr = if mem::size_of::<Fut>() >= 2048 {
+ let future = |meta| {
+ let future = future(meta);
+ Box::pin(future)
+ };
+
+ RawTask::<_, Fut::Output, S, M>::allocate(future, schedule, self)
+ } else {
+ RawTask::<Fut, Fut::Output, S, M>::allocate(future, schedule, self)
+ };
+
+ let runnable = Runnable::from_raw(ptr);
+ let task = Task {
+ ptr,
+ _marker: PhantomData,
+ };
+ (runnable, task)
+ }
+}
+
+/// Creates a new task.
+///
+/// The returned [`Runnable`] is used to poll the `future`, and the [`Task`] is used to await its
+/// output.
+///
+/// Method [`run()`][`Runnable::run()`] polls the task's future once. Then, the [`Runnable`]
+/// vanishes and only reappears when its [`Waker`] wakes the task, thus scheduling it to be run
+/// again.
+///
+/// When the task is woken, its [`Runnable`] is passed to the `schedule` function.
+/// The `schedule` function should not attempt to run the [`Runnable`] nor to drop it. Instead, it
+/// should push it into a task queue so that it can be processed later.
+///
+/// If you need to spawn a future that does not implement [`Send`] or isn't `'static`, consider
+/// using [`spawn_local()`] or [`spawn_unchecked()`] instead.
+///
+/// # Examples
+///
+/// ```
+/// // The future inside the task.
+/// let future = async {
+/// println!("Hello, world!");
+/// };
+///
+/// // A function that schedules the task when it gets woken up.
+/// let (s, r) = flume::unbounded();
+/// let schedule = move |runnable| s.send(runnable).unwrap();
+///
+/// // Create a task with the future and the schedule function.
+/// let (runnable, task) = async_task::spawn(future, schedule);
+/// ```
+pub fn spawn<F, S>(future: F, schedule: S) -> (Runnable, Task<F::Output>)
+where
+ F: Future + Send + 'static,
+ F::Output: Send + 'static,
+ S: Schedule + Send + Sync + 'static,
+{
+ unsafe { spawn_unchecked(future, schedule) }
+}
+
+/// Creates a new thread-local task.
+///
+/// This function is same as [`spawn()`], except it does not require [`Send`] on `future`. If the
+/// [`Runnable`] is used or dropped on another thread, a panic will occur.
+///
+/// This function is only available when the `std` feature for this crate is enabled.
+///
+/// # Examples
+///
+/// ```
+/// use async_task::Runnable;
+/// use flume::{Receiver, Sender};
+/// use std::rc::Rc;
+///
+/// thread_local! {
+/// // A queue that holds scheduled tasks.
+/// static QUEUE: (Sender<Runnable>, Receiver<Runnable>) = flume::unbounded();
+/// }
+///
+/// // Make a non-Send future.
+/// let msg: Rc<str> = "Hello, world!".into();
+/// let future = async move {
+/// println!("{}", msg);
+/// };
+///
+/// // A function that schedules the task when it gets woken up.
+/// let s = QUEUE.with(|(s, _)| s.clone());
+/// let schedule = move |runnable| s.send(runnable).unwrap();
+///
+/// // Create a task with the future and the schedule function.
+/// let (runnable, task) = async_task::spawn_local(future, schedule);
+/// ```
+#[cfg(feature = "std")]
+pub fn spawn_local<F, S>(future: F, schedule: S) -> (Runnable, Task<F::Output>)
+where
+ F: Future + 'static,
+ F::Output: 'static,
+ S: Schedule + Send + Sync + 'static,
+{
+ Builder::new().spawn_local(move |()| future, schedule)
+}
+
+/// Creates a new task without [`Send`], [`Sync`], and `'static` bounds.
+///
+/// This function is same as [`spawn()`], except it does not require [`Send`], [`Sync`], and
+/// `'static` on `future` and `schedule`.
+///
+/// # Safety
+///
+/// - If `future` is not [`Send`], its [`Runnable`] must be used and dropped on the original
+/// thread.
+/// - If `future` is not `'static`, borrowed variables must outlive its [`Runnable`].
+/// - If `schedule` is not [`Send`] and [`Sync`], all instances of the [`Runnable`]'s [`Waker`]
+/// must be used and dropped on the original thread.
+/// - If `schedule` is not `'static`, borrowed variables must outlive all instances of the
+/// [`Runnable`]'s [`Waker`].
+///
+/// # Examples
+///
+/// ```
+/// // The future inside the task.
+/// let future = async {
+/// println!("Hello, world!");
+/// };
+///
+/// // If the task gets woken up, it will be sent into this channel.
+/// let (s, r) = flume::unbounded();
+/// let schedule = move |runnable| s.send(runnable).unwrap();
+///
+/// // Create a task with the future and the schedule function.
+/// let (runnable, task) = unsafe { async_task::spawn_unchecked(future, schedule) };
+/// ```
+pub unsafe fn spawn_unchecked<F, S>(future: F, schedule: S) -> (Runnable, Task<F::Output>)
+where
+ F: Future,
+ S: Schedule,
+{
+ Builder::new().spawn_unchecked(move |()| future, schedule)
+}
+
+/// A handle to a runnable task.
+///
+/// Every spawned task has a single [`Runnable`] handle, which only exists when the task is
+/// scheduled for running.
+///
+/// Method [`run()`][`Runnable::run()`] polls the task's future once. Then, the [`Runnable`]
+/// vanishes and only reappears when its [`Waker`] wakes the task, thus scheduling it to be run
+/// again.
+///
+/// Dropping a [`Runnable`] cancels the task, which means its future won't be polled again, and
+/// awaiting the [`Task`] after that will result in a panic.
+///
+/// # Examples
+///
+/// ```
+/// use async_task::Runnable;
+/// use once_cell::sync::Lazy;
+/// use std::{panic, thread};
+///
+/// // A simple executor.
+/// static QUEUE: Lazy<flume::Sender<Runnable>> = Lazy::new(|| {
+/// let (sender, receiver) = flume::unbounded::<Runnable>();
+/// thread::spawn(|| {
+/// for runnable in receiver {
+/// let _ignore_panic = panic::catch_unwind(|| runnable.run());
+/// }
+/// });
+/// sender
+/// });
+///
+/// // Create a task with a simple future.
+/// let schedule = |runnable| QUEUE.send(runnable).unwrap();
+/// let (runnable, task) = async_task::spawn(async { 1 + 2 }, schedule);
+///
+/// // Schedule the task and await its output.
+/// runnable.schedule();
+/// assert_eq!(smol::future::block_on(task), 3);
+/// ```
+pub struct Runnable<M = ()> {
+ /// A pointer to the heap-allocated task.
+ pub(crate) ptr: NonNull<()>,
+
+ /// A marker capturing generic type `M`.
+ pub(crate) _marker: PhantomData<M>,
+}
+
+unsafe impl<M: Send + Sync> Send for Runnable<M> {}
+unsafe impl<M: Send + Sync> Sync for Runnable<M> {}
+
+#[cfg(feature = "std")]
+impl<M> std::panic::UnwindSafe for Runnable<M> {}
+#[cfg(feature = "std")]
+impl<M> std::panic::RefUnwindSafe for Runnable<M> {}
+
+impl<M> Runnable<M> {
+ /// Get the metadata associated with this task.
+ ///
+ /// Tasks can be created with a metadata object associated with them; by default, this
+ /// is a `()` value. See the [`Builder::metadata()`] method for more information.
+ pub fn metadata(&self) -> &M {
+ &self.header().metadata
+ }
+
+ /// Schedules the task.
+ ///
+ /// This is a convenience method that passes the [`Runnable`] to the schedule function.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// // A function that schedules the task when it gets woken up.
+ /// let (s, r) = flume::unbounded();
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with a simple future and the schedule function.
+ /// let (runnable, task) = async_task::spawn(async {}, schedule);
+ ///
+ /// // Schedule the task.
+ /// assert_eq!(r.len(), 0);
+ /// runnable.schedule();
+ /// assert_eq!(r.len(), 1);
+ /// ```
+ pub fn schedule(self) {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+ mem::forget(self);
+
+ unsafe {
+ ((*header).vtable.schedule)(ptr, ScheduleInfo::new(false));
+ }
+ }
+
+ /// Runs the task by polling its future.
+ ///
+ /// Returns `true` if the task was woken while running, in which case the [`Runnable`] gets
+ /// rescheduled at the end of this method invocation. Otherwise, returns `false` and the
+ /// [`Runnable`] vanishes until the task is woken.
+ /// The return value is just a hint: `true` usually indicates that the task has yielded, i.e.
+ /// it woke itself and then gave the control back to the executor.
+ ///
+ /// If the [`Task`] handle was dropped or if [`cancel()`][`Task::cancel()`] was called, then
+ /// this method simply destroys the task.
+ ///
+ /// If the polled future panics, this method propagates the panic, and awaiting the [`Task`]
+ /// after that will also result in a panic.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// // A function that schedules the task when it gets woken up.
+ /// let (s, r) = flume::unbounded();
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with a simple future and the schedule function.
+ /// let (runnable, task) = async_task::spawn(async { 1 + 2 }, schedule);
+ ///
+ /// // Run the task and check its output.
+ /// runnable.run();
+ /// assert_eq!(smol::future::block_on(task), 3);
+ /// ```
+ pub fn run(self) -> bool {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+ mem::forget(self);
+
+ unsafe { ((*header).vtable.run)(ptr) }
+ }
+
+ /// Returns a waker associated with this task.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use smol::future;
+ ///
+ /// // A function that schedules the task when it gets woken up.
+ /// let (s, r) = flume::unbounded();
+ /// let schedule = move |runnable| s.send(runnable).unwrap();
+ ///
+ /// // Create a task with a simple future and the schedule function.
+ /// let (runnable, task) = async_task::spawn(future::pending::<()>(), schedule);
+ ///
+ /// // Take a waker and run the task.
+ /// let waker = runnable.waker();
+ /// runnable.run();
+ ///
+ /// // Reschedule the task by waking it.
+ /// assert_eq!(r.len(), 0);
+ /// waker.wake();
+ /// assert_eq!(r.len(), 1);
+ /// ```
+ pub fn waker(&self) -> Waker {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ unsafe {
+ let raw_waker = ((*header).vtable.clone_waker)(ptr);
+ Waker::from_raw(raw_waker)
+ }
+ }
+
+ fn header(&self) -> &Header<M> {
+ unsafe { &*(self.ptr.as_ptr() as *const Header<M>) }
+ }
+
+ /// Converts this task into a raw pointer.
+ ///
+ /// To avoid a memory leak the pointer must be converted back to a Runnable using [`Runnable<M>::from_raw`][from_raw].
+ ///
+ /// `into_raw` does not change the state of the [`Task`], but there is no guarantee that it will be in the same state after calling [`Runnable<M>::from_raw`][from_raw],
+ /// as the corresponding [`Task`] might have been dropped or cancelled.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use async_task::{Runnable, spawn};
+
+ /// let (runnable, task) = spawn(async {}, |_| {});
+ /// let runnable_pointer = runnable.into_raw();
+ ///
+ /// unsafe {
+ /// // Convert back to an `Runnable` to prevent leak.
+ /// let runnable = Runnable::<()>::from_raw(runnable_pointer);
+ /// runnable.run();
+ /// // Further calls to `Runnable::from_raw(runnable_pointer)` would be memory-unsafe.
+ /// }
+ /// // The memory was freed when `x` went out of scope above, so `runnable_pointer` is now dangling!
+ /// ```
+ /// [from_raw]: #method.from_raw
+ pub fn into_raw(self) -> NonNull<()> {
+ let ptr = self.ptr;
+ mem::forget(self);
+ ptr
+ }
+
+ /// Converts a raw pointer into a Runnable.
+ ///
+ /// # Safety
+ ///
+ /// This method should only be used with raw pointers returned from [`Runnable<M>::into_raw`][into_raw].
+ /// It is not safe to use the provided pointer once it is passed to `from_raw`.
+ /// Crucially, it is unsafe to call `from_raw` multiple times with the same pointer - even if the resulting [`Runnable`] is not used -
+ /// as internally `async-task` uses reference counting.
+ ///
+ /// It is however safe to call [`Runnable<M>::into_raw`][into_raw] on a [`Runnable`] created with `from_raw` or
+ /// after the [`Task`] associated with a given Runnable has been dropped or cancelled.
+ ///
+ /// The state of the [`Runnable`] created with `from_raw` is not specified.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use async_task::{Runnable, spawn};
+
+ /// let (runnable, task) = spawn(async {}, |_| {});
+ /// let runnable_pointer = runnable.into_raw();
+ ///
+ /// drop(task);
+ /// unsafe {
+ /// // Convert back to an `Runnable` to prevent leak.
+ /// let runnable = Runnable::<()>::from_raw(runnable_pointer);
+ /// let did_poll = runnable.run();
+ /// assert!(!did_poll);
+ /// // Further calls to `Runnable::from_raw(runnable_pointer)` would be memory-unsafe.
+ /// }
+ /// // The memory was freed when `x` went out of scope above, so `runnable_pointer` is now dangling!
+ /// ```
+
+ /// [into_raw]: #method.into_raw
+ pub unsafe fn from_raw(ptr: NonNull<()>) -> Self {
+ Self {
+ ptr,
+ _marker: Default::default(),
+ }
+ }
+}
+
+impl<M> Drop for Runnable<M> {
+ fn drop(&mut self) {
+ let ptr = self.ptr.as_ptr();
+ let header = self.header();
+
+ unsafe {
+ let mut state = header.state.load(Ordering::Acquire);
+
+ loop {
+ // If the task has been completed or closed, it can't be canceled.
+ if state & (COMPLETED | CLOSED) != 0 {
+ break;
+ }
+
+ // Mark the task as closed.
+ match header.state.compare_exchange_weak(
+ state,
+ state | CLOSED,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => break,
+ Err(s) => state = s,
+ }
+ }
+
+ // Drop the future.
+ (header.vtable.drop_future)(ptr);
+
+ // Mark the task as unscheduled.
+ let state = header.state.fetch_and(!SCHEDULED, Ordering::AcqRel);
+
+ // Notify the awaiter that the future has been dropped.
+ if state & AWAITER != 0 {
+ (*header).notify(None);
+ }
+
+ // Drop the task reference.
+ (header.vtable.drop_ref)(ptr);
+ }
+ }
+}
+
+impl<M: fmt::Debug> fmt::Debug for Runnable<M> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ f.debug_struct("Runnable")
+ .field("header", unsafe { &(*header) })
+ .finish()
+ }
+}
diff --git a/external/vendor/async-task/src/state.rs b/external/vendor/async-task/src/state.rs
new file mode 100644
index 0000000..2fc6cf3
--- /dev/null
+++ b/external/vendor/async-task/src/state.rs
@@ -0,0 +1,69 @@
+/// Set if the task is scheduled for running.
+///
+/// A task is considered to be scheduled whenever its `Runnable` exists.
+///
+/// This flag can't be set when the task is completed. However, it can be set while the task is
+/// running, in which case it will be rescheduled as soon as polling finishes.
+pub(crate) const SCHEDULED: usize = 1 << 0;
+
+/// Set if the task is running.
+///
+/// A task is in running state while its future is being polled.
+///
+/// This flag can't be set when the task is completed. However, it can be in scheduled state while
+/// it is running, in which case it will be rescheduled as soon as polling finishes.
+pub(crate) const RUNNING: usize = 1 << 1;
+
+/// Set if the task has been completed.
+///
+/// This flag is set when polling returns `Poll::Ready`. The output of the future is then stored
+/// inside the task until it becomes closed. In fact, `Task` picks up the output by marking
+/// the task as closed.
+///
+/// This flag can't be set when the task is scheduled or running.
+pub(crate) const COMPLETED: usize = 1 << 2;
+
+/// Set if the task is closed.
+///
+/// If a task is closed, that means it's either canceled or its output has been consumed by the
+/// `Task`. A task becomes closed in the following cases:
+///
+/// 1. It gets canceled by `Runnable::drop()`, `Task::drop()`, or `Task::cancel()`.
+/// 2. Its output gets awaited by the `Task`.
+/// 3. It panics while polling the future.
+/// 4. It is completed and the `Task` gets dropped.
+pub(crate) const CLOSED: usize = 1 << 3;
+
+/// Set if the `Task` still exists.
+///
+/// The `Task` is a special case in that it is only tracked by this flag, while all other
+/// task references (`Runnable` and `Waker`s) are tracked by the reference count.
+pub(crate) const TASK: usize = 1 << 4;
+
+/// Set if the `Task` is awaiting the output.
+///
+/// This flag is set while there is a registered awaiter of type `Waker` inside the task. When the
+/// task gets closed or completed, we need to wake the awaiter. This flag can be used as a fast
+/// check that tells us if we need to wake anyone.
+pub(crate) const AWAITER: usize = 1 << 5;
+
+/// Set if an awaiter is being registered.
+///
+/// This flag is set when `Task` is polled and we are registering a new awaiter.
+pub(crate) const REGISTERING: usize = 1 << 6;
+
+/// Set if the awaiter is being notified.
+///
+/// This flag is set when notifying the awaiter. If an awaiter is concurrently registered and
+/// notified, whichever side came first will take over the reposibility of resolving the race.
+pub(crate) const NOTIFYING: usize = 1 << 7;
+
+/// A single reference.
+///
+/// The lower bits in the state contain various flags representing the task state, while the upper
+/// bits contain the reference count. The value of `REFERENCE` represents a single reference in the
+/// total reference count.
+///
+/// Note that the reference counter only tracks the `Runnable` and `Waker`s. The `Task` is
+/// tracked separately by the `TASK` flag.
+pub(crate) const REFERENCE: usize = 1 << 8;
diff --git a/external/vendor/async-task/src/task.rs b/external/vendor/async-task/src/task.rs
new file mode 100644
index 0000000..da45cd8
--- /dev/null
+++ b/external/vendor/async-task/src/task.rs
@@ -0,0 +1,565 @@
+use core::fmt;
+use core::future::Future;
+use core::marker::PhantomData;
+use core::mem;
+use core::pin::Pin;
+use core::ptr::NonNull;
+use core::sync::atomic::Ordering;
+use core::task::{Context, Poll};
+
+use crate::header::Header;
+use crate::raw::Panic;
+use crate::runnable::ScheduleInfo;
+use crate::state::*;
+
+/// A spawned task.
+///
+/// A [`Task`] can be awaited to retrieve the output of its future.
+///
+/// Dropping a [`Task`] cancels it, which means its future won't be polled again. To drop the
+/// [`Task`] handle without canceling it, use [`detach()`][`Task::detach()`] instead. To cancel a
+/// task gracefully and wait until it is fully destroyed, use the [`cancel()`][Task::cancel()]
+/// method.
+///
+/// Note that canceling a task actually wakes it and reschedules one last time. Then, the executor
+/// can destroy the task by simply dropping its [`Runnable`][`super::Runnable`] or by invoking
+/// [`run()`][`super::Runnable::run()`].
+///
+/// # Examples
+///
+/// ```
+/// use smol::{future, Executor};
+/// use std::thread;
+///
+/// let ex = Executor::new();
+///
+/// // Spawn a future onto the executor.
+/// let task = ex.spawn(async {
+/// println!("Hello from a task!");
+/// 1 + 2
+/// });
+///
+/// // Run an executor thread.
+/// thread::spawn(move || future::block_on(ex.run(future::pending::<()>())));
+///
+/// // Wait for the task's output.
+/// assert_eq!(future::block_on(task), 3);
+/// ```
+#[must_use = "tasks get canceled when dropped, use `.detach()` to run them in the background"]
+pub struct Task<T, M = ()> {
+ /// A raw task pointer.
+ pub(crate) ptr: NonNull<()>,
+
+ /// A marker capturing generic types `T` and `M`.
+ pub(crate) _marker: PhantomData<(T, M)>,
+}
+
+unsafe impl<T: Send, M: Send + Sync> Send for Task<T, M> {}
+unsafe impl<T, M: Send + Sync> Sync for Task<T, M> {}
+
+impl<T, M> Unpin for Task<T, M> {}
+
+#[cfg(feature = "std")]
+impl<T, M> std::panic::UnwindSafe for Task<T, M> {}
+#[cfg(feature = "std")]
+impl<T, M> std::panic::RefUnwindSafe for Task<T, M> {}
+
+impl<T, M> Task<T, M> {
+ /// Detaches the task to let it keep running in the background.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use smol::{Executor, Timer};
+ /// use std::time::Duration;
+ ///
+ /// let ex = Executor::new();
+ ///
+ /// // Spawn a deamon future.
+ /// ex.spawn(async {
+ /// loop {
+ /// println!("I'm a daemon task looping forever.");
+ /// Timer::after(Duration::from_secs(1)).await;
+ /// }
+ /// })
+ /// .detach();
+ /// ```
+ pub fn detach(self) {
+ let mut this = self;
+ let _out = this.set_detached();
+ mem::forget(this);
+ }
+
+ /// Cancels the task and waits for it to stop running.
+ ///
+ /// Returns the task's output if it was completed just before it got canceled, or [`None`] if
+ /// it didn't complete.
+ ///
+ /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of
+ /// canceling because it also waits for the task to stop running.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # if cfg!(miri) { return; } // Miri does not support epoll
+ /// use smol::{future, Executor, Timer};
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let ex = Executor::new();
+ ///
+ /// // Spawn a deamon future.
+ /// let task = ex.spawn(async {
+ /// loop {
+ /// println!("Even though I'm in an infinite loop, you can still cancel me!");
+ /// Timer::after(Duration::from_secs(1)).await;
+ /// }
+ /// });
+ ///
+ /// // Run an executor thread.
+ /// thread::spawn(move || future::block_on(ex.run(future::pending::<()>())));
+ ///
+ /// future::block_on(async {
+ /// Timer::after(Duration::from_secs(3)).await;
+ /// task.cancel().await;
+ /// });
+ /// ```
+ pub async fn cancel(self) -> Option<T> {
+ let mut this = self;
+ this.set_canceled();
+ this.fallible().await
+ }
+
+ /// Converts this task into a [`FallibleTask`].
+ ///
+ /// Like [`Task`], a fallible task will poll the task's output until it is
+ /// completed or cancelled due to its [`Runnable`][`super::Runnable`] being
+ /// dropped without being run. Resolves to the task's output when completed,
+ /// or [`None`] if it didn't complete.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use smol::{future, Executor};
+ /// use std::thread;
+ ///
+ /// let ex = Executor::new();
+ ///
+ /// // Spawn a future onto the executor.
+ /// let task = ex.spawn(async {
+ /// println!("Hello from a task!");
+ /// 1 + 2
+ /// })
+ /// .fallible();
+ ///
+ /// // Run an executor thread.
+ /// thread::spawn(move || future::block_on(ex.run(future::pending::<()>())));
+ ///
+ /// // Wait for the task's output.
+ /// assert_eq!(future::block_on(task), Some(3));
+ /// ```
+ ///
+ /// ```
+ /// use smol::future;
+ ///
+ /// // Schedule function which drops the runnable without running it.
+ /// let schedule = move |runnable| drop(runnable);
+ ///
+ /// // Create a task with the future and the schedule function.
+ /// let (runnable, task) = async_task::spawn(async {
+ /// println!("Hello from a task!");
+ /// 1 + 2
+ /// }, schedule);
+ /// runnable.schedule();
+ ///
+ /// // Wait for the task's output.
+ /// assert_eq!(future::block_on(task.fallible()), None);
+ /// ```
+ pub fn fallible(self) -> FallibleTask<T, M> {
+ FallibleTask { task: self }
+ }
+
+ /// Puts the task in canceled state.
+ fn set_canceled(&mut self) {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ unsafe {
+ let mut state = (*header).state.load(Ordering::Acquire);
+
+ loop {
+ // If the task has been completed or closed, it can't be canceled.
+ if state & (COMPLETED | CLOSED) != 0 {
+ break;
+ }
+
+ // If the task is not scheduled nor running, we'll need to schedule it.
+ let new = if state & (SCHEDULED | RUNNING) == 0 {
+ (state | SCHEDULED | CLOSED) + REFERENCE
+ } else {
+ state | CLOSED
+ };
+
+ // Mark the task as closed.
+ match (*header).state.compare_exchange_weak(
+ state,
+ new,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // If the task is not scheduled nor running, schedule it one more time so
+ // that its future gets dropped by the executor.
+ if state & (SCHEDULED | RUNNING) == 0 {
+ ((*header).vtable.schedule)(ptr, ScheduleInfo::new(false));
+ }
+
+ // Notify the awaiter that the task has been closed.
+ if state & AWAITER != 0 {
+ (*header).notify(None);
+ }
+
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ /// Puts the task in detached state.
+ fn set_detached(&mut self) -> Option<Result<T, Panic>> {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ unsafe {
+ // A place where the output will be stored in case it needs to be dropped.
+ let mut output = None;
+
+ // Optimistically assume the `Task` is being detached just after creating the task.
+ // This is a common case so if the `Task` is datached, the overhead of it is only one
+ // compare-exchange operation.
+ if let Err(mut state) = (*header).state.compare_exchange_weak(
+ SCHEDULED | TASK | REFERENCE,
+ SCHEDULED | REFERENCE,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ loop {
+ // If the task has been completed but not yet closed, that means its output
+ // must be dropped.
+ if state & COMPLETED != 0 && state & CLOSED == 0 {
+ // Mark the task as closed in order to grab its output.
+ match (*header).state.compare_exchange_weak(
+ state,
+ state | CLOSED,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // Read the output.
+ output = Some(
+ (((*header).vtable.get_output)(ptr) as *mut Result<T, Panic>)
+ .read(),
+ );
+
+ // Update the state variable because we're continuing the loop.
+ state |= CLOSED;
+ }
+ Err(s) => state = s,
+ }
+ } else {
+ // If this is the last reference to the task and it's not closed, then
+ // close it and schedule one more time so that its future gets dropped by
+ // the executor.
+ let new = if state & (!(REFERENCE - 1) | CLOSED) == 0 {
+ SCHEDULED | CLOSED | REFERENCE
+ } else {
+ state & !TASK
+ };
+
+ // Unset the `TASK` flag.
+ match (*header).state.compare_exchange_weak(
+ state,
+ new,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // If this is the last reference to the task, we need to either
+ // schedule dropping its future or destroy it.
+ if state & !(REFERENCE - 1) == 0 {
+ if state & CLOSED == 0 {
+ ((*header).vtable.schedule)(ptr, ScheduleInfo::new(false));
+ } else {
+ ((*header).vtable.destroy)(ptr);
+ }
+ }
+
+ break;
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ output
+ }
+ }
+
+ /// Polls the task to retrieve its output.
+ ///
+ /// Returns `Some` if the task has completed or `None` if it was closed.
+ ///
+ /// A task becomes closed in the following cases:
+ ///
+ /// 1. It gets canceled by `Runnable::drop()`, `Task::drop()`, or `Task::cancel()`.
+ /// 2. Its output gets awaited by the `Task`.
+ /// 3. It panics while polling the future.
+ /// 4. It is completed and the `Task` gets dropped.
+ fn poll_task(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ unsafe {
+ let mut state = (*header).state.load(Ordering::Acquire);
+
+ loop {
+ // If the task has been closed, notify the awaiter and return `None`.
+ if state & CLOSED != 0 {
+ // If the task is scheduled or running, we need to wait until its future is
+ // dropped.
+ if state & (SCHEDULED | RUNNING) != 0 {
+ // Replace the waker with one associated with the current task.
+ (*header).register(cx.waker());
+
+ // Reload the state after registering. It is possible changes occurred just
+ // before registration so we need to check for that.
+ state = (*header).state.load(Ordering::Acquire);
+
+ // If the task is still scheduled or running, we need to wait because its
+ // future is not dropped yet.
+ if state & (SCHEDULED | RUNNING) != 0 {
+ return Poll::Pending;
+ }
+ }
+
+ // Even though the awaiter is most likely the current task, it could also be
+ // another task.
+ (*header).notify(Some(cx.waker()));
+ return Poll::Ready(None);
+ }
+
+ // If the task is not completed, register the current task.
+ if state & COMPLETED == 0 {
+ // Replace the waker with one associated with the current task.
+ (*header).register(cx.waker());
+
+ // Reload the state after registering. It is possible that the task became
+ // completed or closed just before registration so we need to check for that.
+ state = (*header).state.load(Ordering::Acquire);
+
+ // If the task has been closed, restart.
+ if state & CLOSED != 0 {
+ continue;
+ }
+
+ // If the task is still not completed, we're blocked on it.
+ if state & COMPLETED == 0 {
+ return Poll::Pending;
+ }
+ }
+
+ // Since the task is now completed, mark it as closed in order to grab its output.
+ match (*header).state.compare_exchange(
+ state,
+ state | CLOSED,
+ Ordering::AcqRel,
+ Ordering::Acquire,
+ ) {
+ Ok(_) => {
+ // Notify the awaiter. Even though the awaiter is most likely the current
+ // task, it could also be another task.
+ if state & AWAITER != 0 {
+ (*header).notify(Some(cx.waker()));
+ }
+
+ // Take the output from the task.
+ let output = ((*header).vtable.get_output)(ptr) as *mut Result<T, Panic>;
+ let output = output.read();
+
+ // Propagate the panic if the task panicked.
+ let output = match output {
+ Ok(output) => output,
+ Err(panic) => {
+ #[cfg(feature = "std")]
+ std::panic::resume_unwind(panic);
+
+ #[cfg(not(feature = "std"))]
+ match panic {}
+ }
+ };
+
+ return Poll::Ready(Some(output));
+ }
+ Err(s) => state = s,
+ }
+ }
+ }
+ }
+
+ fn header(&self) -> &Header<M> {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+ unsafe { &*header }
+ }
+
+ /// Returns `true` if the current task is finished.
+ ///
+ /// Note that in a multithreaded environment, this task can change finish immediately after calling this function.
+ pub fn is_finished(&self) -> bool {
+ let ptr = self.ptr.as_ptr();
+ let header = ptr as *const Header<M>;
+
+ unsafe {
+ let state = (*header).state.load(Ordering::Acquire);
+ state & (CLOSED | COMPLETED) != 0
+ }
+ }
+
+ /// Get the metadata associated with this task.
+ ///
+ /// Tasks can be created with a metadata object associated with them; by default, this
+ /// is a `()` value. See the [`Builder::metadata()`] method for more information.
+ pub fn metadata(&self) -> &M {
+ &self.header().metadata
+ }
+}
+
+impl<T, M> Drop for Task<T, M> {
+ fn drop(&mut self) {
+ self.set_canceled();
+ self.set_detached();
+ }
+}
+
+impl<T, M> Future for Task<T, M> {
+ type Output = T;
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ match self.poll_task(cx) {
+ Poll::Ready(t) => Poll::Ready(t.expect("Task polled after completion")),
+ Poll::Pending => Poll::Pending,
+ }
+ }
+}
+
+impl<T, M: fmt::Debug> fmt::Debug for Task<T, M> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Task")
+ .field("header", self.header())
+ .finish()
+ }
+}
+
+/// A spawned task with a fallible response.
+///
+/// This type behaves like [`Task`], however it produces an `Option<T>` when
+/// polled and will return `None` if the executor dropped its
+/// [`Runnable`][`super::Runnable`] without being run.
+///
+/// This can be useful to avoid the panic produced when polling the `Task`
+/// future if the executor dropped its `Runnable`.
+#[must_use = "tasks get canceled when dropped, use `.detach()` to run them in the background"]
+pub struct FallibleTask<T, M = ()> {
+ task: Task<T, M>,
+}
+
+impl<T, M> FallibleTask<T, M> {
+ /// Detaches the task to let it keep running in the background.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use smol::{Executor, Timer};
+ /// use std::time::Duration;
+ ///
+ /// let ex = Executor::new();
+ ///
+ /// // Spawn a deamon future.
+ /// ex.spawn(async {
+ /// loop {
+ /// println!("I'm a daemon task looping forever.");
+ /// Timer::after(Duration::from_secs(1)).await;
+ /// }
+ /// })
+ /// .fallible()
+ /// .detach();
+ /// ```
+ pub fn detach(self) {
+ self.task.detach()
+ }
+
+ /// Cancels the task and waits for it to stop running.
+ ///
+ /// Returns the task's output if it was completed just before it got canceled, or [`None`] if
+ /// it didn't complete.
+ ///
+ /// While it's possible to simply drop the [`Task`] to cancel it, this is a cleaner way of
+ /// canceling because it also waits for the task to stop running.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # if cfg!(miri) { return; } // Miri does not support epoll
+ /// use smol::{future, Executor, Timer};
+ /// use std::thread;
+ /// use std::time::Duration;
+ ///
+ /// let ex = Executor::new();
+ ///
+ /// // Spawn a deamon future.
+ /// let task = ex.spawn(async {
+ /// loop {
+ /// println!("Even though I'm in an infinite loop, you can still cancel me!");
+ /// Timer::after(Duration::from_secs(1)).await;
+ /// }
+ /// })
+ /// .fallible();
+ ///
+ /// // Run an executor thread.
+ /// thread::spawn(move || future::block_on(ex.run(future::pending::<()>())));
+ ///
+ /// future::block_on(async {
+ /// Timer::after(Duration::from_secs(3)).await;
+ /// task.cancel().await;
+ /// });
+ /// ```
+ pub async fn cancel(self) -> Option<T> {
+ self.task.cancel().await
+ }
+
+ /// Returns `true` if the current task is finished.
+ ///
+ /// Note that in a multithreaded environment, this task can change finish immediately after calling this function.
+ pub fn is_finished(&self) -> bool {
+ self.task.is_finished()
+ }
+}
+
+impl<T, M> Future for FallibleTask<T, M> {
+ type Output = Option<T>;
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ self.task.poll_task(cx)
+ }
+}
+
+impl<T, M: fmt::Debug> fmt::Debug for FallibleTask<T, M> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("FallibleTask")
+ .field("header", self.task.header())
+ .finish()
+ }
+}
diff --git a/external/vendor/async-task/src/utils.rs b/external/vendor/async-task/src/utils.rs
new file mode 100644
index 0000000..5c2170c
--- /dev/null
+++ b/external/vendor/async-task/src/utils.rs
@@ -0,0 +1,127 @@
+use core::alloc::Layout as StdLayout;
+use core::mem;
+
+/// Aborts the process.
+///
+/// To abort, this function simply panics while panicking.
+pub(crate) fn abort() -> ! {
+ struct Panic;
+
+ impl Drop for Panic {
+ fn drop(&mut self) {
+ panic!("aborting the process");
+ }
+ }
+
+ let _panic = Panic;
+ panic!("aborting the process");
+}
+
+/// Calls a function and aborts if it panics.
+///
+/// This is useful in unsafe code where we can't recover from panics.
+#[inline]
+pub(crate) fn abort_on_panic<T>(f: impl FnOnce() -> T) -> T {
+ struct Bomb;
+
+ impl Drop for Bomb {
+ fn drop(&mut self) {
+ abort();
+ }
+ }
+
+ let bomb = Bomb;
+ let t = f();
+ mem::forget(bomb);
+ t
+}
+
+/// A version of `alloc::alloc::Layout` that can be used in the const
+/// position.
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct Layout {
+ size: usize,
+ align: usize,
+}
+
+impl Layout {
+ /// Creates a new `Layout` with the given size and alignment.
+ #[inline]
+ pub(crate) const fn from_size_align(size: usize, align: usize) -> Self {
+ Self { size, align }
+ }
+
+ /// Creates a new `Layout` for the given sized type.
+ #[inline]
+ pub(crate) const fn new<T>() -> Self {
+ Self::from_size_align(mem::size_of::<T>(), mem::align_of::<T>())
+ }
+
+ /// Convert this into the standard library's layout type.
+ ///
+ /// # Safety
+ ///
+ /// - `align` must be non-zero and a power of two.
+ /// - When rounded up to the nearest multiple of `align`, the size
+ /// must not overflow.
+ #[inline]
+ pub(crate) const unsafe fn into_std(self) -> StdLayout {
+ StdLayout::from_size_align_unchecked(self.size, self.align)
+ }
+
+ /// Get the alignment of this layout.
+ #[inline]
+ pub(crate) const fn align(&self) -> usize {
+ self.align
+ }
+
+ /// Get the size of this layout.
+ #[inline]
+ pub(crate) const fn size(&self) -> usize {
+ self.size
+ }
+
+ /// Returns the layout for `a` followed by `b` and the offset of `b`.
+ ///
+ /// This function was adapted from the `Layout::extend()`:
+ /// https://doc.rust-lang.org/nightly/std/alloc/struct.Layout.html#method.extend
+ #[inline]
+ pub(crate) const fn extend(self, other: Layout) -> Option<(Layout, usize)> {
+ let new_align = max(self.align(), other.align());
+ let pad = self.padding_needed_for(other.align());
+
+ let offset = leap!(self.size().checked_add(pad));
+ let new_size = leap!(offset.checked_add(other.size()));
+
+ // return None if any of the following are true:
+ // - align is 0 (implied false by is_power_of_two())
+ // - align is not a power of 2
+ // - size rounded up to align overflows
+ if !new_align.is_power_of_two() || new_size > isize::MAX as usize - (new_align - 1) {
+ return None;
+ }
+
+ let layout = Layout::from_size_align(new_size, new_align);
+ Some((layout, offset))
+ }
+
+ /// Returns the padding after `layout` that aligns the following address to `align`.
+ ///
+ /// This function was adapted from the `Layout::padding_needed_for()`:
+ /// https://doc.rust-lang.org/nightly/std/alloc/struct.Layout.html#method.padding_needed_for
+ #[inline]
+ pub(crate) const fn padding_needed_for(self, align: usize) -> usize {
+ let len = self.size();
+ let len_rounded_up = len.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1);
+ len_rounded_up.wrapping_sub(len)
+ }
+}
+
+#[inline]
+pub(crate) const fn max(left: usize, right: usize) -> usize {
+ if left > right {
+ left
+ } else {
+ right
+ }
+}
diff --git a/external/vendor/async-task/tests/basic.rs b/external/vendor/async-task/tests/basic.rs
new file mode 100644
index 0000000..727a05e
--- /dev/null
+++ b/external/vendor/async-task/tests/basic.rs
@@ -0,0 +1,325 @@
+use std::future::Future;
+use std::pin::Pin;
+use std::ptr::NonNull;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::task::{Context, Poll};
+
+use async_task::Runnable;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, POLL, DROP)`
+//
+// The future `f` always returns `Poll::Ready`.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! future {
+ ($name:pat, $poll:ident, $drop:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = Box<i32>;
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ $poll.fetch_add(1, Ordering::SeqCst);
+ Poll::Ready(Box::new(0))
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ Fut(Box::new(0))
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, SCHED, DROP)`
+//
+// The schedule function `s` does nothing.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! schedule {
+ ($name:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ move |_runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ }
+ };
+ };
+}
+
+fn try_await<T>(f: impl Future<Output = T>) -> Option<T> {
+ future::block_on(future::poll_once(f))
+}
+
+#[test]
+fn drop_and_detach() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ drop(runnable);
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn detach_and_drop() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ drop(runnable);
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn detach_and_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn run_and_detach() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn cancel_and_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn run_and_cancel() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn cancel_join() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ assert!(try_await(&mut task).is_none());
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(try_await(&mut task).is_some());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn schedule() {
+ let (s, r) = flume::unbounded();
+ let schedule = move |runnable| s.send(runnable).unwrap();
+ let (runnable, _task) = async_task::spawn(future::poll_fn(|_| Poll::<()>::Pending), schedule);
+
+ assert!(r.is_empty());
+ runnable.schedule();
+
+ let runnable = r.recv().unwrap();
+ assert!(r.is_empty());
+ runnable.schedule();
+
+ let runnable = r.recv().unwrap();
+ assert!(r.is_empty());
+ runnable.schedule();
+
+ r.recv().unwrap();
+}
+
+#[test]
+fn schedule_counter() {
+ static COUNT: AtomicUsize = AtomicUsize::new(0);
+
+ let (s, r) = flume::unbounded();
+ let schedule = move |runnable: Runnable| {
+ COUNT.fetch_add(1, Ordering::SeqCst);
+ s.send(runnable).unwrap();
+ };
+ let (runnable, _task) = async_task::spawn(future::poll_fn(|_| Poll::<()>::Pending), schedule);
+ runnable.schedule();
+
+ r.recv().unwrap().schedule();
+ r.recv().unwrap().schedule();
+ assert_eq!(COUNT.load(Ordering::SeqCst), 3);
+ r.recv().unwrap();
+}
+
+#[test]
+fn drop_inside_schedule() {
+ struct DropGuard(AtomicUsize);
+ impl Drop for DropGuard {
+ fn drop(&mut self) {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ let guard = DropGuard(AtomicUsize::new(0));
+
+ let (runnable, _) = async_task::spawn(async {}, move |runnable| {
+ assert_eq!(guard.0.load(Ordering::SeqCst), 0);
+ drop(runnable);
+ assert_eq!(guard.0.load(Ordering::SeqCst), 0);
+ });
+ runnable.schedule();
+}
+
+#[test]
+fn waker() {
+ let (s, r) = flume::unbounded();
+ let schedule = move |runnable| s.send(runnable).unwrap();
+ let (runnable, _task) = async_task::spawn(future::poll_fn(|_| Poll::<()>::Pending), schedule);
+
+ assert!(r.is_empty());
+ let waker = runnable.waker();
+ runnable.run();
+ waker.wake_by_ref();
+
+ let runnable = r.recv().unwrap();
+ runnable.run();
+ waker.wake();
+ r.recv().unwrap();
+}
+
+#[test]
+fn raw() {
+ // Dispatch schedules a function for execution at a later point. For tests, we execute it straight away.
+ fn dispatch(trampoline: extern "C" fn(NonNull<()>), context: NonNull<()>) {
+ trampoline(context)
+ }
+ extern "C" fn trampoline(runnable: NonNull<()>) {
+ let task = unsafe { Runnable::<()>::from_raw(runnable) };
+ task.run();
+ }
+
+ let task_got_executed = Arc::new(AtomicBool::new(false));
+ let (runnable, _handle) = async_task::spawn(
+ {
+ let task_got_executed = task_got_executed.clone();
+ async move { task_got_executed.store(true, Ordering::SeqCst) }
+ },
+ |runnable: Runnable<()>| dispatch(trampoline, runnable.into_raw()),
+ );
+ runnable.schedule();
+
+ assert!(task_got_executed.load(Ordering::SeqCst));
+}
diff --git a/external/vendor/async-task/tests/cancel.rs b/external/vendor/async-task/tests/cancel.rs
new file mode 100644
index 0000000..0333367
--- /dev/null
+++ b/external/vendor/async-task/tests/cancel.rs
@@ -0,0 +1,183 @@
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use easy_parallel::Parallel;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, POLL, DROP_F, DROP_T)`
+//
+// The future `f` outputs `Poll::Ready`.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP_F` is incremented.
+// When the output gets dropped, `DROP_T` is incremented.
+macro_rules! future {
+ ($name:pat, $poll:ident, $drop_f:ident, $drop_t:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop_f: AtomicUsize = AtomicUsize::new(0);
+ static $drop_t: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = Out;
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(400));
+ Poll::Ready(Out(Box::new(0), true))
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop_f.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ #[derive(Default)]
+ struct Out(#[allow(dead_code)] Box<i32>, bool);
+
+ impl Drop for Out {
+ fn drop(&mut self) {
+ if self.1 {
+ $drop_t.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ }
+
+ Fut(Box::new(0))
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, SCHED, DROP)`
+//
+// The schedule function `s` does nothing.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! schedule {
+ ($name:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ move |runnable: Runnable| {
+ let _ = &guard;
+ runnable.schedule();
+ $sched.fetch_add(1, Ordering::SeqCst);
+ }
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn run_and_cancel() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(future::block_on(task.cancel()).is_some());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn cancel_and_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(200));
+ runnable.run();
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ thread::sleep(ms(200));
+
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ assert!(future::block_on(task.cancel()).is_none());
+
+ thread::sleep(ms(200));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ thread::sleep(ms(200));
+
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn cancel_during_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+
+ thread::sleep(ms(200));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ assert!(future::block_on(task.cancel()).is_none());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
diff --git a/external/vendor/async-task/tests/join.rs b/external/vendor/async-task/tests/join.rs
new file mode 100644
index 0000000..089b5c1
--- /dev/null
+++ b/external/vendor/async-task/tests/join.rs
@@ -0,0 +1,386 @@
+use std::cell::Cell;
+use std::future::Future;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use easy_parallel::Parallel;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, POLL, DROP_F, DROP_T)`
+//
+// The future `f` outputs `Poll::Ready`.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP_F` is incremented.
+// When the output gets dropped, `DROP_T` is incremented.
+macro_rules! future {
+ ($name:pat, $poll:ident, $drop_f:ident, $drop_t:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop_f: AtomicUsize = AtomicUsize::new(0);
+ static $drop_t: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = Out;
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ $poll.fetch_add(1, Ordering::SeqCst);
+ Poll::Ready(Out(Box::new(0), true))
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop_f.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ #[derive(Default)]
+ struct Out(#[allow(dead_code)] Box<i32>, bool);
+
+ impl Drop for Out {
+ fn drop(&mut self) {
+ if self.1 {
+ $drop_t.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ }
+
+ Fut(Box::new(0))
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, SCHED, DROP)`
+//
+// The schedule function `s` does nothing.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! schedule {
+ ($name:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ move |runnable: Runnable| {
+ let _ = &guard;
+ runnable.schedule();
+ $sched.fetch_add(1, Ordering::SeqCst);
+ }
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn drop_and_join() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ drop(runnable);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(|| future::block_on(task)).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+}
+
+#[test]
+fn run_and_join() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(|| future::block_on(task)).is_ok());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn detach_and_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ task.detach();
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn join_twice() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ runnable.run();
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ future::block_on(&mut task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+
+ assert!(catch_unwind(AssertUnwindSafe(|| future::block_on(&mut task))).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+
+ task.detach();
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn join_and_cancel() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(200));
+ drop(runnable);
+
+ thread::sleep(ms(400));
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ assert!(catch_unwind(|| future::block_on(task)).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn join_and_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(400));
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ future::block_on(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn try_join_and_run_and_join() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(400));
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ future::block_on(future::or(&mut task, future::ready(Default::default())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ future::block_on(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn try_join_and_cancel_and_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(200));
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ future::block_on(future::or(&mut task, future::ready(Default::default())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ })
+ .run();
+}
+
+#[test]
+fn try_join_and_run_and_cancel() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ thread::sleep(ms(200));
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ })
+ .add(|| {
+ future::block_on(future::or(&mut task, future::ready(Default::default())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ thread::sleep(ms(400));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn await_output() {
+ struct Fut<T>(Cell<Option<T>>);
+
+ impl<T> Fut<T> {
+ fn new(t: T) -> Fut<T> {
+ Fut(Cell::new(Some(t)))
+ }
+ }
+
+ impl<T> Future for Fut<T> {
+ type Output = T;
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ Poll::Ready(self.0.take().unwrap())
+ }
+ }
+
+ for i in 0..10 {
+ let (runnable, task) = async_task::spawn(Fut::new(i), drop);
+ runnable.run();
+ assert_eq!(future::block_on(task), i);
+ }
+
+ for i in 0..10 {
+ let (runnable, task) = async_task::spawn(Fut::new(vec![7; i]), drop);
+ runnable.run();
+ assert_eq!(future::block_on(task), vec![7; i]);
+ }
+
+ let (runnable, task) = async_task::spawn(Fut::new("foo".to_string()), drop);
+ runnable.run();
+ assert_eq!(future::block_on(task), "foo");
+}
diff --git a/external/vendor/async-task/tests/metadata.rs b/external/vendor/async-task/tests/metadata.rs
new file mode 100644
index 0000000..d3d8d53
--- /dev/null
+++ b/external/vendor/async-task/tests/metadata.rs
@@ -0,0 +1,58 @@
+use async_task::{Builder, Runnable};
+use flume::unbounded;
+use smol::future;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+#[test]
+fn metadata_use_case() {
+ // Each future has a counter that is incremented every time it is scheduled.
+ let (sender, receiver) = unbounded::<Runnable<AtomicUsize>>();
+ let schedule = move |runnable: Runnable<AtomicUsize>| {
+ runnable.metadata().fetch_add(1, Ordering::SeqCst);
+ sender.send(runnable).ok();
+ };
+
+ async fn my_future(counter: &AtomicUsize) {
+ loop {
+ // Loop until we've been scheduled five times.
+ let count = counter.load(Ordering::SeqCst);
+ if count < 5 {
+ // Make sure that we are immediately scheduled again.
+ future::yield_now().await;
+ continue;
+ }
+
+ // We've been scheduled five times, so we're done.
+ break;
+ }
+ }
+
+ let make_task = || {
+ // SAFETY: We are spawning a non-'static future, so we need to use the unsafe API.
+ // The borrowed variables, in this case the metadata, are guaranteed to outlive the runnable.
+ let (runnable, task) = unsafe {
+ Builder::new()
+ .metadata(AtomicUsize::new(0))
+ .spawn_unchecked(my_future, schedule.clone())
+ };
+
+ runnable.schedule();
+ task
+ };
+
+ // Make tasks.
+ let t1 = make_task();
+ let t2 = make_task();
+
+ // Run the tasks.
+ while let Ok(runnable) = receiver.try_recv() {
+ runnable.run();
+ }
+
+ // Unwrap the tasks.
+ smol::future::block_on(async move {
+ t1.await;
+ t2.await;
+ });
+}
diff --git a/external/vendor/async-task/tests/panic.rs b/external/vendor/async-task/tests/panic.rs
new file mode 100644
index 0000000..726e385
--- /dev/null
+++ b/external/vendor/async-task/tests/panic.rs
@@ -0,0 +1,234 @@
+use std::future::Future;
+use std::panic::catch_unwind;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use easy_parallel::Parallel;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, POLL, DROP)`
+//
+// The future `f` sleeps for 200 ms and then panics.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! future {
+ ($name:pat, $poll:ident, $drop:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = ();
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(400));
+ panic!()
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ Fut(Box::new(0))
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, SCHED, DROP)`
+//
+// The schedule function `s` does nothing.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! schedule {
+ ($name:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ move |_runnable: Runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ }
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn cancel_during_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ })
+ .run();
+}
+
+#[test]
+fn run_and_join() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(|| future::block_on(task)).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn try_join_and_run_and_join() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ future::block_on(future::or(&mut task, future::ready(())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 0);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(|| future::block_on(task)).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn join_during_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ assert!(catch_unwind(|| future::block_on(task)).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn try_join_during_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ future::block_on(future::or(&mut task, future::ready(())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ drop(task);
+ })
+ .run();
+}
+
+#[test]
+fn detach_during_run() {
+ future!(f, POLL, DROP_F);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ })
+ .run();
+}
diff --git a/external/vendor/async-task/tests/ready.rs b/external/vendor/async-task/tests/ready.rs
new file mode 100644
index 0000000..aefb36e
--- /dev/null
+++ b/external/vendor/async-task/tests/ready.rs
@@ -0,0 +1,225 @@
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use easy_parallel::Parallel;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, POLL, DROP_F, DROP_T)`
+//
+// The future `f` sleeps for 200 ms and outputs `Poll::Ready`.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP_F` is incremented.
+// When the output gets dropped, `DROP_T` is incremented.
+macro_rules! future {
+ ($name:pat, $poll:ident, $drop_f:ident, $drop_t:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop_f: AtomicUsize = AtomicUsize::new(0);
+ static $drop_t: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = Out;
+
+ fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(400));
+ Poll::Ready(Out(Box::new(0), true))
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop_f.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ #[derive(Default)]
+ struct Out(#[allow(dead_code)] Box<i32>, bool);
+
+ impl Drop for Out {
+ fn drop(&mut self) {
+ if self.1 {
+ $drop_t.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ }
+
+ Fut(Box::new(0))
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, SCHED, DROP)`
+//
+// The schedule function `s` does nothing.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+macro_rules! schedule {
+ ($name:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let $name = {
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ move |_runnable: Runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ }
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn cancel_during_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn join_during_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ future::block_on(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+
+ thread::sleep(ms(200));
+
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ })
+ .run();
+}
+
+#[test]
+fn try_join_during_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, mut task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ future::block_on(future::or(&mut task, future::ready(Default::default())));
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ drop(task);
+ })
+ .run();
+}
+
+#[test]
+fn detach_during_run() {
+ future!(f, POLL, DROP_F, DROP_T);
+ schedule!(s, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_T.load(Ordering::SeqCst), 0);
+ })
+ .run();
+}
diff --git a/external/vendor/async-task/tests/waker_panic.rs b/external/vendor/async-task/tests/waker_panic.rs
new file mode 100644
index 0000000..5b54f9d
--- /dev/null
+++ b/external/vendor/async-task/tests/waker_panic.rs
@@ -0,0 +1,330 @@
+use std::cell::Cell;
+use std::future::Future;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use atomic_waker::AtomicWaker;
+use easy_parallel::Parallel;
+use smol::future;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, get_waker, POLL, DROP)`
+//
+// The future `f` always sleeps for 200 ms, and panics the second time it is polled.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Every time the future is run, it stores the waker into a global variable.
+// This waker can be extracted using the `get_waker()` function.
+macro_rules! future {
+ ($name:pat, $get_waker:pat, $poll:ident, $drop:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static WAKER: AtomicWaker = AtomicWaker::new();
+
+ let ($name, $get_waker) = {
+ struct Fut(Cell<bool>, #[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = ();
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ WAKER.register(cx.waker());
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(400));
+
+ if self.0.get() {
+ panic!()
+ } else {
+ self.0.set(true);
+ Poll::Pending
+ }
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ (Fut(Cell::new(false), Box::new(0)), || WAKER.take().unwrap())
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, chan, SCHED, DROP)`
+//
+// The schedule function `s` pushes the task into `chan`.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Receiver `chan` extracts the task when it is scheduled.
+macro_rules! schedule {
+ ($name:pat, $chan:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let ($name, $chan) = {
+ let (s, r) = flume::unbounded();
+
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ let sched = move |runnable: Runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ s.send(runnable).unwrap();
+ };
+
+ (sched, r)
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+fn try_await<T>(f: impl Future<Output = T>) -> Option<T> {
+ future::block_on(future::poll_once(f))
+}
+
+#[test]
+fn wake_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ waker.wake();
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn cancel_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn wake_and_cancel_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ waker.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[flaky_test::flaky_test]
+fn cancel_and_wake_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ POLL.store(0, Ordering::SeqCst);
+ DROP_F.store(0, Ordering::SeqCst);
+ SCHEDULE.store(0, Ordering::SeqCst);
+ DROP_S.store(0, Ordering::SeqCst);
+
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ waker.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn panic_and_poll() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ get_waker().wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ let mut task = task;
+ assert!(try_await(&mut task).is_none());
+
+ let runnable = chan.recv().unwrap();
+ assert!(catch_unwind(|| runnable.run()).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ assert!(catch_unwind(AssertUnwindSafe(|| try_await(&mut task))).is_err());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+
+ drop(get_waker());
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
diff --git a/external/vendor/async-task/tests/waker_pending.rs b/external/vendor/async-task/tests/waker_pending.rs
new file mode 100644
index 0000000..ccd540b
--- /dev/null
+++ b/external/vendor/async-task/tests/waker_pending.rs
@@ -0,0 +1,365 @@
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use atomic_waker::AtomicWaker;
+use easy_parallel::Parallel;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, get_waker, POLL, DROP)`
+//
+// The future `f` always sleeps for 200 ms and returns `Poll::Pending`.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Every time the future is run, it stores the waker into a global variable.
+// This waker can be extracted using the `get_waker()` function.
+macro_rules! future {
+ ($name:pat, $get_waker:pat, $poll:ident, $drop:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static WAKER: AtomicWaker = AtomicWaker::new();
+
+ let ($name, $get_waker) = {
+ struct Fut(#[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = ();
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ WAKER.register(cx.waker());
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(400));
+ Poll::Pending
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ (Fut(Box::new(0)), || WAKER.take().unwrap())
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, chan, SCHED, DROP)`
+//
+// The schedule function `s` pushes the task into `chan`.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Receiver `chan` extracts the task when it is scheduled.
+macro_rules! schedule {
+ ($name:pat, $chan:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let ($name, $chan) = {
+ let (s, r) = flume::unbounded();
+
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ let sched = move |runnable: Runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ s.send(runnable).unwrap();
+ };
+
+ (sched, r)
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn wake_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, _task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 2);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 1);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ waker.wake_by_ref();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 2);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 1);
+ })
+ .run();
+
+ chan.recv().unwrap();
+ drop(get_waker());
+}
+
+#[test]
+fn cancel_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn wake_and_cancel_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ waker.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn cancel_and_wake_during_run() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+ waker.wake_by_ref();
+ let runnable = chan.recv().unwrap();
+
+ Parallel::new()
+ .add(|| {
+ runnable.run();
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .add(|| {
+ thread::sleep(ms(200));
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ waker.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ thread::sleep(ms(400));
+
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+ })
+ .run();
+}
+
+#[test]
+fn drop_last_waker() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ let waker = get_waker();
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ drop(waker);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 1);
+
+ chan.recv().unwrap().run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
+
+#[test]
+fn cancel_last_task() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ drop(task);
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 1);
+
+ chan.recv().unwrap().run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
+
+#[test]
+fn drop_last_task() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+
+ runnable.run();
+ drop(get_waker());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ task.detach();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 1);
+
+ chan.recv().unwrap().run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
diff --git a/external/vendor/async-task/tests/waker_ready.rs b/external/vendor/async-task/tests/waker_ready.rs
new file mode 100644
index 0000000..b6f6b5f
--- /dev/null
+++ b/external/vendor/async-task/tests/waker_ready.rs
@@ -0,0 +1,279 @@
+use std::cell::Cell;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::task::{Context, Poll};
+use std::thread;
+use std::time::Duration;
+
+use async_task::Runnable;
+use atomic_waker::AtomicWaker;
+
+// Creates a future with event counters.
+//
+// Usage: `future!(f, get_waker, POLL, DROP)`
+//
+// The future `f` always sleeps for 200 ms, and returns `Poll::Ready` the second time it is polled.
+// When it gets polled, `POLL` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Every time the future is run, it stores the waker into a global variable.
+// This waker can be extracted using the `get_waker()` function.
+macro_rules! future {
+ ($name:pat, $get_waker:pat, $poll:ident, $drop:ident) => {
+ static $poll: AtomicUsize = AtomicUsize::new(0);
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static WAKER: AtomicWaker = AtomicWaker::new();
+
+ let ($name, $get_waker) = {
+ struct Fut(Cell<bool>, #[allow(dead_code)] Box<i32>);
+
+ impl Future for Fut {
+ type Output = Box<i32>;
+
+ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
+ WAKER.register(cx.waker());
+ $poll.fetch_add(1, Ordering::SeqCst);
+ thread::sleep(ms(200));
+
+ if self.0.get() {
+ Poll::Ready(Box::new(0))
+ } else {
+ self.0.set(true);
+ Poll::Pending
+ }
+ }
+ }
+
+ impl Drop for Fut {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ (Fut(Cell::new(false), Box::new(0)), || WAKER.take().unwrap())
+ };
+ };
+}
+
+// Creates a schedule function with event counters.
+//
+// Usage: `schedule!(s, chan, SCHED, DROP)`
+//
+// The schedule function `s` pushes the task into `chan`.
+// When it gets invoked, `SCHED` is incremented.
+// When it gets dropped, `DROP` is incremented.
+//
+// Receiver `chan` extracts the task when it is scheduled.
+macro_rules! schedule {
+ ($name:pat, $chan:pat, $sched:ident, $drop:ident) => {
+ static $drop: AtomicUsize = AtomicUsize::new(0);
+ static $sched: AtomicUsize = AtomicUsize::new(0);
+
+ let ($name, $chan) = {
+ let (s, r) = flume::unbounded();
+
+ struct Guard(#[allow(dead_code)] Box<i32>);
+
+ impl Drop for Guard {
+ fn drop(&mut self) {
+ $drop.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ let guard = Guard(Box::new(0));
+ let sched = move |runnable: Runnable| {
+ let _ = &guard;
+ $sched.fetch_add(1, Ordering::SeqCst);
+ s.send(runnable).unwrap();
+ };
+
+ (sched, r)
+ };
+ };
+}
+
+fn ms(ms: u64) -> Duration {
+ Duration::from_millis(ms)
+}
+
+#[test]
+fn wake() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (mut runnable, task) = async_task::spawn(f, s);
+ task.detach();
+
+ assert!(chan.is_empty());
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ get_waker().wake();
+ runnable = chan.recv().unwrap();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ get_waker().wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
+
+#[test]
+fn wake_by_ref() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (mut runnable, task) = async_task::spawn(f, s);
+ task.detach();
+
+ assert!(chan.is_empty());
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ get_waker().wake_by_ref();
+ runnable = chan.recv().unwrap();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ get_waker().wake_by_ref();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
+
+#[allow(clippy::redundant_clone)] // This is intentional
+#[test]
+fn clone() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (mut runnable, task) = async_task::spawn(f, s);
+ task.detach();
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ let w2 = get_waker().clone();
+ let w3 = w2.clone();
+ let w4 = w3.clone();
+ w4.wake();
+
+ runnable = chan.recv().unwrap();
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ w3.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ drop(w2);
+ drop(get_waker());
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn wake_dropped() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+ task.detach();
+
+ runnable.run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ let waker = get_waker();
+
+ waker.wake_by_ref();
+ drop(chan.recv().unwrap());
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ waker.wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
+
+#[test]
+fn wake_completed() {
+ future!(f, get_waker, POLL, DROP_F);
+ schedule!(s, chan, SCHEDULE, DROP_S);
+ let (runnable, task) = async_task::spawn(f, s);
+ task.detach();
+
+ runnable.run();
+ let waker = get_waker();
+ assert_eq!(POLL.load(Ordering::SeqCst), 1);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 0);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ waker.wake();
+ chan.recv().unwrap().run();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 0);
+ assert_eq!(chan.len(), 0);
+
+ get_waker().wake();
+ assert_eq!(POLL.load(Ordering::SeqCst), 2);
+ assert_eq!(SCHEDULE.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_F.load(Ordering::SeqCst), 1);
+ assert_eq!(DROP_S.load(Ordering::SeqCst), 1);
+ assert_eq!(chan.len(), 0);
+}
diff --git a/external/vendor/concurrent-queue/.cargo-checksum.json b/external/vendor/concurrent-queue/.cargo-checksum.json
new file mode 100644
index 0000000..ec22307
--- /dev/null
+++ b/external/vendor/concurrent-queue/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"a70c1490e6daa375beb4928e5f4f97a6d9d6ba215fb4ff8b03ebc02a58a16439","CHANGELOG.md":"e9a4a11edce8b62146fdade24e1a74ee624601b2efcaa7035359c464a1ff7ff7","Cargo.toml":"d14f713829a83746178dd8a52732e1d106c895b3b4370bb9436fb190a2d763b2","Cargo.toml.orig":"18cfe5d32e53cdd29e2566612323ba36657b9cf2de41f7fae2a13e3880b9f458","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"d7a326783ef72b063a5a237b8c64e209e80fe61b9dda20e4686b5d8b19b16fb1","benches/bench.rs":"6bac7fcdfbd1b1caa2b36089a347fb120091b95ca7bd399249a96f1271e1bf08","src/bounded.rs":"f161cc0e03f59cc764a44dc0782f7fcef7325fc328dfc8cb8c7fd608fc259cc8","src/lib.rs":"dc69f8a48cc28fe73ea1be88d77cd1aba98947d5a673019e61c630cc04c537ad","src/single.rs":"610671ffb6f3b3bc9d375b99f4e004c61eece74caa29c2a3af6977d4764185f4","src/sync.rs":"7dc9bba96eda875ee3a1e5b808e4e2317cdd03293a38492a214e26e538159eef","src/unbounded.rs":"e90ea841f3f1eac5503b1c3cd2949de64956fc6a164ca65150c6c2bba02d0e16","tests/bounded.rs":"07a357eae995a79c5b6ac586037a86ed49df754ef3893d16891dc3c686299c6b","tests/loom.rs":"63e40d2598f80c97cada351c8db9c8d5e79d97bae870bdf9fe510d2b21510616","tests/single.rs":"7866f94d1c350e9a860aab550165806a8422649845ac6e9c95045886ce3e7659","tests/unbounded.rs":"3f49e41c33c14ab7ac255ef48c0af4f0f1cfcc9352fc73f21918df3039ff10d9"},"package":"4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"}
\ No newline at end of file
diff --git a/external/vendor/concurrent-queue/.cargo_vcs_info.json b/external/vendor/concurrent-queue/.cargo_vcs_info.json
new file mode 100644
index 0000000..33d501d
--- /dev/null
+++ b/external/vendor/concurrent-queue/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "e874f701f8413de01948c4903f894e5c845d8950"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
diff --git a/external/vendor/concurrent-queue/CHANGELOG.md b/external/vendor/concurrent-queue/CHANGELOG.md
new file mode 100644
index 0000000..f4f8bfd
--- /dev/null
+++ b/external/vendor/concurrent-queue/CHANGELOG.md
@@ -0,0 +1,69 @@
+# Version 2.5.0
+
+- Add a `force_push` method that can be used to add an element to the queue by displacing another. (#58)
+- Make `ConcurrentQueue::unbounded()` into a `const` function. (#67)
+- Fix a compilation error in the Loom implementation. (#65)
+
+# Version 2.4.0
+
+- Remove unnecessary heap allocations from inside of the `ConcurrentQueue` type. (#53)
+
+# Version 2.3.0
+
+- Implement `UnwindSafe` without libstd. (#49)
+- Bump `fastrand` to `v2.0.0`. (#43)
+- Use inline assembly in the `full_fence` funtion. (#47)
+
+# Version 2.2.0
+
+- Add the try_iter method. (#36)
+
+# Version 2.1.0
+
+- Update `portable-atomic` to 1.0. (#33)
+
+# Version 2.0.0
+
+- Add support for the `portable-atomic` and `loom` crates. (#27)
+- **Breaking:** Add an `std` feature that can be disabled to use this crate on `no_std` platforms. (#22)
+- Replace usage of `cache-padded` with `crossbeam-utils`. (#26)
+
+# Version 1.2.4
+
+- Fix fence on x86 and miri. (#18)
+- Revert 1.2.3. (#18)
+
+# Version 1.2.3
+
+**Note:** This release has been yanked, see #17 for details.
+
+- Fix fence on non-x86 architectures and miri. (#16)
+
+# Version 1.2.2
+
+- Add a special, efficient `bounded(1)` implementation.
+
+# Version 1.2.1
+
+- In the bounded queue, use boxed slice instead of raw pointers.
+
+# Version 1.2.0
+
+- Update dependencies.
+- Implement `UnwindSafe` and `RefUnwindSafe` for `ConcurrentQueue`.
+
+# Version 1.1.2
+
+- Optimize `SeqCst` fences.
+
+# Version 1.1.1
+
+- Clarify errors in docs.
+
+# Version 1.1.0
+
+- Add extra methods to error types.
+
+# Version 1.0.0
+
+- Initial version
diff --git a/external/vendor/concurrent-queue/Cargo.toml b/external/vendor/concurrent-queue/Cargo.toml
new file mode 100644
index 0000000..cdce2b4
--- /dev/null
+++ b/external/vendor/concurrent-queue/Cargo.toml
@@ -0,0 +1,72 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.60"
+name = "concurrent-queue"
+version = "2.5.0"
+authors = [
+ "Stjepan Glavina <stjepang@gmail.com>",
+ "Taiki Endo <te316e89@gmail.com>",
+ "John Nunley <dev@notgull.net>",
+]
+exclude = ["/.*"]
+description = "Concurrent multi-producer multi-consumer queue"
+readme = "README.md"
+keywords = [
+ "channel",
+ "mpmc",
+ "spsc",
+ "spmc",
+ "mpsc",
+]
+categories = ["concurrency"]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/concurrent-queue"
+
+[lib]
+bench = false
+
+[[bench]]
+name = "bench"
+harness = false
+
+[dependencies.crossbeam-utils]
+version = "0.8.11"
+default-features = false
+
+[dependencies.portable-atomic]
+version = "1"
+optional = true
+default-features = false
+
+[dev-dependencies.criterion]
+version = "0.5"
+features = ["cargo_bench_support"]
+default-features = false
+
+[dev-dependencies.easy-parallel]
+version = "3.1.0"
+
+[dev-dependencies.fastrand]
+version = "2.0.0"
+
+[features]
+default = ["std"]
+std = []
+
+[target."cfg(loom)".dependencies.loom]
+version = "0.7"
+optional = true
+
+[target."cfg(target_family = \"wasm\")".dev-dependencies.wasm-bindgen-test]
+version = "0.3"
diff --git a/external/vendor/concurrent-queue/Cargo.toml.orig b/external/vendor/concurrent-queue/Cargo.toml.orig
new file mode 100644
index 0000000..462958c
--- /dev/null
+++ b/external/vendor/concurrent-queue/Cargo.toml.orig
@@ -0,0 +1,47 @@
+[package]
+name = "concurrent-queue"
+# When publishing a new version:
+# - Update CHANGELOG.md
+# - Create "v2.x.y" git tag
+version = "2.5.0"
+authors = [
+ "Stjepan Glavina <stjepang@gmail.com>",
+ "Taiki Endo <te316e89@gmail.com>",
+ "John Nunley <dev@notgull.net>"
+]
+edition = "2021"
+rust-version = "1.60"
+description = "Concurrent multi-producer multi-consumer queue"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/smol-rs/concurrent-queue"
+keywords = ["channel", "mpmc", "spsc", "spmc", "mpsc"]
+categories = ["concurrency"]
+exclude = ["/.*"]
+
+[lib]
+bench = false
+
+[dependencies]
+crossbeam-utils = { version = "0.8.11", default-features = false }
+portable-atomic = { version = "1", default-features = false, optional = true }
+
+# Enables loom testing. This feature is permanently unstable and the API may
+# change at any time.
+[target.'cfg(loom)'.dependencies]
+loom = { version = "0.7", optional = true }
+
+[[bench]]
+name = "bench"
+harness = false
+
+[dev-dependencies]
+criterion = { version = "0.5", features = ["cargo_bench_support"], default-features = false }
+easy-parallel = "3.1.0"
+fastrand = "2.0.0"
+
+[target.'cfg(target_family = "wasm")'.dev-dependencies]
+wasm-bindgen-test = "0.3"
+
+[features]
+default = ["std"]
+std = []
diff --git a/external/vendor/concurrent-queue/LICENSE-APACHE b/external/vendor/concurrent-queue/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/external/vendor/concurrent-queue/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ hasWhy this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.