1

我正在寻找为返回某种类型的任何流实现包装器结构,以减少乱扔我的应用程序的动态关键字。我遇到过BoxStream,但不知道如何在Stream::poll_next. 这是我到目前为止所拥有的:

use std::pin::Pin;
use std::task::{Context, Poll};
use futures::prelude::stream::BoxStream;
use futures::Stream;

pub struct Row;

pub struct RowCollection<'a> {
    stream: BoxStream<'a, Row>,
}

impl RowCollection<'_> {
    pub fn new<'a>(stream: BoxStream<Row>) -> RowCollection {
        RowCollection { stream }
    }
}

impl Stream for RowCollection<'_> {
    type Item = Row;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // I have no idea what to put here, but it needs to get the information from self.stream and return appropriate value
    }
}

依赖项:

期货=“0.3”

4

1 回答 1

3

既然Box实现Unpin了,那么就BoxStream实现Unpin了,以此类推RowCollection

正因为如此,你可以利用Pin::get_mut其中会给你一个&mut RowCollection. 从中,您可以获得一个&mut BoxStream. 您可以重新固定该通过Pin::new,然后调用poll_next它。这称为引脚投影

impl Stream for RowCollection<'_> {
    type Item = Row;
    
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.get_mut().stream).poll_next(cx)
    }
}

也可以看看:

于 2021-11-29T19:42:48.247 回答