#async #recursion #macro #recursive

macro async-recursion

Recursion for async functions

7 releases

0.3.2 Feb 2, 2021
0.3.1 Apr 10, 2020
0.2.0 Mar 27, 2020
0.1.2 Oct 4, 2019
Download history 2712/week @ 2020-10-27 2690/week @ 2020-11-03 2496/week @ 2020-11-10 2824/week @ 2020-11-17 3291/week @ 2020-11-24 3040/week @ 2020-12-01 2446/week @ 2020-12-08 3564/week @ 2020-12-15 1776/week @ 2020-12-22 2175/week @ 2020-12-29 4676/week @ 2021-01-05 3896/week @ 2021-01-12 4811/week @ 2021-01-19 4594/week @ 2021-01-26 5495/week @ 2021-02-02 7032/week @ 2021-02-09

13,875 downloads per month
Used in 25 crates (18 directly)

MIT/Apache

15KB
194 lines

async-recursion macro

Build Status

Procedural macro for recursive async functions.

Motivation

Consider the following recursive implementation of the fibonacci numbers:

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:

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`.

This crate provides an attribute macro to automatically convert an async function to one returning a boxed Future.

Example

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

By default the returned future has a Send bound to make sure that it can be sent between threads. If this is not desired you can mark that you would like that that bound to be left out like so:

#[async_recursion(?Send)]
async fn example() {}

In other words, #[async_recursion] modifies your function to return a BoxFuture and #[async_recursion(?Send)] modifies your function to return a LocalBoxFuture.

Installation

Add this to your Cargo.toml:

[dependencies]
async-recursion = "0.2"

License

Licensed under either of

Dependencies

~0.4–0.8MB
~20K SLoC