Skip to content

Commit cc493df

Browse files
committed
Sketch out rfold
1 parent 78bafbb commit cc493df

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/stream/double_ended/mod.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
mod nth_back;
22
mod rfind;
3+
mod rfold;
34

45
use nth_back::NthBackFuture;
56
use rfind::RFindFuture;
7+
use rfold::RFoldFuture;
68

79
extension_trait! {
810
use crate::stream::Stream;
@@ -67,5 +69,16 @@ extension_trait! {
6769
RFindFuture::new(self, p)
6870
}
6971

72+
fn rfold<B, F>(
73+
self,
74+
accum: B,
75+
f: F,
76+
) -> impl Future<Output = Option<B>> [RFoldFuture<Self, F, B>]
77+
where
78+
Self: Sized,
79+
F: FnMut(B, Self::Item) -> B,
80+
{
81+
RFoldFuture::new(self, accum, f)
82+
}
7083
}
7184
}

src/stream/double_ended/rfold.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
use std::future::Future;
2+
use std::pin::Pin;
3+
use std::task::{Context, Poll};
4+
5+
use pin_project_lite::pin_project;
6+
7+
use crate::stream::DoubleEndedStream;
8+
9+
pin_project! {
10+
pub struct RFoldFuture<S, F, B> {
11+
#[pin]
12+
stream: S,
13+
f: F,
14+
acc: Option<B>,
15+
}
16+
}
17+
18+
impl<S, F, B> RFoldFuture<S, F, B> {
19+
pub(super) fn new(stream: S, init: B, f: F) -> Self {
20+
RFoldFuture {
21+
stream,
22+
f,
23+
acc: Some(init),
24+
}
25+
}
26+
}
27+
28+
impl<S, F, B> Future for RFoldFuture<S, F, B>
29+
where
30+
S: DoubleEndedStream + Sized,
31+
F: FnMut(B, S::Item) -> B,
32+
{
33+
type Output = B;
34+
35+
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
36+
let mut this = self.project();
37+
loop {
38+
let next = futures_core::ready!(this.stream.as_mut().poll_next_back(cx));
39+
40+
match next {
41+
Some(v) => {
42+
let old = this.acc.take().unwrap();
43+
let new = (this.f)(old, v);
44+
*this.acc = Some(new);
45+
}
46+
None => return Poll::Ready(this.acc.take().unwrap()),
47+
}
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)