Skip to main content

ntex_util/future/
either.rs

1use std::{error, fmt, future::Future, io, pin::Pin, task::Context, task::Poll};
2
3use ntex_service::{BindCtx, Ctx, Service};
4
5/// A value of one of two types.
6///
7/// `Either` is a [`Future`] when both variants are futures with the same
8/// output, and a [`Service`] when both variants are services with the same
9/// request, response, and error types.
10#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
11pub enum Either<A, B> {
12    /// First branch of the type
13    Left(A),
14    /// Second branch of the type
15    Right(B),
16}
17
18impl<A, B> Either<A, B> {
19    fn project(self: Pin<&mut Self>) -> Either<Pin<&mut A>, Pin<&mut B>> {
20        // `pin-project-lite` does not support tuple variants.
21        // SAFETY: structural pinning; the variant value is never moved out
22        // of a pinned `Either`, and `Either` has no `Drop` impl.
23        unsafe {
24            match self.get_unchecked_mut() {
25                Either::Left(a) => Either::Left(Pin::new_unchecked(a)),
26                Either::Right(b) => Either::Right(Pin::new_unchecked(b)),
27            }
28        }
29    }
30
31    #[inline]
32    /// Returns `true` if the value is the `Left` variant.
33    pub fn is_left(&self) -> bool {
34        match *self {
35            Either::Left(_) => true,
36            Either::Right(_) => false,
37        }
38    }
39
40    #[inline]
41    /// Returns `true` if the value is the `Right` variant.
42    pub fn is_right(&self) -> bool {
43        !self.is_left()
44    }
45
46    #[inline]
47    /// Converts the left side of `Either<A, B>` to an `Option<A>`.
48    pub fn left(self) -> Option<A> {
49        match self {
50            Either::Left(l) => Some(l),
51            Either::Right(_) => None,
52        }
53    }
54
55    #[inline]
56    /// Converts the right side of `Either<A, B>` to an `Option<B>`.
57    pub fn right(self) -> Option<B> {
58        match self {
59            Either::Left(_) => None,
60            Either::Right(r) => Some(r),
61        }
62    }
63
64    #[inline]
65    /// Converts `&Either<A, B>` to `Either<&A, &B>`.
66    pub fn as_ref(&self) -> Either<&A, &B> {
67        match *self {
68            Either::Left(ref inner) => Either::Left(inner),
69            Either::Right(ref inner) => Either::Right(inner),
70        }
71    }
72
73    #[inline]
74    /// Converts `&mut Either<A, B>` to `Either<&mut A, &mut B>`.
75    pub fn as_mut(&mut self) -> Either<&mut A, &mut B> {
76        match *self {
77            Either::Left(ref mut inner) => Either::Left(inner),
78            Either::Right(ref mut inner) => Either::Right(inner),
79        }
80    }
81}
82
83impl<T> Either<T, T> {
84    #[inline]
85    /// Extracts the value of an `Either` over two equal types.
86    pub fn into_inner(self) -> T {
87        match self {
88            Either::Left(x) | Either::Right(x) => x,
89        }
90    }
91}
92
93/// `Either` implements `Error` if *both* `A` and `B` implement it.
94impl<A, B> error::Error for Either<A, B>
95where
96    A: error::Error,
97    B: error::Error,
98{
99    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
100        match self {
101            Either::Left(a) => a.source(),
102            Either::Right(b) => b.source(),
103        }
104    }
105}
106
107impl<A, B> fmt::Display for Either<A, B>
108where
109    A: fmt::Display,
110    B: fmt::Display,
111{
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Either::Left(a) => a.fmt(f),
115            Either::Right(b) => b.fmt(f),
116        }
117    }
118}
119
120impl<A, B> Future for Either<A, B>
121where
122    A: Future,
123    B: Future<Output = A::Output>,
124{
125    type Output = A::Output;
126
127    #[inline]
128    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
129        match self.project() {
130            Either::Left(x) => x.poll(cx),
131            Either::Right(x) => x.poll(cx),
132        }
133    }
134}
135
136impl<E: error::Error> From<Either<E, io::Error>> for io::Error {
137    fn from(err: Either<E, io::Error>) -> Self {
138        match err {
139            Either::Left(e) => io::Error::other(format!("{e:?}")),
140            Either::Right(e) => e,
141        }
142    }
143}
144
145impl<A, B, St, Req> Service<St, Req> for Either<A, B>
146where
147    A: Service<St, Req>,
148    B: Service<St, Req, Res = A::Res, Error = A::Error>,
149{
150    type Res = A::Res;
151    type Error = A::Error;
152
153    fn bind(&self, ctx: BindCtx<'_>) {
154        match self {
155            Either::Left(svc) => ctx.bind(svc),
156            Either::Right(svc) => ctx.bind(svc),
157        }
158    }
159
160    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<Self::Res, Self::Error> {
161        match self {
162            Either::Left(svc) => ctx.call(svc, req).await,
163            Either::Right(svc) => ctx.call(svc, req).await,
164        }
165    }
166
167    async fn ready(&self, ctx: Ctx<'_, Self, St>) -> Result<(), Self::Error> {
168        match self {
169            Either::Left(svc) => ctx.ready(svc).await,
170            Either::Right(svc) => ctx.ready(svc).await,
171        }
172    }
173
174    async fn shutdown(&self, ctx: Ctx<'_, Self, St>) {
175        match self {
176            Either::Left(svc) => ctx.shutdown(svc).await,
177            Either::Right(svc) => ctx.shutdown(svc).await,
178        }
179    }
180}
181
182#[cfg(test)]
183mod test {
184    use std::{cell::Cell, error::Error as _, future, rc::Rc};
185
186    use ntex_service::{Pipeline, ReadyBinding, ReadyNotifier};
187
188    use super::*;
189
190    /// STATEMENT: `Either` accessors, mutation, extraction, and display use the active branch.
191    ///
192    /// HOW:
193    /// - Inspect and mutate left and right values through borrowed accessors.
194    /// - Extract their values and compare inner-value and display results for both branches.
195    #[test]
196    fn accessors() {
197        let mut value = Either::<u8, String>::Left(10);
198        assert!(value.is_left());
199        assert!(!value.is_right());
200        assert_eq!(value.as_ref(), Either::Left(&10));
201        if let Either::Left(inner) = value.as_mut() {
202            *inner = 20;
203        }
204        assert_eq!(value.left(), Some(20));
205
206        let mut value = Either::<u8, String>::Right("right".to_owned());
207        assert!(!value.is_left());
208        assert!(value.is_right());
209        assert_eq!(value.as_ref(), Either::Right(&"right".to_owned()));
210        if let Either::Right(inner) = value.as_mut() {
211            inner.push_str(" branch");
212        }
213        assert_eq!(value.right().as_deref(), Some("right branch"));
214
215        assert_eq!(Either::<u8, u8>::Left(1).into_inner(), 1);
216        assert_eq!(Either::<u8, u8>::Right(2).into_inner(), 2);
217
218        assert_eq!(
219            format!("{}", Either::<_, &'static str>::Left("test")),
220            "test"
221        );
222        assert_eq!(
223            format!("{}", Either::<&'static str, _>::Right("test")),
224            "test"
225        );
226    }
227
228    /// STATEMENT: Awaiting `Either` returns the active future's output.
229    ///
230    /// HOW:
231    /// - Wrap ready futures in each branch and verify their distinct returned values.
232    #[ntex::test]
233    async fn future() {
234        let left: Either<_, future::Ready<u8>> = Either::Left(future::ready(10));
235        assert_eq!(left.await, 10);
236
237        let right: Either<future::Ready<u8>, _> = Either::Right(future::ready(20));
238        assert_eq!(right.await, 20);
239    }
240
241    #[derive(Debug)]
242    struct TestError {
243        message: &'static str,
244        source: Option<io::Error>,
245    }
246
247    impl fmt::Display for TestError {
248        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249            f.write_str(self.message)
250        }
251    }
252
253    impl error::Error for TestError {
254        fn source(&self) -> Option<&(dyn error::Error + 'static)> {
255            self.source
256                .as_ref()
257                .map(|source| source as &(dyn error::Error + 'static))
258        }
259    }
260
261    /// STATEMENT: `Either` forwards error messages and sources and preserves I/O conversion semantics.
262    ///
263    /// HOW:
264    /// - Inspect display and source chains for errors in both branches.
265    /// - Convert each branch to `io::Error` and check its kind and message.
266    #[test]
267    fn errors() {
268        let left = Either::<TestError, TestError>::Left(TestError {
269            message: "left",
270            source: Some(io::Error::other("left source")),
271        });
272        assert_eq!(left.to_string(), "left");
273        assert_eq!(left.source().unwrap().to_string(), "left source");
274
275        let right = Either::<TestError, TestError>::Right(TestError {
276            message: "right",
277            source: Some(io::Error::other("right source")),
278        });
279        assert_eq!(right.to_string(), "right");
280        assert_eq!(right.source().unwrap().to_string(), "right source");
281
282        let left: io::Error = Either::<TestError, io::Error>::Left(TestError {
283            message: "converted",
284            source: None,
285        })
286        .into();
287        assert_eq!(left.kind(), io::ErrorKind::Other);
288        assert!(left.to_string().contains("converted"));
289
290        let right: io::Error = Either::<TestError, io::Error>::Right(io::Error::new(
291            io::ErrorKind::TimedOut,
292            "right error",
293        ))
294        .into();
295        assert_eq!(right.kind(), io::ErrorKind::TimedOut);
296        assert_eq!(right.to_string(), "right error");
297    }
298
299    #[derive(Default)]
300    struct ServiceState {
301        bound: Cell<bool>,
302        ready: Cell<bool>,
303        failed: Cell<bool>,
304        called: Cell<bool>,
305        shutdown: Cell<bool>,
306        changed: ReadyNotifier,
307    }
308
309    struct TestService {
310        state: Rc<ServiceState>,
311        response: u8,
312    }
313
314    impl Service<(), u8> for TestService {
315        type Res = u8;
316        type Error = ();
317
318        fn bind(&self, ctx: BindCtx<'_>) {
319            self.state.bound.set(true);
320            ctx.subscribe(&self.state.changed);
321        }
322
323        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), Self::Error> {
324            self.state.ready.set(true);
325            if self.state.failed.get() { Err(()) } else { Ok(()) }
326        }
327
328        async fn call(&self, req: u8, _: Ctx<'_, Self>) -> Result<Self::Res, Self::Error> {
329            self.state.called.set(true);
330            Ok(req + self.response)
331        }
332
333        async fn shutdown(&self, _: Ctx<'_, Self>) {
334            self.state.shutdown.set(true);
335        }
336    }
337
338    /// STATEMENT: `Either` forwards binding, readiness, calls, and shutdown to its active service.
339    ///
340    /// HOW:
341    /// - Build pipelines for each branch using services with lifecycle flags.
342    /// - Check binding and calls, then notify a readiness failure and verify it reaches the pipeline.
343    /// - Restore readiness and verify shutdown reaches the active service.
344    #[ntex::test]
345    async fn service() {
346        async fn check(service: Either<TestService, TestService>, response: u8) {
347            let state = match &service {
348                Either::Left(service) | Either::Right(service) => service.state.clone(),
349            };
350            let service = Pipeline::new((), service);
351
352            assert!(state.bound.get());
353            assert_eq!(service.ready().await, Ok(()));
354            assert!(state.ready.get());
355            assert_eq!(service.call(5).await, Ok(5 + response));
356            assert!(state.called.get());
357
358            state.called.set(false);
359            state.failed.set(true);
360            state.changed.notify();
361            assert!(!service.is_ready());
362            assert_eq!(service.call(5).await, Err(()));
363            assert!(!state.called.get());
364            state.failed.set(false);
365            state.changed.notify();
366            assert_eq!(service.call(5).await, Ok(5 + response));
367
368            service.shutdown().await;
369            assert!(state.shutdown.get());
370        }
371
372        let state = Rc::new(ServiceState::default());
373        check(
374            Either::Left(TestService {
375                state,
376                response: 10,
377            }),
378            10,
379        )
380        .await;
381
382        let state = Rc::new(ServiceState::default());
383        check(
384            Either::Right(TestService {
385                state,
386                response: 20,
387            }),
388            20,
389        )
390        .await;
391    }
392
393    /// STATEMENT: Either branch binds an enclosed `ReadyBinding` before using its readiness scope.
394    ///
395    /// HOW:
396    /// - Place a bound service in each branch and construct an enclosing pipeline.
397    /// - Verify readiness and calls succeed without an unbound-dependency panic.
398    #[ntex::test]
399    async fn bound_service() {
400        for left in [true, false] {
401            let inner = ReadyBinding::new(TestService {
402                state: Rc::new(ServiceState::default()),
403                response: 10,
404            });
405            let service = if left {
406                Either::Left(inner)
407            } else {
408                Either::Right(inner)
409            };
410            let service = Pipeline::new((), service);
411            assert_eq!(service.ready().await, Ok(()));
412            assert_eq!(service.call(5).await, Ok(15));
413        }
414    }
415
416    /// STATEMENT: Branch-specific extraction returns `None` for the inactive `Either` branch.
417    ///
418    /// HOW:
419    /// - Call both extraction methods on left and right values and compare all four results.
420    #[test]
421    fn either_left_right() {
422        assert_eq!(Either::<u8, u8>::Left(1).left(), Some(1));
423        assert_eq!(Either::<u8, u8>::Left(1).right(), None);
424        assert_eq!(Either::<u8, u8>::Right(2).left(), None);
425        assert_eq!(Either::<u8, u8>::Right(2).right(), Some(2));
426    }
427
428    /// STATEMENT: Polling an `Either` future pin-projects to the active branch without
429    /// undefined behavior.
430    ///
431    /// HOW:
432    /// - Poll a `Left` ready `String` future with `Waker::noop` and check its output.
433    /// - Poll a `Right` future that is pending once, then check it returns its output.
434    #[test]
435    fn miri_either_polls_active_branch() {
436        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
437        let mut left = std::pin::pin!(Either::<_, future::Ready<String>>::Left(future::ready(
438            "l".to_string()
439        )));
440        assert_eq!(left.as_mut().poll(&mut cx), Poll::Ready("l".to_string()));
441
442        let mut pending = true;
443        let mut right = std::pin::pin!(Either::<future::Ready<String>, _>::Right(future::poll_fn(
444            move |_| if std::mem::take(&mut pending) {
445                Poll::Pending
446            } else {
447                Poll::Ready("r".to_string())
448            }
449        )));
450        assert!(right.as_mut().poll(&mut cx).is_pending());
451        assert_eq!(right.as_mut().poll(&mut cx), Poll::Ready("r".to_string()));
452    }
453}