Skip to main content

tuwunel_core/utils/stream/
try_tools.rs

1//! TryStreamTools for futures::TryStream
2#![expect(clippy::type_complexity)]
3
4use futures::{
5	StreamExt, TryStream, TryStreamExt, future,
6	future::{Ready, ready},
7	stream::TryTakeWhile,
8};
9
10use crate::Result;
11
12/// Adds general-purpose operations to fallible streams.
13///
14/// Operations preserve the source error type and process successful items in
15/// source order. They support limiting the stream and collecting successful
16/// pairs, with or without the errors beside them.
17pub trait TryTools<T, E, S>
18where
19	S: TryStream<Ok = T, Error = E, Item = Result<T, E>> + ?Sized,
20	Self: TryStream + Sized,
21{
22	/// Limits the stream to at most `n` successful items.
23	///
24	/// After yielding `n` successes, the adapter consumes one additional
25	/// success to detect the limit. Earlier source errors are still forwarded;
26	/// with zero, they precede consumption of the first unyielded success.
27	fn try_take(
28		self,
29		n: usize,
30	) -> TryTakeWhile<
31		Self,
32		Ready<Result<bool, S::Error>>,
33		impl FnMut(&S::Ok) -> Ready<Result<bool, S::Error>>,
34	>;
35
36	/// Collects successful pairs into two collections.
37	///
38	/// Collections are extended in source order, starting from their defaults.
39	/// The first source error ends the fold without returning partial collections.
40	fn try_unzip<FromA, FromB>(self) -> impl Future<Output = Result<(FromA, FromB), S::Error>>
41	where
42		(FromA, FromB): Default + Extend<T>;
43
44	/// Collects successful pairs into two collections and every error into a third.
45	///
46	/// Collections are extended in source order, starting from their defaults.
47	/// Unlike [`Self::try_unzip`], an error does not end the fold.
48	fn try_unzip_partial<FromA, FromB, FromE>(
49		self,
50	) -> impl Future<Output = ((FromA, FromB), FromE)>
51	where
52		(FromA, FromB): Default + Extend<T>,
53		FromE: Default + Extend<E>;
54}
55
56impl<T, E, S> TryTools<T, E, S> for S
57where
58	S: TryStream<Ok = T, Error = E, Item = Result<T, E>> + ?Sized,
59	Self: TryStream + Sized,
60{
61	#[inline]
62	fn try_take(
63		self,
64		mut n: usize,
65	) -> TryTakeWhile<
66		Self,
67		Ready<Result<bool, S::Error>>,
68		impl FnMut(&S::Ok) -> Ready<Result<bool, S::Error>>,
69	> {
70		self.try_take_while(move |_| {
71			let res = future::ok(n > 0);
72			n = n.saturating_sub(1);
73			res
74		})
75	}
76
77	#[inline]
78	fn try_unzip<FromA, FromB>(self) -> impl Future<Output = Result<(FromA, FromB), S::Error>>
79	where
80		(FromA, FromB): Default + Extend<T>,
81	{
82		self.try_fold(<(FromA, FromB)>::default(), |mut collections, item| {
83			collections.extend([item]);
84			ready(Ok(collections))
85		})
86	}
87
88	#[inline]
89	fn try_unzip_partial<FromA, FromB, FromE>(
90		self,
91	) -> impl Future<Output = ((FromA, FromB), FromE)>
92	where
93		(FromA, FromB): Default + Extend<T>,
94		FromE: Default + Extend<E>,
95	{
96		self.into_stream().fold(
97			<((FromA, FromB), FromE)>::default(),
98			|(mut collections, mut errors), item| {
99				match item {
100					| Ok(item) => collections.extend([item]),
101					| Err(error) => errors.extend([error]),
102				}
103
104				ready((collections, errors))
105			},
106		)
107	}
108}