Skip to content

replace unfold with from_fn #1609

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
cramertj opened this issue May 15, 2019 · 4 comments
Open

replace unfold with from_fn #1609

cramertj opened this issue May 15, 2019 · 4 comments

Comments

@cramertj
Copy link
Member

a la https://doc.rust-lang.org/std/iter/fn.from_fn.html

@cramertj
Copy link
Member Author

aaaand unfortunately this doesn't work out today because the returned async body can't reference upvars from the closure passed in, so we still need unfold. :(

@danielhenrymantilla
Copy link
Contributor

FWIW, we can finally implement this on 1.85.0 onwards 🙂, courtesy of AsyncFnMut() -> Option<Item>, whose lifetime semantics are exactly what we need here

@cramertj cramertj reopened this Apr 11, 2025
@cramertj
Copy link
Member Author

@danielhenrymantilla Unfortunately, I believe it's still not possible to spell this API without return type notation or type alias impl trait.

Without these features, there's no way to spell this struct:

pub struct FromFn<'a, Item, F: AsyncFnMut() -> Option<Item>> {
    func: F,
    ongoing_future: Option<F::CallRefFuture<'a>>, // `CallRefFuture` aka `F::async_call_mut(...)` isn't stable
}

@danielhenrymantilla
Copy link
Contributor

danielhenrymantilla commented Apr 11, 2025

Do we necessarily need it to be named? The closure param inside it will remain hard-to-name, so I'd imagine we can bite the bullet and just involve an -> impl Stream API:

use ::futures::stream::{self, Stream};

fn from_fn<Item>(
    f: impl AsyncFnMut() -> Option<Item>,
) -> impl Stream<Item = Item> {
    stream::unfold(f, |mut f| async move {
        Some((f().await?, f))
    })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants