tuwunel_core/utils/stream/
try_tools.rs1#![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
12pub trait TryTools<T, E, S>
18where
19 S: TryStream<Ok = T, Error = E, Item = Result<T, E>> + ?Sized,
20 Self: TryStream + Sized,
21{
22 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 fn try_unzip<FromA, FromB>(self) -> impl Future<Output = Result<(FromA, FromB), S::Error>>
41 where
42 (FromA, FromB): Default + Extend<T>;
43
44 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}