actix_http/body/
either.rs1use 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    #[project = EitherBodyProj]
25    #[derive(Debug, Clone)]
26    pub enum EitherBody<L, R = BoxBody> {
27        Left { #[pin] body: L },
29
30        Right { #[pin] body: R },
32    }
33}
34
35impl<L> EitherBody<L, BoxBody> {
36    #[inline]
41    pub fn new(body: L) -> Self {
42        Self::Left { body }
43    }
44}
45
46impl<L, R> EitherBody<L, R> {
47    #[inline]
49    pub fn left(body: L) -> Self {
50        Self::Left { body }
51    }
52
53    #[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}