async-recursion-1.0.0/.cargo_vcs_info.json0000644000000001360000000000100141560ustar { "git": { "sha1": "bca2d7eb90d97cebc2c3981c9b42c9bc663dadfd" }, "path_in_vcs": "" }async-recursion-1.0.0/.github/dependabot.yml000064400000000000000000000002310072674642500171620ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "19:00" open-pull-requests-limit: 10 async-recursion-1.0.0/.github/workflows/rust.yml000064400000000000000000000006510072674642500201150ustar 00000000000000name: Push action on: [push] jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest] rust: [stable] steps: - uses: hecrj/setup-rust-action@v1 with: rust-version: ${{ matrix.rust }} - uses: actions/checkout@master - name: Tests run: cargo fmt -- --check && cargo clippy -- -Dwarnings && cargo test --verbose async-recursion-1.0.0/.gitignore000064400000000000000000000000730072674642500147660ustar 00000000000000/target **/*.rs.bk Cargo.lock .idea async-recursion.imlasync-recursion-1.0.0/Cargo.toml0000644000000017770000000000100121700ustar # 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 = "2018" name = "async-recursion" version = "1.0.0" authors = ["Robert Usher <266585+dcchut@users.noreply.github.com>"] description = "Recursion for async functions" documentation = "https://docs.rs/async-recursion" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/dcchut/async-recursion" [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0" features = ["full"] [dev-dependencies.futures-executor] version = "0.3" async-recursion-1.0.0/Cargo.toml.orig000064400000000000000000000010200072674642500156560ustar 00000000000000[package] name = "async-recursion" version = "1.0.0" authors = ["Robert Usher <266585+dcchut@users.noreply.github.com>"] edition = "2018" license = "MIT OR Apache-2.0" description = "Recursion for async functions" repository = "https://github.com/dcchut/async-recursion" documentation = "https://docs.rs/async-recursion" readme = "README.md" [lib] proc-macro = true [dependencies] proc-macro2 = "1.0" quote = "1.0" syn = { version = "1.0", features = ["full"] } [dev-dependencies] futures-executor = "0.3"async-recursion-1.0.0/LICENSE-APACHE000064400000000000000000000254460072674642500147350ustar 00000000000000 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.async-recursion-1.0.0/LICENSE-MIT000064400000000000000000000020240072674642500144300ustar 00000000000000Permission 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.async-recursion-1.0.0/README.md000064400000000000000000000045030072674642500142570ustar 00000000000000# async-recursion macro ![Build Status](https://github.com/dcchut/async-recursion/workflows/Push%20action/badge.svg?branch=master) Procedural macro for recursive async functions. * [Documentation](https://docs.rs/async-recursion/) * Cargo package: [async-recursion](https://crates.io/crates/async-recursion) ## Motivation Consider the following recursive implementation of the fibonacci numbers: ```rust,ignore async fn fib(n : u32) -> u64 { match n { 0 => panic!("zero is not a valid argument to fib()!"), 1 | 2 => 1, 3 => 2, _ => fib(n-1).await + fib(n-2).await } } ``` The compiler helpfully tells us that: ```console error[E0733]: recursion in an `async fn` requires boxing --> src/main.rs:1:26 | 1 | async fn fib(n : u32) -> u64 { | ^^^ recursive `async fn` | = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`. = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion ``` This crate provides an attribute macro to automatically convert an async function to one returning a boxed `Future`. ## Example ```rust use async_recursion::async_recursion; #[async_recursion] async fn fib(n : u32) -> u64 { match n { 0 => panic!("zero is not a valid argument to fib()!"), 1 | 2 => 1, 3 => 2, _ => fib(n-1).await + fib(n-2).await } } ``` ## ?Send Option The returned future has a `Send` bound to make sure it can be sent between threads. If this is undesirable you can mark that the bound should be left out like so: ```rust #[async_recursion(?Send)] async fn example() { // ... } ``` In detail: - `#[async_recursion]` modifies your function to return a [`BoxFuture`], and - `#[async_recursion(?Send)]` modifies your function to return a [`LocalBoxFuture`]. [`BoxFuture`]: https://docs.rs/futures/0.3.19/futures/future/type.BoxFuture.html [`LocalBoxFuture`]: https://docs.rs/futures/0.3.19/futures/future/type.LocalBoxFuture.html ### License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. async-recursion-1.0.0/src/expand.rs000064400000000000000000000140020072674642500154070ustar 00000000000000use crate::parse::{AsyncItem, RecursionArgs}; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::punctuated::Punctuated; use syn::{parse_quote, Block, FnArg, Lifetime, ReturnType, Signature, Type, WhereClause}; impl ToTokens for AsyncItem { fn to_tokens(&self, tokens: &mut TokenStream) { self.0.to_tokens(tokens); } } pub fn expand(item: &mut AsyncItem, args: &RecursionArgs) { transform_sig(&mut item.0.sig, args); transform_block(&mut item.0.block); } fn transform_block(block: &mut Block) { let brace = block.brace_token; *block = parse_quote!({ Box::pin(async move #block) }); block.brace_token = brace; } enum ArgLifetime { New(Lifetime), Existing(Lifetime), } impl ArgLifetime { pub fn lifetime(self) -> Lifetime { match self { ArgLifetime::New(lt) | ArgLifetime::Existing(lt) => lt, } } } // Input: // async fn f(x : S, y : &T) -> Ret; // // Output: // fn f(x : S, y : &T) -> Pin + Send> fn transform_sig(sig: &mut Signature, args: &RecursionArgs) { // Determine the original return type let ret = match &sig.output { ReturnType::Default => quote!(()), ReturnType::Type(_, ret) => quote!(#ret), }; // Remove the asyncness of this function sig.asyncness = None; // Find all reference arguments let mut ref_arguments = Vec::new(); let mut self_lifetime = None; for arg in &mut sig.inputs { if let FnArg::Typed(pt) = arg { if let Type::Reference(tr) = pt.ty.as_mut() { ref_arguments.push(tr); } } else if let FnArg::Receiver(recv) = arg { if let Some((_, slt)) = &mut recv.reference { self_lifetime = Some(slt); } } } let mut counter = 0; let mut lifetimes = Vec::new(); if !ref_arguments.is_empty() { for ra in &mut ref_arguments { // If this reference arg doesn't have a lifetime, give it an explicit one if ra.lifetime.is_none() { let lt = Lifetime::new(&format!("'life{}", counter), Span::call_site()); lifetimes.push(ArgLifetime::New(parse_quote!(#lt))); ra.lifetime = Some(lt); counter += 1; } else { let lt = ra.lifetime.as_ref().cloned().unwrap(); // Check that this lifetime isn't already in our vector let ident_matches = |x: &ArgLifetime| { if let ArgLifetime::Existing(elt) = x { elt.ident == lt.ident } else { false } }; if !lifetimes.iter().any(ident_matches) { lifetimes.push(ArgLifetime::Existing( ra.lifetime.as_ref().cloned().unwrap(), )); } } } } // Does this expansion require `async_recursion to be added to the output let mut requires_lifetime = false; let mut where_clause_lifetimes = vec![]; let mut where_clause_generics = vec![]; // 'async_recursion lifetime let asr: Lifetime = parse_quote!('async_recursion); // Add an S : 'async_recursion bound to any generic parameter for param in sig.generics.type_params() { let ident = param.ident.clone(); where_clause_generics.push(ident); requires_lifetime = true; } // Add an 'a : 'async_recursion bound to any lifetimes 'a appearing in the function if !lifetimes.is_empty() { for alt in lifetimes { if let ArgLifetime::New(lt) = &alt { // If this is a new argument, sig.generics.params.push(parse_quote!(#lt)); } // Add a bound to the where clause let lt = alt.lifetime(); where_clause_lifetimes.push(lt); } requires_lifetime = true; } // If our function accepts &self, then we modify this to the explicit lifetime &'life_self, // and add the bound &'life_self : 'async_recursion if let Some(slt) = self_lifetime { let lt = { if let Some(lt) = slt.as_mut() { lt.clone() } else { // We use `life_self here to avoid any collisions with `life0, `life1 from above let lt: Lifetime = parse_quote!('life_self); sig.generics.params.push(parse_quote!(#lt)); // add lt to the lifetime of self *slt = Some(lt.clone()); lt } }; where_clause_lifetimes.push(lt); requires_lifetime = true; } let box_lifetime: TokenStream = if requires_lifetime { // Add 'async_recursion to our generic parameters sig.generics.params.push(parse_quote!('async_recursion)); quote!(+ #asr) } else { quote!() }; let send_bound: TokenStream = if args.send_bound { quote!(+ ::core::marker::Send) } else { quote!() }; let where_clause = sig .generics .where_clause .get_or_insert_with(|| WhereClause { where_token: Default::default(), predicates: Punctuated::new(), }); // Add our S : 'async_recursion bounds for generic_ident in where_clause_generics { where_clause .predicates .push(parse_quote!(#generic_ident : #asr)); } // Add our 'a : 'async_recursion bounds for lifetime in where_clause_lifetimes { where_clause.predicates.push(parse_quote!(#lifetime : #asr)); } // Modify the return type sig.output = parse_quote! { -> ::core::pin::Pin #box_lifetime #send_bound >> }; } async-recursion-1.0.0/src/lib.rs000064400000000000000000000061060072674642500147040ustar 00000000000000//! # async-recursion macro //! //! ![Build Status](https://github.com/dcchut/async-recursion/workflows/Push%20action/badge.svg?branch=master) //! //! Procedural macro for recursive async functions. //! //! * [Documentation](https://docs.rs/async-recursion/) //! * Cargo package: [async-recursion](https://crates.io/crates/async-recursion) //! //! ## Motivation //! Consider the following recursive implementation of the fibonacci numbers: //! //! ```rust,ignore //! async fn fib(n : u32) -> u64 { //! match n { //! 0 => panic!("zero is not a valid argument to fib()!"), //! 1 | 2 => 1, //! 3 => 2, //! _ => fib(n-1).await + fib(n-2).await //! } //! } //! ``` //! //! The compiler helpfully tells us that: //! //! ```console //! error[E0733]: recursion in an `async fn` requires boxing //! --> src/main.rs:1:26 //! | //! 1 | async fn fib(n : u32) -> u64 { //! | ^^^ recursive `async fn` //! | //! = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`. //! = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion //! ``` //! //! This crate provides an attribute macro to automatically convert an async function //! to one returning a boxed [`Future`](core::future::Future). //! //! ## Example //! //! ```rust //! use async_recursion::async_recursion; //! //! #[async_recursion] //! async fn fib(n : u32) -> u64 { //! match n { //! 0 => panic!("zero is not a valid argument to fib()!"), //! 1 | 2 => 1, //! 3 => 2, //! _ => fib(n-1).await + fib(n-2).await //! } //! } //! ``` //! //! ## ?Send Option //! //! The returned future has a [`Send`] bound to make sure it can be sent between threads. //! If this is undesirable you can mark that the bound should be left out like so: //! //! ```rust //! # use async_recursion::async_recursion; //! //! #[async_recursion(?Send)] //! async fn example() { //! // ... //! } //! ``` //! //! In detail: //! //! - `#[async_recursion]` modifies your function to return a [`BoxFuture`], and //! - `#[async_recursion(?Send)]` modifies your function to return a [`LocalBoxFuture`]. //! //! [`BoxFuture`]: https://docs.rs/futures/0.3.19/futures/future/type.BoxFuture.html //! [`LocalBoxFuture`]: https://docs.rs/futures/0.3.19/futures/future/type.LocalBoxFuture.html //! //! ### License //! //! Licensed under either of //! * Apache License, Version 2.0 () //! * MIT license () //! //! at your option. extern crate proc_macro; mod expand; mod parse; use proc_macro::TokenStream; use quote::quote; use syn::parse_macro_input; #[proc_macro_attribute] pub fn async_recursion(args: TokenStream, input: TokenStream) -> TokenStream { let mut item = parse_macro_input!(input as parse::AsyncItem); let args = parse_macro_input!(args as parse::RecursionArgs); expand::expand(&mut item, &args); TokenStream::from(quote!(#item)) } async-recursion-1.0.0/src/parse.rs000064400000000000000000000023220072674642500152440ustar 00000000000000use proc_macro2::Span; use syn::parse::{Error, Parse, ParseStream, Result}; use syn::{token::Question, ItemFn, Token}; pub struct AsyncItem(pub ItemFn); impl Parse for AsyncItem { fn parse(input: ParseStream) -> Result { let item: ItemFn = input.parse()?; // Check that this is an async function if item.sig.asyncness.is_none() { return Err(Error::new(Span::call_site(), "expected an async function")); } Ok(AsyncItem(item)) } } pub struct RecursionArgs { pub send_bound: bool, } impl Default for RecursionArgs { fn default() -> Self { RecursionArgs { send_bound: true } } } /// Custom keywords for parser mod kw { syn::custom_keyword!(Send); } impl Parse for RecursionArgs { fn parse(input: ParseStream) -> Result { // Check for the `?Send` option if input.peek(Token![?]) { input.parse::()?; input.parse::()?; Ok(Self { send_bound: false }) } else if !input.is_empty() { Err(input.error("expected `?Send` or empty")) } else { Ok(Self::default()) } } } async-recursion-1.0.0/tests/core_module.rs000064400000000000000000000003370072674642500170060ustar 00000000000000use async_recursion::async_recursion; mod core { // already defined core module shouldn't fail with message like 'could not find `pin` in `core`' } #[async_recursion] pub async fn n(x: i32) -> i32 { x } async-recursion-1.0.0/tests/fibonacci.rs000064400000000000000000000012160072674642500164230ustar 00000000000000use async_recursion::async_recursion; use futures_executor::block_on; #[async_recursion] async fn fib(n: u32) -> u64 { match n { 0 => panic!("zero is not a valid argument to fib()!"), 1 | 2 => 1, 3 => 2, _ => fib(n - 1).await + fib(n - 2).await, } } #[test] fn fibonacci_example_works() { block_on(async move { assert_eq!(fib(3).await, 2); assert_eq!(fib(4).await, 3); assert_eq!(fib(5).await, 5); assert_eq!(fib(6).await, 8); }); } #[test] fn fibonacci_example_is_send() { fn assert_is_send(_: impl Send) {} assert_is_send(fib(6)); } async-recursion-1.0.0/tests/generic_parameters.rs000064400000000000000000000024270072674642500203520ustar 00000000000000use async_recursion::async_recursion; use futures_executor::block_on; pub trait ThirtySeven { fn thirty_seven(&self) -> u64 { 37 } fn descend(&mut self) -> bool; } struct Silly { counter: usize, } impl ThirtySeven for Silly { fn descend(&mut self) -> bool { if self.counter == 0 { false } else { self.counter -= 1; true } } } #[async_recursion] pub async fn generic_parameter(mut x: S) -> u64 { if x.descend() { generic_parameter(x).await } else { x.thirty_seven() } } #[async_recursion(?Send)] pub async fn generic_parameter_no_send(x: T, y: u64) -> u64 { if y > 0 { generic_parameter_no_send(x, y - 1).await } else { 111 } } #[test] fn generic_parameter_is_send() { fn assert_is_send(_: impl Send) {} assert_is_send(generic_parameter(Silly { counter: 10 })); } #[test] fn generic_parameter_bounds() { block_on(async move { let s = Silly { counter: 45 }; assert_eq!(generic_parameter(s).await, 37); assert_eq!( generic_parameter_no_send(Silly { counter: 999 }, 10).await, 111 ); }); } async-recursion-1.0.0/tests/lifetimes.rs000064400000000000000000000042700072674642500164720ustar 00000000000000use async_recursion::async_recursion; use futures_executor::block_on; struct Node<'a, T> { value: T, left: Option<&'a Node<'a, T>>, right: Option<&'a Node<'a, T>>, } impl Node<'_, T> { pub fn new(value: T) -> Self { Self { value, left: None, right: None, } } } // Note: Use the `?Send` notation here allows us not to require that our type parameter `T` is // `T: PartialEq + Sync + Send`. #[async_recursion(?Send)] async fn contains_value<'a, T: PartialEq>(value: &T, node: &Node<'a, T>) -> bool { if &node.value == value { true } else { (node.left.is_some() && contains_value(value, node.left.unwrap()).await) || (node.right.is_some() && contains_value(value, node.right.unwrap()).await) } } #[async_recursion(?Send)] async fn contains_value_2<'a, 'b, T: PartialEq>(value: &'b T, node: &'b Node<'a, T>) -> bool { contains_value(value, node).await } #[test] fn lifetime_expansion_works() { block_on(async move { let mut node = Node::new(10); let mut left = Node::new(5); let left_left = Node::new(3); let left_right = Node::new(7); let mut right = Node::new(15); let right_left = Node::new(13); let right_right = Node::new(17); left.left = Some(&left_left); left.right = Some(&left_right); right.left = Some(&right_left); right.right = Some(&right_right); node.left = Some(&left); node.right = Some(&right); assert_eq!(contains_value(&3, &node).await, true); assert_eq!(contains_value(&4, &node).await, false); assert_eq!(contains_value(&17, &node).await, true); assert_eq!(contains_value(&13, &node).await, true); assert_eq!(contains_value(&12, &node).await, false); assert_eq!(contains_value_2(&3, &node).await, true); assert_eq!(contains_value_2(&4, &node).await, false); assert_eq!(contains_value_2(&17, &node).await, true); assert_eq!(contains_value_2(&13, &node).await, true); assert_eq!(contains_value_2(&12, &node).await, false); }); } async-recursion-1.0.0/tests/struct_methods.rs000064400000000000000000000036320072674642500175610ustar 00000000000000use async_recursion::async_recursion; use futures_executor::block_on; pub struct Empty {} impl Empty { #[async_recursion] pub async fn fib(&self, n: u32) -> u64 { match n { 0 => panic!("zero is not a valid argument to fib()!"), 1 | 2 => 1, 3 => 2, _ => self.fib(n - 1).await + self.fib(n - 2).await, } } #[async_recursion] pub async fn empty_string<'a>(&self, some_str: &'a str) -> &'a str { if some_str.is_empty() { "" } else { self.empty_string(&some_str[1..]).await } } #[async_recursion] pub async fn generic_parameter(&self, _something: &T) -> u64 { 0 } #[async_recursion] pub async fn all_of_the_above<'a, 'b, S, T>( &self, // Some references with / without lifetimes to generic parameters _x: &S, _y: &'b T, // Some generic parameters passed by value _w: S, _z: T, // A reference to a concrete type without a lifetime _p: &usize, // A reference to a concrete type with a lifetime _q: &'a u64, ) { } } #[test] fn struct_method_fib_works() { block_on(async move { let e = Empty {}; assert_eq!(e.fib(6).await, 8); assert_eq!(e.fib(5).await, 5); assert_eq!(e.fib(7).await, 13); }); } #[test] fn struct_method_empty_string_works() { block_on(async move { let e = Empty {}; assert_eq!(e.empty_string("hello world").await, ""); assert_eq!(e.empty_string("something else").await, ""); }); } #[test] fn struct_method_with_generic_parameter_works() { block_on(async move { let e = Empty {}; assert_eq!( e.generic_parameter::<*const u64>(&(0 as *const u64)).await, 0 ); }) }