parent
89ffe57153
commit
2155e729d7
@ -0,0 +1,53 @@
|
||||
use super::*;
|
||||
use pin_project::pin_project;
|
||||
use std::{
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
#[pin_project]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MaybeStream<I,T>(#[pin] Option<I>)
|
||||
where I: Stream<Item=T>;
|
||||
|
||||
pub trait OptionStreamExt<I, T>: Sized
|
||||
where I: Stream<Item=T>
|
||||
{
|
||||
/// Map this `Option<Stream>` into a stream that will yield the items of the stream if it is present.
|
||||
fn map_into_stream(self) -> MaybeStream<I,T>;
|
||||
}
|
||||
|
||||
impl<I: Stream<Item=T>, T> Stream for MaybeStream<I,T>
|
||||
{
|
||||
type Item = T;
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
match self.project().0.as_pin_mut()
|
||||
{
|
||||
Some(i) => i.poll_next(cx),
|
||||
_ => Poll::Ready(None),
|
||||
}
|
||||
}
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
match &self.0 {
|
||||
Some(i) => i.size_hint(),
|
||||
None => (0, Some(0)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<E, T, I: Stream<Item=T>> OptionStreamExt<I, T> for Result<I, E>
|
||||
where I: Stream<Item = T>
|
||||
{
|
||||
#[inline] fn map_into_stream(self) -> MaybeStream<I, T> {
|
||||
MaybeStream(self.ok())
|
||||
}
|
||||
}
|
||||
impl<T, I: Stream<Item=T>> OptionStreamExt<I, T> for Option<I>
|
||||
where I: Stream<Item = T>
|
||||
{
|
||||
#[inline] fn map_into_stream(self) -> MaybeStream<I, T> {
|
||||
MaybeStream(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
Loading…
Reference in new issue