Wrapping tokio asyncread with an Enum

Hey,
Im trying to wrap an Tokio Stream (tokio::net::TcpStream) with an enum. I found this on (stackoverflow with a similar problem. I was able to modify it to compile.

If I change that code example to use an Enum instead of a struct I keep running into problems and cant seem to figure out how to get it work. Any help or insight would be great! Thanks!

use std::io::Result;
use core::pin::Pin;
use core::task::{Context, Poll};
use tokio::io::ReadBuf;

use tokio::io::AsyncRead;
use std::io;


pub struct Wrapper<T: AsyncRead + std::marker::Unpin>{
    inner: T
}

impl<T: AsyncRead + std::marker::Unpin> AsyncRead for Wrapper<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_read(cx, buf)
    }
}

pub enum WrapperEnum<T: AsyncRead + std::marker::Unpin>{
    Foo{inner: T},
    Bar{inner: T}
}

impl<T: AsyncRead + std::marker::Unpin> AsyncRead for WrapperEnum<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        match &*self {
            WrapperEnum::Foo{inner} => Pin::new(&mut inner).poll_read(cx, buf),
            WrapperEnum::Foo{inner} => Pin::new(&mut inner).poll_read(cx, buf)
        }
    }
}

(Playground)

The problem is in the match &*self line. AsyncRead wants a mutable Pin<&mut Self> borrow, but &*self only creates an immutable borrow. So the fix is to use a &mut *self borrow (Rust Playground):

impl<T: AsyncRead + Unpin> AsyncRead for WrapperEnum<T> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        match &mut *self {
            WrapperEnum::Foo { inner } => Pin::new(inner).poll_read(cx, buf),
            WrapperEnum::Bar { inner } => Pin::new(inner).poll_read(cx, buf),
        }
    }
}

Ah I see. Thanks that solved it! Idk why I couldn't figure that out on my own

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.