How are you supposed to implement AsyncWrite?

⚓ Rust    📅 2025-06-22    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 52 days ago. The information described in this article may have changed.

If I have some third party struct that I want to implement Write for, it's easy to make a wrapper like this:

struct ExternalType;

impl ExternalType {
    fn foo(&mut self, data: &[u8]) {
        todo!()
    }
}

struct WriteWrapper(ExternalType);

impl Write for WriteWrapper {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.foo(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

But if I have an async struct I want to implement AsyncWrite for, I cannot figure out how to do so. I want to do the equivalent of this:

struct AsyncExternalType;

impl AsyncExternalType {
    async fn foo(&mut self, data: &[u8]) {
        todo!()
    }
}

struct AsyncWriteWrapper(AsyncExternalType);

impl tokio::io::AsyncWrite for AsyncWriteWrapper {
    async fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.foo(buf).await;
        Ok(buf.len())
    }
}

I understand that this isn't how the tokio::io::AsyncWrite trait works, instead I'm supposed to implement poll_write and friends, but those are not async. Based on my searching the internet, I'm supposed to store a future on the wrapper that I set in the poll, but I cannot figure out how to do so without running into impossible lifetime issues.

How am I supposed to implement tokio::io::AsyncWrite when all I want to do is call an async method with the buf provided on some other type?

1 post - 1 participant

Read full topic

🏷️ rust_feed