1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use std::{
    borrow::Cow,
    error::Error as StdError,
    fmt, mem,
    pin::Pin,
    task::{Context, Poll},
};

use bytes::{Bytes, BytesMut};
use futures_core::Stream;
use pin_project::pin_project;

use crate::error::Error;

use super::{BodySize, BodyStream, MessageBody, MessageBodyMapErr, SizedStream};

#[deprecated(since = "4.0.0", note = "Renamed to `AnyBody`.")]
pub type Body = AnyBody;

/// Represents various types of HTTP message body.
#[pin_project(project = AnyBodyProj)]
#[derive(Clone)]
pub enum AnyBody<B = BoxBody> {
    /// Empty response. `Content-Length` header is not set.
    None,

    /// Complete, in-memory response body.
    Bytes(Bytes),

    /// Generic / Other message body.
    Body(#[pin] B),
}

impl AnyBody {
    /// Constructs a "body" representing an empty response.
    pub fn none() -> Self {
        Self::None
    }

    /// Constructs a new, 0-length body.
    pub fn empty() -> Self {
        Self::Bytes(Bytes::new())
    }

    /// Create boxed body from generic message body.
    pub fn new_boxed<B>(body: B) -> Self
    where
        B: MessageBody + 'static,
        B::Error: Into<Box<dyn StdError + 'static>>,
    {
        Self::Body(BoxBody::from_body(body))
    }

    /// Constructs new `AnyBody` instance from a slice of bytes by copying it.
    ///
    /// If your bytes container is owned, it may be cheaper to use a `From` impl.
    pub fn copy_from_slice(s: &[u8]) -> Self {
        Self::Bytes(Bytes::copy_from_slice(s))
    }

    #[doc(hidden)]
    #[deprecated(since = "4.0.0", note = "Renamed to `copy_from_slice`.")]
    pub fn from_slice(s: &[u8]) -> Self {
        Self::Bytes(Bytes::copy_from_slice(s))
    }
}

impl<B> AnyBody<B>
where
    B: MessageBody + 'static,
    B::Error: Into<Box<dyn StdError + 'static>>,
{
    /// Create body from generic message body.
    pub fn new(body: B) -> Self {
        Self::Body(body)
    }

    pub fn into_boxed(self) -> AnyBody {
        match self {
            Self::None => AnyBody::None,
            Self::Bytes(bytes) => AnyBody::Bytes(bytes),
            Self::Body(body) => AnyBody::new_boxed(body),
        }
    }
}

impl<B> MessageBody for AnyBody<B>
where
    B: MessageBody,
    B::Error: Into<Box<dyn StdError>> + 'static,
{
    type Error = Error;

    fn size(&self) -> BodySize {
        match self {
            AnyBody::None => BodySize::None,
            AnyBody::Bytes(ref bin) => BodySize::Sized(bin.len() as u64),
            AnyBody::Body(ref body) => body.size(),
        }
    }

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Bytes, Self::Error>>> {
        match self.project() {
            AnyBodyProj::None => Poll::Ready(None),
            AnyBodyProj::Bytes(bin) => {
                let len = bin.len();
                if len == 0 {
                    Poll::Ready(None)
                } else {
                    Poll::Ready(Some(Ok(mem::take(bin))))
                }
            }

            AnyBodyProj::Body(body) => body
                .poll_next(cx)
                .map_err(|err| Error::new_body().with_cause(err)),
        }
    }
}

impl PartialEq for AnyBody {
    fn eq(&self, other: &AnyBody) -> bool {
        match *self {
            AnyBody::None => matches!(*other, AnyBody::None),
            AnyBody::Bytes(ref b) => match *other {
                AnyBody::Bytes(ref b2) => b == b2,
                _ => false,
            },
            AnyBody::Body(_) => false,
        }
    }
}

impl<S: fmt::Debug> fmt::Debug for AnyBody<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            AnyBody::None => write!(f, "AnyBody::None"),
            AnyBody::Bytes(ref bytes) => write!(f, "AnyBody::Bytes({:?})", bytes),
            AnyBody::Body(ref stream) => write!(f, "AnyBody::Message({:?})", stream),
        }
    }
}

impl<B> From<&'static str> for AnyBody<B> {
    fn from(string: &'static str) -> Self {
        Self::Bytes(Bytes::from_static(string.as_ref()))
    }
}

impl<B> From<&'static [u8]> for AnyBody<B> {
    fn from(bytes: &'static [u8]) -> Self {
        Self::Bytes(Bytes::from_static(bytes))
    }
}

impl<B> From<Vec<u8>> for AnyBody<B> {
    fn from(vec: Vec<u8>) -> Self {
        Self::Bytes(Bytes::from(vec))
    }
}

impl<B> From<String> for AnyBody<B> {
    fn from(string: String) -> Self {
        Self::Bytes(Bytes::from(string))
    }
}

impl<B> From<&'_ String> for AnyBody<B> {
    fn from(string: &String) -> Self {
        Self::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&string)))
    }
}

impl<B> From<Cow<'_, str>> for AnyBody<B> {
    fn from(string: Cow<'_, str>) -> Self {
        match string {
            Cow::Owned(s) => Self::from(s),
            Cow::Borrowed(s) => {
                Self::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(s)))
            }
        }
    }
}

impl<B> From<Bytes> for AnyBody<B> {
    fn from(bytes: Bytes) -> Self {
        Self::Bytes(bytes)
    }
}

impl<B> From<BytesMut> for AnyBody<B> {
    fn from(bytes: BytesMut) -> Self {
        Self::Bytes(bytes.freeze())
    }
}

impl<S, E> From<SizedStream<S>> for AnyBody<SizedStream<S>>
where
    S: Stream<Item = Result<Bytes, E>> + 'static,
    E: Into<Box<dyn StdError>> + 'static,
{
    fn from(stream: SizedStream<S>) -> Self {
        AnyBody::new(stream)
    }
}

impl<S, E> From<SizedStream<S>> for AnyBody
where
    S: Stream<Item = Result<Bytes, E>> + 'static,
    E: Into<Box<dyn StdError>> + 'static,
{
    fn from(stream: SizedStream<S>) -> Self {
        AnyBody::new_boxed(stream)
    }
}

impl<S, E> From<BodyStream<S>> for AnyBody<BodyStream<S>>
where
    S: Stream<Item = Result<Bytes, E>> + 'static,
    E: Into<Box<dyn StdError>> + 'static,
{
    fn from(stream: BodyStream<S>) -> Self {
        AnyBody::new(stream)
    }
}

impl<S, E> From<BodyStream<S>> for AnyBody
where
    S: Stream<Item = Result<Bytes, E>> + 'static,
    E: Into<Box<dyn StdError>> + 'static,
{
    fn from(stream: BodyStream<S>) -> Self {
        AnyBody::new_boxed(stream)
    }
}

/// A boxed message body with boxed errors.
pub struct BoxBody(Pin<Box<dyn MessageBody<Error = Box<dyn StdError>>>>);

impl BoxBody {
    /// Boxes a `MessageBody` and any errors it generates.
    pub fn from_body<B>(body: B) -> Self
    where
        B: MessageBody + 'static,
        B::Error: Into<Box<dyn StdError + 'static>>,
    {
        let body = MessageBodyMapErr::new(body, Into::into);
        Self(Box::pin(body))
    }

    /// Returns a mutable pinned reference to the inner message body type.
    pub fn as_pin_mut(
        &mut self,
    ) -> Pin<&mut (dyn MessageBody<Error = Box<dyn StdError>>)> {
        self.0.as_mut()
    }
}

impl fmt::Debug for BoxBody {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("BoxAnyBody(dyn MessageBody)")
    }
}

impl MessageBody for BoxBody {
    type Error = Error;

    fn size(&self) -> BodySize {
        self.0.size()
    }

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Bytes, Self::Error>>> {
        self.0
            .as_mut()
            .poll_next(cx)
            .map_err(|err| Error::new_body().with_cause(err))
    }
}

#[cfg(test)]
mod tests {
    use std::marker::PhantomPinned;

    use static_assertions::{assert_impl_all, assert_not_impl_all};

    use super::*;
    use crate::body::to_bytes;

    struct PinType(PhantomPinned);

    impl MessageBody for PinType {
        type Error = crate::Error;

        fn size(&self) -> BodySize {
            unimplemented!()
        }

        fn poll_next(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Option<Result<Bytes, Self::Error>>> {
            unimplemented!()
        }
    }

    assert_impl_all!(AnyBody<()>: MessageBody, fmt::Debug, Send, Sync, Unpin);
    assert_impl_all!(AnyBody<AnyBody<()>>: MessageBody, fmt::Debug, Send, Sync, Unpin);
    assert_impl_all!(AnyBody<Bytes>: MessageBody, fmt::Debug, Send, Sync, Unpin);
    assert_impl_all!(AnyBody: MessageBody, fmt::Debug, Unpin);
    assert_impl_all!(BoxBody: MessageBody, fmt::Debug, Unpin);
    assert_impl_all!(AnyBody<PinType>: MessageBody);

    assert_not_impl_all!(AnyBody: Send, Sync, Unpin);
    assert_not_impl_all!(BoxBody: Send, Sync, Unpin);
    assert_not_impl_all!(AnyBody<PinType>: Send, Sync, Unpin);

    #[actix_rt::test]
    async fn nested_boxed_body() {
        let body = AnyBody::copy_from_slice(&[1, 2, 3]);
        let boxed_body = BoxBody::from_body(BoxBody::from_body(body));

        assert_eq!(
            to_bytes(boxed_body).await.unwrap(),
            Bytes::from(vec![1, 2, 3]),
        );
    }
}