为了 API 方便,我如何包装动态类型的流?
How can I wrap a dynamically typed stream for API convenience?
我希望为任何 returns 特定类型的流实现包装器结构,以减少乱丢我的应用程序的动态关键字。我遇到过 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”
由于 Box
implements Unpin
,BoxStream
实施 Unpin
,因此 RowCollection
。
因此,您可以利用 Pin::get_mut
which will give you a &mut RowCollection
. From that, you can get a &mut BoxStream
. You can re-pin that via Pin::new
and then call poll_next
on it. This is called pin-projection。
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)
}
}
另请参阅:
我希望为任何 returns 特定类型的流实现包装器结构,以减少乱丢我的应用程序的动态关键字。我遇到过 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”
由于 Box
implements Unpin
,BoxStream
实施 Unpin
,因此 RowCollection
。
因此,您可以利用 Pin::get_mut
which will give you a &mut RowCollection
. From that, you can get a &mut BoxStream
. You can re-pin that via Pin::new
and then call poll_next
on it. This is called pin-projection。
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)
}
}
另请参阅: