Crates.io | future-union |
lib.rs | future-union |
version | 0.1.1 |
source | src |
created_at | 2019-04-13 16:27:38.492987 |
updated_at | 2019-04-13 16:39:28.398597 |
description | Use future::Either with `impl Future` |
homepage | |
repository | https://github.com/djmcgill/future-union |
max_upload_size | |
id | 127690 |
size | 25,477 |
When you use impl traits, specifically with futures,
sometimes you will want to have a branching expression
(e.g. an if
or match
) in which the different branches
return different types that both impl Future. This does
not work since in current stable rust impl trait can only
refer to a single type.
One solution to this problem is to use futures::future::Either
to combine together all your different possible futures together
into one type to return. Doing this by hand is really annoying
and requires sweeping changes when you change the number of
possible branches.
This macro future_union
does this automatically.
Currently you still have to keep the total count per function, and then
also the index (starting from 0). If those values are inaccurate then
you'll get horrible type errors.
use futures::future::{self, Future};
use future_union::future_union;
fn impl_demo(n: usize) -> impl Future<Item=(), Error=()> {
match n {
0 => future_union!(3, 0, future::ok(())),
1 => future_union!(3, 1, future::ok(()).map(|_| ())),
_ => future_union!(3, 2, future::ok(()).map(|_| ()).map(|_| ())),
}
}
future_union
calls
in a given function and automatically adds the correct count and index e.g.:
use futures::future::{self, Future};
use future_union::*;
#[future_union_fn]
fn impl_demo(n: usize) -> impl Future<Item=(), Error=()> {
match n {
0 => future_union_auto!(future::ok(())),
1 => future_union_auto!(future::ok(()).map(|_| ())),
_ => future_union_auto!(future::ok(()).map(|_| ()).map(|_| ())),
}
}
Contributions welcome!
Licensed under either of
at your option.
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.