Skip to content

Commit

Permalink
Implement async support
Browse files Browse the repository at this point in the history
Refactor doctests slightly
  • Loading branch information
speelbarrow committed Jul 25, 2023
1 parent f616532 commit e647697
Showing 1 changed file with 32 additions and 25 deletions.
57 changes: 32 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,29 +65,6 @@ impl Enum {
}
}
```
```
# use enum_from_functions::enum_from_functions;
// `async` functions are allowed, but then all functions in the `impl` block must be `async`.
// As well, the generated `map` function will also be `async`.
#[enum_from_functions]
impl Enum {
async fn foo() -> &'static str {
"Foo"
}
async fn bar() -> &'static str {
"Bar"
}
}
fn main() {
# futures::executor::block_on(
async {
assert_eq!(Enum::map(Enum::Foo).await, "Foo");
assert_eq!(Enum::map(Enum::Bar).await, "Bar");
}
# )
}
```
```compile_fail
# use enum_from_functions::enum_from_functions;
// Causes a compile error because the return types don't match.
Expand All @@ -114,6 +91,29 @@ impl Enum {
}
}
```
`async` functions are allowed, but then all functions in the `impl` block must be `async`. The generated `map` function
will also be `async`.
```
# use enum_from_functions::enum_from_functions;
#[enum_from_functions]
impl Enum {
async fn foo() -> &'static str {
"Foo"
}
async fn bar() -> &'static str {
"Bar"
}
}
fn main() {
# futures::executor::block_on(
async {
assert_eq!(Enum::map(Enum::Foo).await, "Foo");
assert_eq!(Enum::map(Enum::Bar).await, "Bar");
}
# )
}
```
You can also create an empty `enum` by not providing any functions in the `impl` block (though I'm not sure why you
would want to do this).
```
Expand Down Expand Up @@ -189,7 +189,7 @@ use syn::{
parse_macro_input, parse_quote,
punctuated::{Pair, Punctuated},
token::Comma,
FnArg, ImplItem, Pat,
FnArg, ImplItem, Pat, Token,
};

/**
Expand Down Expand Up @@ -281,10 +281,17 @@ pub fn enum_from_functions(args: TokenStream, input: TokenStream) -> TokenStream
}
}));

let (await_dot, await_token) = some.asyncness.map_or((None, None), |_| {
(
Some(<Token![.]>::default()),
Some(<Token![await]>::default()),
)
});

parse_quote! {
pub #sig {
match self {
#(Self::#variants => Self::#function_names(#args)),*
#(Self::#variants => Self::#function_names(#args) #await_dot #await_token),*
}
}
}
Expand Down

0 comments on commit e647697

Please sign in to comment.