abstract and encapsulate the awkward OptionFuture into Stream pattern

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2025-04-04 02:39:40 +00:00
parent 532dfd004d
commit bb8320a691
4 changed files with 35 additions and 40 deletions

View file

@ -1,9 +1,11 @@
mod bool_ext;
mod ext_ext;
mod option_ext;
mod option_stream;
mod try_ext_ext;
pub use bool_ext::{BoolExt, and, or};
pub use ext_ext::ExtExt;
pub use option_ext::OptionExt;
pub use option_stream::OptionStream;
pub use try_ext_ext::TryExtExt;

View file

@ -11,11 +11,14 @@ pub trait OptionExt<T> {
impl<T, Fut> OptionExt<T> for OptionFuture<Fut>
where
Fut: Future<Output = T> + Send,
T: Send,
{
#[inline]
fn is_none_or(self, f: impl FnOnce(&T) -> bool + Send) -> impl Future<Output = bool> + Send {
self.map(|o| o.as_ref().is_none_or(f))
}
#[inline]
fn is_some_and(self, f: impl FnOnce(&T) -> bool + Send) -> impl Future<Output = bool> + Send {
self.map(|o| o.as_ref().is_some_and(f))
}

View file

@ -0,0 +1,25 @@
use futures::{Future, FutureExt, Stream, StreamExt, future::OptionFuture};
use super::super::IterStream;
pub trait OptionStream<T> {
fn stream(self) -> impl Stream<Item = T> + Send;
}
impl<T, O, S, Fut> OptionStream<T> for OptionFuture<Fut>
where
Fut: Future<Output = (O, S)> + Send,
S: Stream<Item = T> + Send,
O: IntoIterator<Item = T> + Send,
<O as IntoIterator>::IntoIter: Send,
T: Send,
{
#[inline]
fn stream(self) -> impl Stream<Item = T> + Send {
self.map(|opt| opt.map(|(curr, next)| curr.into_iter().stream().chain(next)))
.map(Option::into_iter)
.map(IterStream::stream)
.flatten_stream()
.flatten()
}
}