Sketch out nth_back

split-by-pattern
Felipe Sere 5 years ago
parent fa288931c6
commit d0ef48c753

@ -1,9 +1,14 @@
mod nth_back;
use nth_back::NthBackFuture;
extension_trait! { extension_trait! {
use crate::stream::Stream; use crate::stream::Stream;
use std::pin::Pin; use std::pin::Pin;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
#[doc = r#" #[doc = r#"
Something fancy Something fancy
"#] "#]
@ -17,6 +22,36 @@ extension_trait! {
Something else Something else
"#] "#]
pub trait DoubleEndedStreamExt: crate::stream::DoubleEndedStream { pub trait DoubleEndedStreamExt: crate::stream::DoubleEndedStream {
#[doc = r#"
Returns the nth element from the back of the stream.
# Examples
Basic usage:
```
# fn main() { async_std::task::block_on(async {
#
use async_std::stream::double_ended::DoubleEndedStreamExt;
use async_std::stream;
let mut s = stream::from_iter(vec![1u8, 2, 3, 4, 5]);
let second = s.nth_back(1).await;
assert_eq!(second, Some(4));
#
# }) }
```
"#]
fn nth_back(
&mut self,
n: usize,
) -> impl Future<Output = Option<Self::Item>> + '_ [NthBackFuture<'_, Self>]
where
Self: Unpin + Sized,
{
NthBackFuture::new(self, n)
}
} }
} }

@ -0,0 +1,39 @@
use std::pin::Pin;
use std::task::{Context, Poll};
use std::future::Future;
use crate::stream::DoubleEndedStream;
pub struct NthBackFuture<'a, S> {
stream: &'a mut S,
n: usize,
}
impl<'a, S> NthBackFuture<'a, S> {
pub(crate) fn new(stream: &'a mut S, n: usize) -> Self {
NthBackFuture { stream, n }
}
}
impl<'a, S> Future for NthBackFuture<'a, S>
where
S: DoubleEndedStream + Sized + Unpin,
{
type Output = Option<S::Item>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let next = futures_core::ready!(Pin::new(&mut *self.stream).poll_next_back(cx));
match next {
Some(v) => match self.n {
0 => Poll::Ready(Some(v)),
_ => {
self.n -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
},
None => Poll::Ready(None),
}
}
}

@ -318,7 +318,7 @@ mod repeat;
mod repeat_with; mod repeat_with;
cfg_unstable! { cfg_unstable! {
mod double_ended; pub mod double_ended;
mod double_ended_stream; mod double_ended_stream;
mod exact_size_stream; mod exact_size_stream;
mod extend; mod extend;

Loading…
Cancel
Save