如何将Pin与Tokio的水槽一起使用?

时间:2019-08-13 07:09:20

标签: rust future rust-tokio

我想创建一个在实现Tokio的Sink的结构上发送一些数据的方法,但是我在使用Pin作为自身时遇到了问题。本质上,我需要这样的东西:

fn send_data(&mut self, data: Item, cx: &mut Context) -> Poll<Result<(), Error>> {
    futures_core::ready!(something.poll_ready(cx))?;
    something.start_send(data)?;
    futures_core::ready!(something.poll_close(cx))
}

问题在于,每次对poll_ready()start_send()poll_close()的调用都需要self: Pin<&mut Self>,而我不知道用例应该使用什么something是。如果我尝试使用let something = Pin::new(self);,则something会在调用poll_ready()之后被移动,因此我无法将其用于后续调用(此时,self也消失了)。我该如何解决此问题?

use futures_core;
use std::pin::Pin;
use tokio::prelude::*; // 0.3.0-alpha.1

struct Test {}

impl Sink<i32> for Test {
    type Error = ();

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn start_send(self: Pin<&mut Self>, item: i32) -> Result<(), Self::Error> {
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
}

impl Test {
    fn send_data(&mut self, data: i32, cx: &mut Context) -> Poll<Result<(), Error>> {
        // what should "something" here be?
        futures_core::ready!(something.poll_ready(cx))?;
        something.start_send(data)?;
        futures_core::ready!(something.poll_close(cx))
    }
}

0 个答案:

没有答案