Skip to main content

tuwunel_core/utils/
option.rs

1//! Asynchronous mapping adapters for optional values.
2//!
3//! [`OptionExt`] turns an optional value into an optional future, a fallible
4//! future of an option, or a zero-or-one stream. The mapping closure runs only
5//! when the option contains a value.
6
7use futures::{FutureExt, Stream, future::OptionFuture};
8
9use super::IterStream;
10
11/// Extends [`Option`] with asynchronous mapping adapters.
12///
13/// [`OptionExt::map_async`] preserves optionality through future completion.
14/// [`OptionExt::map_stream`] exposes the mapped result as a zero-or-one stream.
15/// [`OptionExt::try_map_async`] lifts a fallible future's error out of the
16/// option.
17pub trait OptionExt<T> {
18	/// Maps the contained value to a future without eagerly awaiting it.
19	///
20	/// A [`Some`] value yields an [`OptionFuture`] that resolves to the mapped
21	/// output. [`None`] resolves to `None` and never calls the mapping
22	/// closure.
23	fn map_async<F, Fut, U>(self, f: F) -> OptionFuture<Fut>
24	where
25		F: FnOnce(T) -> Fut,
26		Fut: Future<Output = U> + Send,
27		U: Send;
28
29	/// Maps the contained value to a future-backed stream with at most one
30	/// item.
31	///
32	/// A [`Some`] value yields the mapped output after its future completes.
33	/// [`None`] yields an empty stream and never calls the mapping closure.
34	#[inline]
35	fn map_stream<F, Fut, U>(self, f: F) -> impl Stream<Item = U> + Send
36	where
37		F: FnOnce(T) -> Fut,
38		Fut: Future<Output = U> + Send,
39		U: Send,
40		Self: Sized,
41	{
42		self.map_async(f)
43			.map(Option::into_iter)
44			.map(IterStream::stream)
45			.flatten_stream()
46	}
47
48	/// Maps the contained value to a fallible future and lifts its error out.
49	///
50	/// A [`Some`] value resolves to the mapped output in `Ok(Some(_))`, or to
51	/// the future's error. [`None`] resolves to `Ok(None)` and never calls the
52	/// mapping closure.
53	#[inline]
54	fn try_map_async<F, Fut, U, E>(
55		self,
56		f: F,
57	) -> impl Future<Output = Result<Option<U>, E>> + Send
58	where
59		F: FnOnce(T) -> Fut,
60		Fut: Future<Output = Result<U, E>> + Send,
61		U: Send,
62		E: Send,
63		Self: Sized,
64	{
65		self.map_async(f).map(Option::transpose)
66	}
67}
68
69impl<T> OptionExt<T> for Option<T> {
70	#[inline]
71	fn map_async<F, Fut, U>(self, f: F) -> OptionFuture<Fut>
72	where
73		F: FnOnce(T) -> Fut,
74		Fut: Future<Output = U> + Send,
75		U: Send,
76	{
77		self.map(f).into()
78	}
79}