Good way to implement this Future

Hi there,

I'm trying to implement a Future that is able to run through several states and cary some data as either Vec or array right from the beginning up to the state where the data is needed to be processed.
My kinda naive implementation looks like this:

enum TestFuture {
    Entry{ data: Option<Vec<u8>> },
    State1{ data: Option<Vec<u8>> },
}

impl Future for TestFuture {
    type Output = ();
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        
        let this = self.get_mut();
        let next_state = match *this {
            TestFuture::Entry { data } => TestFuture::State1 {
                data
            },
            TestFuture::State1 { data } => return Poll::Ready(()),
        };
        
        *this = next_state;
        
        Poll::Pending
    }
}
  • just ignore that this example does not cover waking up the Future but this is not impacting my question in any way -

For obvious reasons this does not compile as I'm not able to move the Option<Vec> out of *this. The only idea that comes into my Rust greenhorn head is to copy the Vec in memory and use this for the next state, but this feels odd and a waste of resources. Is there any better way of doing this (appart from splitting each state into a separate Future which I'd consider as no-no as it would make things more complecated in my mind then they need to be.

As a side node: I'm working in no_std environment but do have a custom allocator in place :slight_smile: Any hint would be much appreciated.

A simple solution to your problem, since the Vec is inside an Option, would be to move the Vec out with Option::take(), leaving a None in its place.

2 Likes

If the vector is not in an Option, you would also be able to use std::mem::take, which takes the vector and leaves an empty vector in place.

More generally you can use std::mem::replace with a dummy state.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.