├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── lib.rs └── prelude.rs └── tests └── test.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "futures-micro" 3 | version = "1.0.0-rc0" 4 | description = "Minimal, no_std compatible async prelude." 5 | keywords = ["async", "futures", "no-std", "tests", "testing"] 6 | categories = ["asynchronous", "concurrency", "no-std"] 7 | authors = ["James Laver "] 8 | homepage = "https://github.com/irrustible/futures-micro" 9 | repository = "https://github.com/irrustible/futures-micro" 10 | documentation = "https://docs.rs/futures-micro" 11 | edition = "2018" 12 | license = "Apache-2.0 WITH LLVM-exception" 13 | readme = "README.md" 14 | 15 | [dependencies] 16 | pin-project-lite = "0.2.4" 17 | 18 | [dev-dependencies] 19 | futures-lite = "2.3.0" 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | 204 | ---- LLVM Exceptions to the Apache 2.0 License ---- 205 | 206 | As an exception, if, as a result of your compiling your source code, portions 207 | of this Software are embedded into an Object form of such source code, you 208 | may redistribute such embedded portions in such Object form without complying 209 | with the conditions of Sections 4(a), 4(b) and 4(d) of the License. 210 | 211 | In addition, if you combine or link compiled forms of this Software with 212 | software that is licensed under the GPLv2 ("Combined Software") and if a 213 | court of competent jurisdiction determines that the patent provision (Section 214 | 3), the indemnity provision (Section 9) or other Section of the License 215 | conflicts with the conditions of the GPLv2, you may retroactively and 216 | prospectively choose to deem waived or otherwise exclude such Section(s) of 217 | the License, but only in their entirety and only with respect to the Combined 218 | Software. 219 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # futures-micro 2 | 3 | [![License](https://img.shields.io/crates/l/futures-micro.svg)](https://github.com/irrustible/futures-micro/blob/main/LICENSE) 4 | [![Package](https://img.shields.io/crates/v/futures-micro.svg)](https://crates.io/crates/futures-micro) 5 | [![Documentation](https://docs.rs/futures-micro/badge.svg)](https://docs.rs/futures-micro) 6 | 7 | To futures-lite as futures-lite is to futures: smaller. 8 | 9 | Features: 10 | * Fun tools to write everything as async fns. 11 | * Tiny, with a single dependency. 12 | * 100% `no_std` support, no heap allocation required! 13 | * Complete stable compiler support - Uses no nightly features! 14 | 15 | * Bootstrap tools: 16 | * `poll_fn` - wrap a function into a future. 17 | * `pin!()` - pin a value to the stack. 18 | * Futures interface subversion (poll interface from async fns): 19 | * `waker()` to get the current waker. 20 | * `sleep()` to wait until you are woken. 21 | * Common stuff: 22 | * `yield_once()` - lets some other futures do some work . 23 | * `or()` - return the result of the first future to complete. 24 | * `or!()` - `or()`, but varargs. 25 | * `zip()` - return the result of both futures when they both complete. 26 | * `zip!()` - `zip()`, but varargs. 27 | * `ready!()` - unwraps a ready value or returns pending. 28 | 29 | ## Status 30 | 31 | Beta? The API we have here seems pretty reasonable now. 32 | 33 | If there's something you're missing, you may be looking for 34 | [futures-lite](https://github.com/smol-rs/futures-lite). 35 | 36 | ## Missing/Removed APIs 37 | 38 | There are many APIs you will *not* find in this crate. Some are absent to keep the crate small and quick to compile, others used to be here but have since been removed. These are: 39 | 40 | * `pending()` - never completes, now in libcore as `core::future::pending()` 41 | * `ready()` - completes on first poll, now in libcore as `core::future::ready()` 42 | * `poll_state` - wrap a function and some state into a future. 43 | ```rust 44 | /// outdated 45 | poll_state(INITIAL, |state, ctx| {...}).await 46 | 47 | /// replacement (NOTE: `*state` should be replaced by `state`) 48 | let mut state = INITIAL; 49 | poll_fn(move |ctx| { ... }).await 50 | ``` 51 | 52 | ## Changelog 53 | 54 | ### 0.5.0 - 2021-03-13 55 | 56 | * Switch to using `pin-project-lite` for pin projections, removing 57 | most of the unsafe code. 58 | * Removed `next_poll`. It wasn't very useful and our implementation 59 | may not have been sound. This may explain why I can't find it in `futures-lite`. 60 | 61 | ## Copyright and License 62 | 63 | Copyright (c) 2020 James Laver, Matthieu le Brazidec, Stjepan Glavina, Alain Zscheile, 64 | futures-micro contributors, futures-lite contributors 65 | 66 | [Licensed](LICENSE) under Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0), 67 | with LLVM Exceptions (https://spdx.org/licenses/LLVM-exception.html). 68 | 69 | Unless you explicitly state otherwise, any contribution intentionally submitted 70 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 71 | licensed as above, without any additional terms or conditions. 72 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A very small, no-std compatible toolbox of async utilities. 2 | #![no_std] 3 | #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] 4 | 5 | pub mod prelude; 6 | 7 | #[doc(no_inline)] 8 | pub use core::future::Future; 9 | #[doc(no_inline)] 10 | pub use core::pin::Pin; 11 | #[doc(no_inline)] 12 | pub use core::task::{Context, Poll, Waker}; 13 | 14 | use core::fmt; 15 | 16 | use pin_project_lite::pin_project; 17 | 18 | // ---------- futures using the poll api ----------- 19 | 20 | /// Creates a future from a function returning [`Poll`]. 21 | /// 22 | /// # Examples 23 | /// 24 | /// ``` 25 | /// use futures_lite::future::block_on; 26 | /// use futures_micro::poll_fn; 27 | /// use std::task::{Context, Poll}; 28 | /// 29 | /// # block_on(async { 30 | /// fn f(_ctx: &mut Context<'_>) -> Poll { 31 | /// Poll::Ready(7) 32 | /// } 33 | /// 34 | /// assert_eq!(poll_fn(f).await, 7); 35 | /// # }) 36 | /// ``` 37 | #[inline(always)] 38 | pub fn poll_fn(inner: F) -> PollFn 39 | where 40 | F: FnMut(&mut Context<'_>) -> Poll, 41 | { 42 | PollFn { inner } 43 | } 44 | 45 | pin_project! { 46 | /// Future for the [`poll_fn()`] function. 47 | #[must_use = "futures do nothing unless you `.await` or poll them"] 48 | pub struct PollFn { 49 | inner: F, 50 | } 51 | } 52 | 53 | impl fmt::Debug for PollFn { 54 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 55 | f.debug_struct("PollFn").finish() 56 | } 57 | } 58 | 59 | impl Future for PollFn 60 | where 61 | F: FnMut(&mut Context<'_>) -> Poll, 62 | { 63 | type Output = T; 64 | fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll { 65 | let this = self.project(); 66 | (this.inner)(ctx) 67 | } 68 | } 69 | 70 | pin_project! { 71 | /// Returns the result of `left` or `right` future, preferring `left` if both are ready. 72 | #[derive(Debug)] 73 | #[must_use = "futures do nothing unless you `.await` or poll them"] 74 | pub struct Or { 75 | #[pin] 76 | future1: F1, 77 | #[pin] 78 | future2: F2, 79 | } 80 | } 81 | 82 | impl Or 83 | where 84 | F1: Future, 85 | F2: Future, 86 | { 87 | /// Returns the result of `left` or `right` future, preferring `left` if both are ready. 88 | pub fn new(future1: F1, future2: F2) -> Self { 89 | Or { future1, future2 } 90 | } 91 | } 92 | 93 | impl Future for Or 94 | where 95 | F1: Future, 96 | F2: Future, 97 | { 98 | type Output = T; 99 | 100 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 101 | let this = self.project(); 102 | 103 | if let Poll::Ready(t) = this.future1.poll(cx) { 104 | Poll::Ready(t) 105 | } else if let Poll::Ready(t) = this.future2.poll(cx) { 106 | Poll::Ready(t) 107 | } else { 108 | Poll::Pending 109 | } 110 | } 111 | } 112 | 113 | pin_project! { 114 | /// Waits for two [`Future`]s to complete, returning both results. 115 | #[derive(Debug)] 116 | #[must_use = "futures do nothing unless you `.await` or poll them"] 117 | pub struct Zip 118 | where 119 | F1: Future, 120 | F2: Future, 121 | { 122 | #[pin] 123 | future1: F1, 124 | output1: Option, 125 | #[pin] 126 | future2: F2, 127 | output2: Option, 128 | } 129 | } 130 | 131 | impl Zip 132 | where 133 | F1: Future, 134 | F2: Future, 135 | { 136 | /// Zips two futures, waiting for both to complete. 137 | /// 138 | /// # Examples 139 | /// 140 | /// ``` 141 | /// use futures_micro::Zip; 142 | /// 143 | /// # futures_lite::future::block_on(async { 144 | /// let a = async { 1 }; 145 | /// let b = async { 2 }; 146 | /// 147 | /// assert_eq!(Zip::new(a, b).await, (1, 2)); 148 | /// # }) 149 | /// ``` 150 | pub fn new(future1: F1, future2: F2) -> Self { 151 | Zip { 152 | future1, 153 | future2, 154 | output1: None, 155 | output2: None, 156 | } 157 | } 158 | } 159 | 160 | impl Future for Zip 161 | where 162 | F1: Future, 163 | F2: Future, 164 | { 165 | type Output = (F1::Output, F2::Output); 166 | 167 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 168 | let this = self.project(); 169 | 170 | if this.output1.is_none() { 171 | if let Poll::Ready(out) = this.future1.poll(cx) { 172 | *this.output1 = Some(out); 173 | } 174 | } 175 | 176 | if this.output2.is_none() { 177 | if let Poll::Ready(out) = this.future2.poll(cx) { 178 | *this.output2 = Some(out); 179 | } 180 | } 181 | 182 | if this.output1.is_some() && this.output2.is_some() { 183 | Poll::Ready((this.output1.take().unwrap(), this.output2.take().unwrap())) 184 | } else { 185 | Poll::Pending 186 | } 187 | } 188 | } 189 | 190 | /// Get the [`Waker`] inside an async fn where you aren't supposed to 191 | /// have it. 192 | /// 193 | /// This is a low level primitive for implementing more complex 194 | /// patterns while avoiding the [`Poll`] API. 195 | /// 196 | /// # Examples 197 | /// 198 | /// ``` 199 | /// use futures_micro::{sleep, waker}; 200 | /// 201 | /// # futures_lite::future::block_on(async { 202 | /// let waker = waker().await; 203 | /// assert_eq!(async { waker.wake(); sleep().await; 1 }.await, 1) 204 | /// # }) 205 | /// ``` 206 | pub fn waker() -> impl Future { 207 | poll_fn(|ctx| Poll::Ready(ctx.waker().clone())) 208 | } 209 | 210 | /// Goes to sleep until woken by its [`Waker`] being called. 211 | /// 212 | /// This is a low level primitive for implementing more complex 213 | /// patterns while avoiding the [`Poll`] API. 214 | /// 215 | /// # Examples 216 | /// 217 | /// ``` 218 | /// use futures_micro::{sleep, waker}; 219 | /// 220 | /// # futures_lite::future::block_on(async { 221 | /// let waker = waker().await; 222 | /// assert_eq!(async { waker.wake(); sleep().await; 1 }.await, 1) 223 | /// # }) 224 | /// ``` 225 | pub fn sleep() -> impl Future { 226 | let mut done = false; 227 | poll_fn(move |_| { 228 | if done { 229 | Poll::Ready(()) 230 | } else { 231 | done = true; 232 | Poll::Pending 233 | } 234 | }) 235 | } 236 | 237 | /// Pushes itself to the back of the executor queue so some other 238 | /// tasks can do some work. 239 | pub fn yield_once() -> impl Future { 240 | let mut done = false; 241 | poll_fn(move |ctx| { 242 | if done { 243 | Poll::Ready(()) 244 | } else { 245 | done = true; 246 | ctx.waker().wake_by_ref(); 247 | Poll::Pending 248 | } 249 | }) 250 | } 251 | 252 | // --------- MACROS --------- 253 | 254 | // Helper for `or!` 255 | #[doc(hidden)] 256 | #[macro_export] 257 | macro_rules! __internal_fold_with { 258 | ($func:path, $e:expr) => { $e }; 259 | ($func:path, $e:expr, $($es:expr),+) => { 260 | $func($e, $crate::__internal_fold_with!($func, $($es),+)) 261 | }; 262 | } 263 | 264 | /// Polls arbitrarily many futures, returning the first ready value. 265 | /// 266 | /// All futures must have the same output type. Left biased when more 267 | /// than one Future is ready at the same time. 268 | #[macro_export] 269 | macro_rules! or { 270 | ($($es:expr),+$(,)?) => { $crate::__internal_fold_with!($crate::Or::new, $($es),+) }; 271 | } 272 | 273 | /// Pins a variable of type `T` on the stack and rebinds it as `Pin<&mut T>`. 274 | /// 275 | /// ``` 276 | /// use futures_micro::*; 277 | /// use std::fmt::Debug; 278 | /// use std::time::Instant; 279 | /// 280 | /// // Inspects each invocation of `Future::poll()`. 281 | /// async fn inspect(f: impl Future) -> T { 282 | /// pin!(f); 283 | /// poll_fn(|cx| dbg!(f.as_mut().poll(cx))).await 284 | /// } 285 | /// 286 | /// # futures_lite::future::block_on(async { 287 | /// let f = async { 1 + 2 }; 288 | /// inspect(f).await; 289 | /// # }) 290 | /// ``` 291 | #[macro_export] 292 | macro_rules! pin { 293 | ($($x:ident),* $(,)?) => { 294 | $( 295 | let mut $x = $x; 296 | #[allow(unused_mut)] 297 | let mut $x = unsafe { 298 | core::pin::Pin::new_unchecked(&mut $x) 299 | }; 300 | )* 301 | } 302 | } 303 | 304 | /// Unwraps `Poll` or returns [`Pending`][`Poll::Pending`]. 305 | /// 306 | /// # Examples 307 | /// 308 | /// ``` 309 | /// use futures_micro::*; 310 | /// 311 | /// // Polls two futures and sums their results. 312 | /// fn poll_sum( 313 | /// cx: &mut Context<'_>, 314 | /// mut a: impl Future + Unpin, 315 | /// mut b: impl Future + Unpin, 316 | /// ) -> Poll { 317 | /// let x = ready!(Pin::new(&mut a).poll(cx)); 318 | /// let y = ready!(Pin::new(&mut b).poll(cx)); 319 | /// Poll::Ready(x + y) 320 | /// } 321 | /// ``` 322 | #[macro_export] 323 | macro_rules! ready { 324 | ($e:expr $(,)?) => { 325 | match $e { 326 | core::task::Poll::Ready(t) => t, 327 | t @ core::task::Poll::Pending => return t, 328 | } 329 | }; 330 | } 331 | 332 | /// Zips arbitrarily many futures, waiting for all to complete. 333 | /// 334 | /// # Examples 335 | /// 336 | /// ``` 337 | /// use futures_micro::zip; 338 | /// 339 | /// # futures_lite::future::block_on(async { 340 | /// let a = async { 1 }; 341 | /// let b = async { 2 }; 342 | /// 343 | /// assert_eq!(zip!(a, b).await, (1, 2)); 344 | /// # }) 345 | /// ``` 346 | #[macro_export] 347 | macro_rules! zip { 348 | ($($es:expr),+ $(,)?) => {{ 349 | let mut zips = $crate::__internal_fold_with!($crate::Zip::new, $($es),+); 350 | $crate::poll_fn(move |ctx| { 351 | use ::core::pin::Pin; 352 | use ::core::task::Poll; 353 | 354 | let zips = unsafe { Pin::new_unchecked(&mut zips) }; 355 | if let Poll::Ready(val) = ::core::future::Future::poll(zips, ctx) { 356 | Poll::Ready($crate::zip!(@flatten; ; val; $($es),+)) 357 | } else { 358 | Poll::Pending 359 | } 360 | }) 361 | }}; 362 | 363 | (@flatten; $($prev:expr,)*; $tuple:expr; $e:expr) => { 364 | ($($prev,)* $tuple) 365 | }; 366 | 367 | (@flatten; $($prev:expr,)*; $tuple:expr; $e:expr, $($es:expr),+) => { 368 | $crate::zip!(@flatten; $($prev,)* $tuple.0,; $tuple.1; $($es),+) 369 | }; 370 | } 371 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | //! This module has extras that clash with names in [`futures-lite`], 2 | //! which depends on us. 3 | pub use crate::*; 4 | 5 | /// Zips two futures, waiting for both to complete. 6 | /// 7 | /// # Examples 8 | /// 9 | /// ``` 10 | /// use futures_micro::prelude::zip; 11 | /// 12 | /// # futures_lite::future::block_on(async { 13 | /// let a = async { 1 }; 14 | /// let b = async { 2 }; 15 | /// 16 | /// assert_eq!(zip(a, b).await, (1, 2)); 17 | /// # }) 18 | /// ``` 19 | pub fn zip(f1: F1, f2: F2) -> Zip 20 | where 21 | F1: Future, 22 | F2: Future, 23 | { 24 | Zip::new(f1, f2) 25 | } 26 | 27 | /// Returns the result of `left` or `right` future, preferring `left` if both are ready. 28 | pub fn or(future1: F1, future2: F2) -> Or 29 | where 30 | F1: Future, 31 | F2: Future, 32 | { 33 | Or { future1, future2 } 34 | } 35 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | #![allow(deprecated)] 3 | 4 | use futures_lite::future::block_on; 5 | use futures_micro::{poll_fn, prelude::*}; 6 | use std::task::Poll; 7 | 8 | fn ready(x: T) -> impl Future { 9 | let mut x = Some(x); 10 | poll_fn(move |_| Poll::Ready(x.take().unwrap())) 11 | } 12 | 13 | fn pending() -> impl Future { 14 | poll_fn(|_| Poll::Pending) 15 | } 16 | 17 | #[test] 18 | fn waker_sleep_test() { 19 | assert!(block_on(async { 20 | let waker = waker().await; 21 | waker.wake(); 22 | sleep().await; 23 | true 24 | })); 25 | } 26 | 27 | #[test] 28 | fn yield_once_test() { 29 | assert_eq!( 30 | true, 31 | block_on(async { 32 | yield_once().await; 33 | true 34 | }) 35 | ); 36 | assert_eq!( 37 | false, 38 | block_on(or!( 39 | async { 40 | yield_once().await; 41 | true 42 | }, 43 | ready(false) 44 | )) 45 | ); 46 | } 47 | 48 | #[test] 49 | fn or_test() { 50 | assert_eq!(false, block_on(or(pending::(), ready(false)))); 51 | assert_eq!(1, block_on(or!(ready(1), ready(2), ready(3)))); 52 | assert_eq!(2, block_on(or!(pending(), ready(2), ready(3)))); 53 | assert_eq!(3, block_on(or!(pending(), pending(), ready(3)))); 54 | } 55 | 56 | #[test] 57 | fn zip_test() { 58 | assert_eq!((true, false), block_on(zip(ready(true), ready(false)))); 59 | assert_eq!((1, 2, 3), block_on(zip!(ready(1), ready(2), ready(3)))); 60 | 61 | assert_eq!( 62 | (1, false, 3), 63 | block_on(zip!(ready(1), ready(false), ready(3))) 64 | ); 65 | } 66 | --------------------------------------------------------------------------------