actix_http/body/
either.rs

1use std::{
2    pin::Pin,
3    task::{Context, Poll},
4};
5
6use bytes::Bytes;
7use pin_project_lite::pin_project;
8
9use super::{BodySize, BoxBody, MessageBody};
10use crate::Error;
11
12pin_project! {
13    /// An "either" type specialized for body types.
14    ///
15    /// It is common, in middleware especially, to conditionally return an inner service's unknown/
16    /// generic body `B` type or return early with a new response. This type's "right" variant
17    /// defaults to `BoxBody` since error responses are the common case.
18    ///
19    /// For example, middleware will often have `type Response = ServiceResponse<EitherBody<B>>`.
20    /// This means that the inner service's response body type maps to the `Left` variant and the
21    /// middleware's own error responses use the default `Right` variant of `BoxBody`. Of course,
22    /// there's no reason it couldn't use `EitherBody<B, String>` instead if its alternative
23    /// responses have a known type.
24    #[project = EitherBodyProj]
25    #[derive(Debug, Clone)]
26    pub enum EitherBody<L, R = BoxBody> {
27        /// A body of type `L`.
28        Left { #[pin] body: L },
29
30        /// A body of type `R`.
31        Right { #[pin] body: R },
32    }
33}
34
35impl<L> EitherBody<L, BoxBody> {
36    /// Creates new `EitherBody` left variant with a boxed right variant.
37    ///
38    /// If the expected `R` type will be inferred and is not `BoxBody` then use the
39    /// [`left`](Self::left) constructor instead.
40    #[inline]
41    pub fn new(body: L) -> Self {
42        Self::Left { body }
43    }
44}
45
46impl<L, R> EitherBody<L, R> {
47    /// Creates new `EitherBody` using left variant.
48    #[inline]
49    pub fn left(body: L) -> Self {
50        Self::Left { body }
51    }
52
53    /// Creates new `EitherBody` using right variant.
54    #[inline]
55    pub fn right(body: R) -> Self {
56        Self::Right { body }
57    }
58}
59
60impl<L, R> MessageBody for EitherBody<L, R>
61where
62    L: MessageBody + 'static,
63    R: MessageBody + 'static,
64{
65    type Error = Error;
66
67    #[inline]
68    fn size(&self) -> BodySize {
69        match self {
70            EitherBody::Left { body } => body.size(),
71            EitherBody::Right { body } => body.size(),
72        }
73    }
74
75    #[inline]
76    fn poll_next(
77        self: Pin<&mut Self>,
78        cx: &mut Context<'_>,
79    ) -> Poll<Option<Result<Bytes, Self::Error>>> {
80        match self.project() {
81            EitherBodyProj::Left { body } => body
82                .poll_next(cx)
83                .map_err(|err| Error::new_body().with_cause(err)),
84            EitherBodyProj::Right { body } => body
85                .poll_next(cx)
86                .map_err(|err| Error::new_body().with_cause(err)),
87        }
88    }
89
90    #[inline]
91    fn try_into_bytes(self) -> Result<Bytes, Self> {
92        match self {
93            EitherBody::Left { body } => body
94                .try_into_bytes()
95                .map_err(|body| EitherBody::Left { body }),
96            EitherBody::Right { body } => body
97                .try_into_bytes()
98                .map_err(|body| EitherBody::Right { body }),
99        }
100    }
101
102    #[inline]
103    fn boxed(self) -> BoxBody {
104        match self {
105            EitherBody::Left { body } => body.boxed(),
106            EitherBody::Right { body } => body.boxed(),
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn type_parameter_inference() {
117        let _body: EitherBody<(), _> = EitherBody::new(());
118
119        let _body: EitherBody<_, ()> = EitherBody::left(());
120        let _body: EitherBody<(), _> = EitherBody::right(());
121    }
122}