Tracking an Optional Future as state

⚓ Rust    📅 2025-09-03    👤 surdeus    👁️ 1      

surdeus

I'm working on trying to clean up some code I've written to implement a custom/proprietary protocol over Bluetooth, and running into a challenge I'm not entirely sure how to deal with. The protocol consists of various commands wrapped in frames and sent over a serial link, where the framing layer includes things like sequence numbering, acknowledgement, checksumming.

I learned about tokio_util::codec::Framed and used it to implement the framing, so I now have a Stream + Sink of Frames. Next, I'd like to wrap this duplex stream to produce one working on Commands, taking care of the sequence numbers/acknowledging (and eventually resending with backoff) so that the rest of the code doesn't need to worry about the low-level details.


This is where I've ran into a bit of an issue as I'm trying to implement Stream in such a way that acknowledgements might be sent to the wrapped Sink<Frame> as part of reading from the stream.

I came across this post from three years ago, and via it the async-stream crate, but I don't think it's applicable directly in my usecase and looking at the implementation didn't help me see how to handle it either. Essentially I'm trying to implement the approach of keeping track of a "priority" Future and polling it as part of poll_next, not processing any other frames until we've acknowledged the current one.

Here's a playground with a reduced sketch of my current best attempt: Rust Playground

I'd love for some guidance about ideally both

  • how I can track an optional Future like this and poll it when I have Some(future)
  • if there's a different, better way to approach this that's more idiomatic

Thanks!

1 post - 1 participant

Read full topic

🏷️ Rust_feed