jk_games
jk_games

Reputation: 27

Stream storing a self-referencing future in rust

This is a simplified version of my code:

struct B;
impl B {
    pub async fn func(&self) {}
}

struct A<'a> {
    b: B,
    current: Option<std::pin::Pin<Box<dyn futures::Future<Output = ()> + 'a>>>,
}
impl<'a> futures::Stream for A<'a> {
    type Item = ();
    fn poll_next<'b: 'a>(
        self: std::pin::Pin<&'b mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> futures::task::Poll<Option<Self::Item>> {
        let this: &'b mut A<'a> = self.get_mut();
        if let Some(future) = &mut this.current {
            future.as_mut().poll(cx).map(Some)
        } else {
            let future = this.b.func();
            this.current = Some(Box::pin(future));
            futures::task::Poll::Pending
        }
    }
}

In reality A also stores a stream and polls it.

Currently my problem is that to store the future inside of A it needs to borrow A for 'a. But in this function self is borrowed for some lifetime 'b not connected to 'a. When I try to assert that b': 'a I get the reasonable error that that requirement is not in the Stream trait.

Is this not possible in safe rust?

Upvotes: 0

Views: 54

Answers (0)

Related Questions