mirror of
https://github.com/async-rs/async-std.git
synced 2025-03-04 17:19:41 +00:00
Sketch out rfold
This commit is contained in:
parent
78bafbb88f
commit
cc493df433
2 changed files with 63 additions and 0 deletions
|
@ -1,8 +1,10 @@
|
|||
mod nth_back;
|
||||
mod rfind;
|
||||
mod rfold;
|
||||
|
||||
use nth_back::NthBackFuture;
|
||||
use rfind::RFindFuture;
|
||||
use rfold::RFoldFuture;
|
||||
|
||||
extension_trait! {
|
||||
use crate::stream::Stream;
|
||||
|
@ -67,5 +69,16 @@ extension_trait! {
|
|||
RFindFuture::new(self, p)
|
||||
}
|
||||
|
||||
fn rfold<B, F>(
|
||||
self,
|
||||
accum: B,
|
||||
f: F,
|
||||
) -> impl Future<Output = Option<B>> [RFoldFuture<Self, F, B>]
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(B, Self::Item) -> B,
|
||||
{
|
||||
RFoldFuture::new(self, accum, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
50
src/stream/double_ended/rfold.rs
Normal file
50
src/stream/double_ended/rfold.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
use crate::stream::DoubleEndedStream;
|
||||
|
||||
pin_project! {
|
||||
pub struct RFoldFuture<S, F, B> {
|
||||
#[pin]
|
||||
stream: S,
|
||||
f: F,
|
||||
acc: Option<B>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F, B> RFoldFuture<S, F, B> {
|
||||
pub(super) fn new(stream: S, init: B, f: F) -> Self {
|
||||
RFoldFuture {
|
||||
stream,
|
||||
f,
|
||||
acc: Some(init),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, F, B> Future for RFoldFuture<S, F, B>
|
||||
where
|
||||
S: DoubleEndedStream + Sized,
|
||||
F: FnMut(B, S::Item) -> B,
|
||||
{
|
||||
type Output = B;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let mut this = self.project();
|
||||
loop {
|
||||
let next = futures_core::ready!(this.stream.as_mut().poll_next_back(cx));
|
||||
|
||||
match next {
|
||||
Some(v) => {
|
||||
let old = this.acc.take().unwrap();
|
||||
let new = (this.f)(old, v);
|
||||
*this.acc = Some(new);
|
||||
}
|
||||
None => return Poll::Ready(this.acc.take().unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue