Skip to main content

ntex_http/
body.rs

1//! Traits and structures to aid consuming and writing HTTP payloads.
2use std::{error::Error, fmt, marker, mem, pin::Pin, rc::Rc, task::Context, task::Poll};
3
4use futures_core::Stream;
5use ntex_bytes::{BytePages, Bytes, BytesMut};
6
7#[derive(Debug, PartialEq, Eq, Copy, Clone)]
8/// Size information used when encoding an HTTP message body.
9pub enum BodySize {
10    /// No body is present and no `Content-Length` header should be emitted.
11    ///
12    /// An HTTP/1 response that may carry a body is still sent with
13    /// `Content-Length: 0`, otherwise its end could not be determined.
14    None,
15    /// An empty body with a `Content-Length: 0` header.
16    Empty,
17    /// A body with a known byte length.
18    Sized(u64),
19    /// A streaming body with an unknown final length.
20    Stream,
21}
22
23impl BodySize {
24    /// Returns `true` if this size represents no payload bytes.
25    pub fn is_eof(&self) -> bool {
26        matches!(self, BodySize::None | BodySize::Empty | BodySize::Sized(0))
27    }
28}
29
30/// Interface for types that can be streamed to a peer.
31pub trait MessageBody: 'static {
32    /// Returns the body size hint.
33    fn size(&self) -> BodySize;
34
35    /// Polls the next body chunk.
36    fn poll_next_chunk(
37        &mut self,
38        cx: &mut Context<'_>,
39    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>>;
40}
41
42impl MessageBody for () {
43    #[inline]
44    fn size(&self) -> BodySize {
45        BodySize::Empty
46    }
47
48    #[inline]
49    fn poll_next_chunk(
50        &mut self,
51        _: &mut Context<'_>,
52    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
53        Poll::Ready(None)
54    }
55}
56
57impl<T: MessageBody> MessageBody for Box<T> {
58    #[inline]
59    fn size(&self) -> BodySize {
60        self.as_ref().size()
61    }
62
63    #[inline]
64    fn poll_next_chunk(
65        &mut self,
66        cx: &mut Context<'_>,
67    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
68        self.as_mut().poll_next_chunk(cx)
69    }
70}
71
72#[derive(Debug)]
73/// Response body preserving either a concrete body type or a type-erased body.
74pub enum ResponseBody<B> {
75    /// The original concrete body.
76    Body(B),
77    /// A type-erased body.
78    Other(Body),
79}
80
81impl ResponseBody<Body> {
82    /// Converts a type-erased response body to another concrete response type.
83    pub fn into_body<B>(self) -> ResponseBody<B> {
84        match self {
85            ResponseBody::Body(b) | ResponseBody::Other(b) => ResponseBody::Other(b),
86        }
87    }
88}
89
90impl From<ResponseBody<Body>> for Body {
91    fn from(b: ResponseBody<Body>) -> Self {
92        match b {
93            ResponseBody::Body(b) | ResponseBody::Other(b) => b,
94        }
95    }
96}
97
98impl<B> From<Body> for ResponseBody<B> {
99    fn from(b: Body) -> Self {
100        ResponseBody::Other(b)
101    }
102}
103
104impl<B> ResponseBody<B> {
105    #[inline]
106    /// Creates a response body from a concrete body value.
107    pub fn new(body: B) -> Self {
108        ResponseBody::Body(body)
109    }
110
111    #[inline]
112    #[must_use]
113    /// Replaces this response body with [`Body::None`] and returns the original.
114    pub fn take_body(&mut self) -> ResponseBody<B> {
115        std::mem::replace(self, ResponseBody::Other(Body::None))
116    }
117}
118
119impl<B: MessageBody> ResponseBody<B> {
120    /// Returns the concrete body, if this is [`ResponseBody::Body`].
121    pub fn as_ref(&self) -> Option<&B> {
122        if let ResponseBody::Body(b) = self {
123            Some(b)
124        } else {
125            None
126        }
127    }
128}
129
130impl<B: MessageBody> MessageBody for ResponseBody<B> {
131    #[inline]
132    fn size(&self) -> BodySize {
133        match self {
134            ResponseBody::Body(body) => body.size(),
135            ResponseBody::Other(body) => body.size(),
136        }
137    }
138
139    #[inline]
140    fn poll_next_chunk(
141        &mut self,
142        cx: &mut Context<'_>,
143    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
144        match self {
145            ResponseBody::Body(body) => body.poll_next_chunk(cx),
146            ResponseBody::Other(body) => body.poll_next_chunk(cx),
147        }
148    }
149}
150
151impl<B: MessageBody + Unpin> Stream for ResponseBody<B> {
152    type Item = Result<Bytes, Rc<dyn Error>>;
153
154    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
155        match self.get_mut() {
156            ResponseBody::Body(body) => body.poll_next_chunk(cx),
157            ResponseBody::Other(body) => body.poll_next_chunk(cx),
158        }
159    }
160}
161
162/// Type-erased HTTP message body.
163pub enum Body {
164    /// Empty response. `Content-Length` header is not set.
165    ///
166    /// See [`BodySize::None`].
167    None,
168    /// Zero sized response body. `Content-Length` header is set to `0`.
169    Empty,
170    /// Specific response body.
171    Bytes(Bytes),
172    /// Generic message body.
173    Message(Box<dyn MessageBody>),
174}
175
176impl Body {
177    /// Creates a body by copying a byte slice.
178    pub fn from_slice(s: &[u8]) -> Body {
179        Body::Bytes(Bytes::copy_from_slice(s))
180    }
181
182    /// Creates a body from a streaming message body.
183    pub fn from_message<B: MessageBody>(body: B) -> Body {
184        Body::Message(Box::new(body))
185    }
186}
187
188impl MessageBody for Body {
189    #[inline]
190    fn size(&self) -> BodySize {
191        match self {
192            Body::None => BodySize::None,
193            Body::Empty => BodySize::Empty,
194            Body::Bytes(bin) => BodySize::Sized(bin.len() as u64),
195            Body::Message(body) => body.size(),
196        }
197    }
198
199    fn poll_next_chunk(
200        &mut self,
201        cx: &mut Context<'_>,
202    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
203        match self {
204            Body::None | Body::Empty => Poll::Ready(None),
205            Body::Bytes(bin) => {
206                let len = bin.len();
207                if len == 0 {
208                    Poll::Ready(None)
209                } else {
210                    Poll::Ready(Some(Ok(mem::take(bin))))
211                }
212            }
213            Body::Message(body) => body.poll_next_chunk(cx),
214        }
215    }
216}
217
218impl PartialEq for Body {
219    fn eq(&self, other: &Body) -> bool {
220        match (self, other) {
221            (Body::None, Body::None) | (Body::Empty, Body::Empty) => true,
222            (Body::Bytes(b), Body::Bytes(b2)) => b == b2,
223            _ => false,
224        }
225    }
226}
227
228impl fmt::Debug for Body {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        match *self {
231            Body::None => write!(f, "Body::None"),
232            Body::Empty => write!(f, "Body::Empty"),
233            Body::Bytes(ref b) => write!(f, "Body::Bytes({b:?})"),
234            Body::Message(_) => write!(f, "Body::Message(_)"),
235        }
236    }
237}
238
239impl From<&'static str> for Body {
240    fn from(s: &'static str) -> Body {
241        Body::Bytes(Bytes::from_static(s.as_ref()))
242    }
243}
244
245impl From<&'static [u8]> for Body {
246    fn from(s: &'static [u8]) -> Body {
247        Body::Bytes(Bytes::from_static(s))
248    }
249}
250
251impl From<Vec<u8>> for Body {
252    fn from(vec: Vec<u8>) -> Body {
253        Body::Bytes(Bytes::from(vec))
254    }
255}
256
257impl From<String> for Body {
258    fn from(s: String) -> Body {
259        s.into_bytes().into()
260    }
261}
262
263impl<'a> From<&'a String> for Body {
264    fn from(s: &'a String) -> Body {
265        Body::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&s)))
266    }
267}
268
269impl From<Bytes> for Body {
270    fn from(s: Bytes) -> Body {
271        Body::Bytes(s)
272    }
273}
274
275impl From<BytesMut> for Body {
276    fn from(s: BytesMut) -> Body {
277        Body::Bytes(s.freeze())
278    }
279}
280
281impl From<BytePages> for Body {
282    fn from(pages: BytePages) -> Body {
283        Body::from_message(pages)
284    }
285}
286
287impl<S> From<SizedStream<S>> for Body
288where
289    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin + 'static,
290{
291    fn from(s: SizedStream<S>) -> Body {
292        Body::from_message(s)
293    }
294}
295
296impl<S, E> From<BodyStream<S, E>> for Body
297where
298    S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
299    E: Error + 'static,
300{
301    fn from(s: BodyStream<S, E>) -> Body {
302        Body::from_message(s)
303    }
304}
305
306impl<S> From<BoxedBodyStream<S>> for Body
307where
308    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin + 'static,
309{
310    fn from(s: BoxedBodyStream<S>) -> Body {
311        Body::from_message(s)
312    }
313}
314
315impl MessageBody for Bytes {
316    fn size(&self) -> BodySize {
317        BodySize::Sized(self.len() as u64)
318    }
319
320    fn poll_next_chunk(
321        &mut self,
322        _: &mut Context<'_>,
323    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
324        if self.is_empty() {
325            Poll::Ready(None)
326        } else {
327            Poll::Ready(Some(Ok(mem::take(self))))
328        }
329    }
330}
331
332impl MessageBody for BytesMut {
333    fn size(&self) -> BodySize {
334        BodySize::Sized(self.len() as u64)
335    }
336
337    fn poll_next_chunk(
338        &mut self,
339        _: &mut Context<'_>,
340    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
341        if self.is_empty() {
342            Poll::Ready(None)
343        } else {
344            Poll::Ready(Some(Ok(mem::take(self).freeze())))
345        }
346    }
347}
348
349impl MessageBody for BytePages {
350    fn size(&self) -> BodySize {
351        BodySize::Sized(self.len() as u64)
352    }
353
354    fn poll_next_chunk(
355        &mut self,
356        _: &mut Context<'_>,
357    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
358        if let Some(page) = self.take() {
359            Poll::Ready(Some(Ok(page.freeze())))
360        } else {
361            Poll::Ready(None)
362        }
363    }
364}
365
366impl MessageBody for &'static str {
367    fn size(&self) -> BodySize {
368        BodySize::Sized(self.len() as u64)
369    }
370
371    fn poll_next_chunk(
372        &mut self,
373        _: &mut Context<'_>,
374    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
375        if self.is_empty() {
376            Poll::Ready(None)
377        } else {
378            Poll::Ready(Some(Ok(Bytes::from_static(mem::take(self).as_ref()))))
379        }
380    }
381}
382
383impl MessageBody for &'static [u8] {
384    fn size(&self) -> BodySize {
385        BodySize::Sized(self.len() as u64)
386    }
387
388    fn poll_next_chunk(
389        &mut self,
390        _: &mut Context<'_>,
391    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
392        if self.is_empty() {
393            Poll::Ready(None)
394        } else {
395            Poll::Ready(Some(Ok(Bytes::from_static(mem::take(self)))))
396        }
397    }
398}
399
400impl MessageBody for Vec<u8> {
401    fn size(&self) -> BodySize {
402        BodySize::Sized(self.len() as u64)
403    }
404
405    fn poll_next_chunk(
406        &mut self,
407        _: &mut Context<'_>,
408    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
409        if self.is_empty() {
410            Poll::Ready(None)
411        } else {
412            Poll::Ready(Some(Ok(Bytes::from(mem::take(self)))))
413        }
414    }
415}
416
417impl MessageBody for String {
418    fn size(&self) -> BodySize {
419        BodySize::Sized(self.len() as u64)
420    }
421
422    fn poll_next_chunk(
423        &mut self,
424        _: &mut Context<'_>,
425    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
426        if self.is_empty() {
427            Poll::Ready(None)
428        } else {
429            Poll::Ready(Some(Ok(Bytes::from(mem::take(self).into_bytes()))))
430        }
431    }
432}
433
434/// Type represent streaming body.
435///
436/// Response does not contain `content-length` header and appropriate transfer encoding is used.
437pub struct BodyStream<S, E> {
438    stream: S,
439    _t: marker::PhantomData<E>,
440}
441
442impl<S, E> BodyStream<S, E>
443where
444    S: Stream<Item = Result<Bytes, E>> + Unpin,
445    E: Error,
446{
447    pub fn new(stream: S) -> Self {
448        BodyStream {
449            stream,
450            _t: marker::PhantomData,
451        }
452    }
453}
454
455impl<S, E> fmt::Debug for BodyStream<S, E> {
456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457        f.debug_struct("BodyStream")
458            .field("stream", &std::any::type_name::<S>())
459            .field("error", &std::any::type_name::<E>())
460            .finish()
461    }
462}
463
464impl<S, E> MessageBody for BodyStream<S, E>
465where
466    S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
467    E: Error + 'static,
468{
469    fn size(&self) -> BodySize {
470        BodySize::Stream
471    }
472
473    /// Attempts to pull out the next value of the underlying [`Stream`].
474    ///
475    /// Empty values are skipped to prevent [`BodyStream`]'s transmission being
476    /// ended on a zero-length chunk, but rather proceed until the underlying
477    /// [`Stream`] ends.
478    fn poll_next_chunk(
479        &mut self,
480        cx: &mut Context<'_>,
481    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
482        loop {
483            return Poll::Ready(match Pin::new(&mut self.stream).poll_next(cx) {
484                Poll::Ready(Some(Ok(ref bytes))) if bytes.is_empty() => continue,
485                Poll::Ready(opt) => opt.map(|res| {
486                    res.map_err(|e| {
487                        let e: Rc<dyn Error> = Rc::new(e);
488                        e
489                    })
490                }),
491                Poll::Pending => return Poll::Pending,
492            });
493        }
494    }
495}
496
497/// Type represent streaming body.
498/// Response does not contain `content-length` header and appropriate transfer encoding is used.
499pub struct BoxedBodyStream<S> {
500    stream: S,
501}
502
503impl<S> BoxedBodyStream<S>
504where
505    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin,
506{
507    pub fn new(stream: S) -> Self {
508        BoxedBodyStream { stream }
509    }
510}
511
512impl<S> fmt::Debug for BoxedBodyStream<S> {
513    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514        f.debug_struct("BoxedBodyStream")
515            .field("stream", &std::any::type_name::<S>())
516            .finish()
517    }
518}
519
520impl<S> MessageBody for BoxedBodyStream<S>
521where
522    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin + 'static,
523{
524    fn size(&self) -> BodySize {
525        BodySize::Stream
526    }
527
528    /// Attempts to pull out the next value of the underlying [`Stream`].
529    ///
530    /// Empty values are skipped to prevent [`BodyStream`]'s transmission being
531    /// ended on a zero-length chunk, but rather proceed until the underlying
532    /// [`Stream`] ends.
533    fn poll_next_chunk(
534        &mut self,
535        cx: &mut Context<'_>,
536    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
537        loop {
538            return Poll::Ready(match Pin::new(&mut self.stream).poll_next(cx) {
539                Poll::Ready(Some(Ok(ref bytes))) if bytes.is_empty() => continue,
540                Poll::Ready(opt) => opt,
541                Poll::Pending => return Poll::Pending,
542            });
543        }
544    }
545}
546
547/// Type represent streaming body. This body implementation should be used
548/// if total size of stream is known. Data get sent as is without using transfer encoding.
549pub struct SizedStream<S> {
550    size: u64,
551    stream: S,
552}
553
554impl<S> SizedStream<S>
555where
556    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin,
557{
558    pub fn new(size: u64, stream: S) -> Self {
559        SizedStream { size, stream }
560    }
561}
562
563impl<S> fmt::Debug for SizedStream<S> {
564    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
565        f.debug_struct("SizedStream")
566            .field("size", &self.size)
567            .field("stream", &std::any::type_name::<S>())
568            .finish()
569    }
570}
571
572impl<S> MessageBody for SizedStream<S>
573where
574    S: Stream<Item = Result<Bytes, Rc<dyn Error>>> + Unpin + 'static,
575{
576    fn size(&self) -> BodySize {
577        BodySize::Sized(self.size)
578    }
579
580    /// Attempts to pull out the next value of the underlying [`Stream`].
581    ///
582    /// Empty values are skipped to prevent [`SizedStream`]'s transmission being
583    /// ended on a zero-length chunk, but rather proceed until the underlying
584    /// [`Stream`] ends.
585    fn poll_next_chunk(
586        &mut self,
587        cx: &mut Context<'_>,
588    ) -> Poll<Option<Result<Bytes, Rc<dyn Error>>>> {
589        loop {
590            return Poll::Ready(match Pin::new(&mut self.stream).poll_next(cx) {
591                Poll::Ready(Some(Ok(ref bytes))) if bytes.is_empty() => continue,
592                Poll::Ready(val) => val,
593                Poll::Pending => return Poll::Pending,
594            });
595        }
596    }
597}
598
599#[cfg(test)]
600mod tests {
601    use std::{future::poll_fn, future::ready, io};
602
603    use futures_util::stream;
604    use ntex::util::BufMut;
605
606    use super::*;
607
608    impl Body {
609        pub(crate) fn get_ref(&self) -> &[u8] {
610            if let Body::Bytes(bin) = self { bin } else { panic!() }
611        }
612    }
613
614    /// STATEMENT: `Body` and `ResponseBody` keep their expected sizes.
615    ///
616    /// HOW:
617    /// - Check `size_of` for `Body`, `ResponseBody<Bytes>` and `ResponseBody<Body>`.
618    /// - Expect 32, 32 and 40 bytes, so a layout regression fails here.
619    #[ntex::test]
620    async fn test_size() {
621        assert_eq!(32, std::mem::size_of::<Body>());
622        assert_eq!(32, std::mem::size_of::<ResponseBody<Bytes>>());
623        assert_eq!(40, std::mem::size_of::<ResponseBody<Body>>());
624    }
625
626    /// STATEMENT: A `&'static str` body reports its length and yields its bytes once, and an
627    /// empty string yields no chunk.
628    ///
629    /// HOW:
630    /// - Check `Body::from(&str)` size and `get_ref` for empty and `test`.
631    /// - Poll fresh `"test"` values; expect a `test` chunk each time.
632    /// - Poll `""`; expect end of stream.
633    #[ntex::test]
634    async fn test_static_str() {
635        assert_eq!(Body::from("").size(), BodySize::Sized(0));
636        assert_eq!(Body::from("test").size(), BodySize::Sized(4));
637        assert_eq!(Body::from("test").get_ref(), b"test");
638
639        assert_eq!("test".size(), BodySize::Sized(4));
640        assert_eq!(
641            poll_fn(|cx| "test".poll_next_chunk(cx)).await.unwrap().ok(),
642            Some(Bytes::from("test"))
643        );
644        assert_eq!(
645            poll_fn(|cx| "test".poll_next_chunk(cx)).await.unwrap().ok(),
646            Some(Bytes::from("test"))
647        );
648        assert!(poll_fn(|cx| "".poll_next_chunk(cx)).await.is_none());
649    }
650
651    /// STATEMENT: A `Body` built from `BytePages` reports the total size and yields all pages as
652    /// one chunk.
653    ///
654    /// HOW:
655    /// - Fill pages with `put_slice` and two `append` calls (12 bytes).
656    /// - Expect `BodySize::Sized(12)`, one `111122223333` chunk, then end of stream.
657    #[ntex::test]
658    async fn test_pages() {
659        let mut pages = BytePages::default();
660        pages.put_slice(b"1111");
661        pages.append(Bytes::from("2222"));
662        pages.append(Bytes::from("3333"));
663
664        let mut body = Body::from(pages);
665        assert_eq!(body.size(), BodySize::Sized(12));
666        assert_eq!(
667            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
668            Some(Bytes::from("111122223333"))
669        );
670        assert!(poll_fn(|cx| body.poll_next_chunk(cx)).await.is_none());
671    }
672
673    /// STATEMENT: `&'static [u8]` bodies, via `From` and `from_slice`, report their length and
674    /// yield their bytes, and an empty slice yields no chunk.
675    ///
676    /// HOW:
677    /// - Check size and `get_ref` for `Body::from` and `Body::from_slice`.
678    /// - Poll a `&[u8]` directly; expect a `test` chunk.
679    /// - Poll an empty slice; expect end of stream.
680    #[ntex::test]
681    async fn test_static_bytes() {
682        assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4));
683        assert_eq!(Body::from(b"test".as_ref()).get_ref(), b"test");
684        assert_eq!(
685            Body::from_slice(b"test".as_ref()).size(),
686            BodySize::Sized(4)
687        );
688        assert_eq!(Body::from_slice(b"test".as_ref()).get_ref(), b"test");
689
690        assert_eq!((&b"test"[..]).size(), BodySize::Sized(4));
691        assert_eq!(
692            poll_fn(|cx| (&b"test"[..]).poll_next_chunk(cx))
693                .await
694                .unwrap()
695                .ok(),
696            Some(Bytes::from("test"))
697        );
698        assert_eq!((&b"test"[..]).size(), BodySize::Sized(4));
699        assert!(poll_fn(|cx| (&b""[..]).poll_next_chunk(cx)).await.is_none());
700    }
701
702    /// STATEMENT: `Vec<u8>` bodies report their length and yield their bytes, and an empty
703    /// vector yields no chunk.
704    ///
705    /// HOW:
706    /// - Check `Body::from(Vec)` size and `get_ref`.
707    /// - Poll fresh vectors; expect a `test` chunk each time.
708    /// - Poll an empty vector; expect end of stream.
709    #[ntex::test]
710    async fn test_vec() {
711        assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4));
712        assert_eq!(Body::from(Vec::from("test")).get_ref(), b"test");
713
714        assert_eq!(Vec::from("test").size(), BodySize::Sized(4));
715        assert_eq!(
716            poll_fn(|cx| Vec::from("test").poll_next_chunk(cx))
717                .await
718                .unwrap()
719                .ok(),
720            Some(Bytes::from("test"))
721        );
722        assert_eq!(
723            poll_fn(|cx| Vec::from("test").poll_next_chunk(cx))
724                .await
725                .unwrap()
726                .ok(),
727            Some(Bytes::from("test"))
728        );
729        assert!(
730            poll_fn(|cx| Vec::<u8>::new().poll_next_chunk(cx))
731                .await
732                .is_none()
733        );
734    }
735
736    /// STATEMENT: A `Bytes` body yields its content once and then ends.
737    ///
738    /// HOW:
739    /// - Check `Body::from(Bytes)` size and `get_ref`.
740    /// - Poll the same `Bytes` twice; expect `test`, then end of stream.
741    #[ntex::test]
742    async fn test_bytes() {
743        let mut b = Bytes::from("test");
744        assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
745        assert_eq!(Body::from(b.clone()).get_ref(), b"test");
746
747        assert_eq!(b.size(), BodySize::Sized(4));
748        assert_eq!(
749            poll_fn(|cx| b.poll_next_chunk(cx)).await.unwrap().ok(),
750            Some(Bytes::from("test"))
751        );
752        assert!(poll_fn(|cx| b.poll_next_chunk(cx)).await.is_none(),);
753    }
754
755    /// STATEMENT: A `BytesMut` body yields its content once, after which its size is zero.
756    ///
757    /// HOW:
758    /// - Poll `Body::from(BytesMut)` twice; expect `test`, then end of stream.
759    /// - Poll a `BytesMut` directly; expect `test`, `BodySize::Sized(0)`, then end of stream.
760    #[ntex::test]
761    async fn test_bytes_mut() {
762        let mut b = Body::from(BytesMut::from("test"));
763        assert_eq!(b.size(), BodySize::Sized(4));
764        assert_eq!(b.get_ref(), b"test");
765        assert_eq!(
766            poll_fn(|cx| b.poll_next_chunk(cx)).await.unwrap().ok(),
767            Some(Bytes::from("test"))
768        );
769        assert!(poll_fn(|cx| b.poll_next_chunk(cx)).await.is_none(),);
770
771        let mut b = BytesMut::from("test");
772        assert_eq!(b.size(), BodySize::Sized(4));
773        assert_eq!(
774            poll_fn(|cx| b.poll_next_chunk(cx)).await.unwrap().ok(),
775            Some(Bytes::from("test"))
776        );
777        assert_eq!(b.size(), BodySize::Sized(0));
778        assert!(poll_fn(|cx| b.poll_next_chunk(cx)).await.is_none(),);
779    }
780
781    /// STATEMENT: `String` and `&String` bodies report their length, and a `String` yields its
782    /// content once.
783    ///
784    /// HOW:
785    /// - Check size and `get_ref` for `Body::from(String)` and `Body::from(&String)`.
786    /// - Poll the same `String` twice; expect `test`, then end of stream.
787    #[ntex::test]
788    async fn test_string() {
789        let mut b = "test".to_owned();
790        assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
791        assert_eq!(Body::from(b.clone()).get_ref(), b"test");
792        assert_eq!(Body::from(&b).size(), BodySize::Sized(4));
793        assert_eq!(Body::from(&b).get_ref(), b"test");
794
795        assert_eq!(b.size(), BodySize::Sized(4));
796        assert_eq!(
797            poll_fn(|cx| b.poll_next_chunk(cx)).await.unwrap().ok(),
798            Some(Bytes::from("test"))
799        );
800        assert!(poll_fn(|cx| b.poll_next_chunk(cx)).await.is_none(),);
801    }
802
803    /// STATEMENT: `()` is an empty body.
804    ///
805    /// HOW:
806    /// - Expect `BodySize::Empty` and end of stream on the first poll.
807    #[ntex::test]
808    async fn test_unit() {
809        assert_eq!(().size(), BodySize::Empty);
810        assert!(poll_fn(|cx| ().poll_next_chunk(cx)).await.is_none());
811    }
812
813    /// STATEMENT: `Box<B>` forwards `size` and `poll_next_chunk` to the boxed body.
814    ///
815    /// HOW:
816    /// - Box a `()` body.
817    /// - Expect `BodySize::Empty` and end of stream on the first poll.
818    #[ntex::test]
819    async fn test_box() {
820        let mut val = Box::new(());
821        assert_eq!(val.size(), BodySize::Empty);
822        assert!(poll_fn(|cx| val.poll_next_chunk(cx)).await.is_none());
823    }
824
825    /// STATEMENT: `Body` equality matches `None`, `Empty` and equal `Bytes`, and nothing else.
826    ///
827    /// HOW:
828    /// - Compare `None`, `Empty` and `Bytes` bodies with themselves and each other.
829    /// - Expect equal only for the same variant with the same bytes.
830    #[ntex::test]
831    #[allow(clippy::eq_op)]
832    async fn test_body_eq() {
833        assert_eq!(Body::None, Body::None);
834        assert_ne!(Body::None, Body::Empty);
835        assert_eq!(Body::Empty, Body::Empty);
836        assert_ne!(Body::Empty, Body::None);
837        assert_eq!(
838            Body::Bytes(Bytes::from_static(b"1")),
839            Body::Bytes(Bytes::from_static(b"1"))
840        );
841        assert_ne!(Body::Bytes(Bytes::from_static(b"1")), Body::None);
842    }
843
844    /// STATEMENT: `Body` `Debug` names the variant and shows byte content.
845    ///
846    /// HOW:
847    /// - Format `None`, `Empty` and `Bytes(1)`.
848    /// - Expect `Body::None`, `Body::Empty` and the byte value in the output.
849    #[ntex::test]
850    async fn test_body_debug() {
851        assert!(format!("{:?}", Body::None).contains("Body::None"));
852        assert!(format!("{:?}", Body::Empty).contains("Body::Empty"));
853        assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains('1'));
854    }
855
856    /// STATEMENT: A `BodyStream` converts into a `Body::Message` that is not equal to
857    /// `Body::None` and can be wrapped in `ResponseBody`.
858    ///
859    /// HOW:
860    /// - Wrap a one-item stream in `BodyStream`; check its `Debug` output.
861    /// - Convert to `Body`; expect `Body::Message(_)` in `Debug` and inequality with `None`.
862    /// - Wrap in `ResponseBody`; expect `as_ref()` to return the body.
863    #[ntex::test]
864    async fn body_stream() {
865        let st = BodyStream::new(stream::once(ready(Ok::<_, io::Error>(Bytes::from("1")))));
866        assert!(format!("{st:?}").contains("BodyStream"));
867        let body: Body = st.into();
868        assert!(format!("{body:?}").contains("Body::Message(_)"));
869        assert_ne!(body, Body::None);
870
871        let res = ResponseBody::new(body);
872        assert!(res.as_ref().is_some());
873    }
874
875    /// STATEMENT: A `BoxedBodyStream` converts into a `Body::Message` that is not equal to
876    /// `Body::None` and can be wrapped in `ResponseBody`.
877    ///
878    /// HOW:
879    /// - Wrap a one-item stream in `BoxedBodyStream`; check its `Debug` output.
880    /// - Convert to `Body`; expect `Body::Message(_)` in `Debug` and inequality with `None`.
881    /// - Wrap in `ResponseBody`; expect `as_ref()` to return the body.
882    #[ntex::test]
883    async fn boxed_body_stream() {
884        let st = BoxedBodyStream::new(stream::once(ready(Ok::<_, Rc<dyn Error>>(Bytes::from(
885            "1",
886        )))));
887        assert!(format!("{st:?}").contains("BoxedBodyStream"));
888        let body: Body = st.into();
889        assert!(format!("{body:?}").contains("Body::Message(_)"));
890        assert_ne!(body, Body::None);
891
892        let res = ResponseBody::new(body);
893        assert!(res.as_ref().is_some());
894    }
895
896    /// STATEMENT: `BodyStream` skips empty chunks from the inner stream.
897    ///
898    /// HOW:
899    /// - Stream `1`, an empty chunk and `2`.
900    /// - Expect the first two polls to return `1` and `2`.
901    #[ntex::test]
902    async fn body_skips_empty_chunks() {
903        let mut body = BodyStream::new(stream::iter(
904            ["1", "", "2"]
905                .iter()
906                .map(|&v| Ok(Bytes::from(v)) as Result<Bytes, io::Error>),
907        ));
908        assert_eq!(
909            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
910            Some(Bytes::from("1")),
911        );
912        assert_eq!(
913            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
914            Some(Bytes::from("2")),
915        );
916    }
917
918    /// STATEMENT: `SizedStream` skips empty chunks from the inner stream.
919    ///
920    /// HOW:
921    /// - Stream `1`, an empty chunk and `2` with a declared size of 2.
922    /// - Expect the first two polls to return `1` and `2`.
923    #[ntex::test]
924    async fn sized_skips_empty_chunks() {
925        let mut body = SizedStream::new(
926            2,
927            stream::iter(["1", "", "2"].iter().map(|&v| Ok(Bytes::from(v)))),
928        );
929        assert!(format!("{body:?}").contains("SizedStream"));
930        assert_eq!(
931            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
932            Some(Bytes::from("1")),
933        );
934        assert_eq!(
935            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
936            Some(Bytes::from("2")),
937        );
938    }
939
940    /// STATEMENT: `BoxedBodyStream` skips empty chunks from the inner stream.
941    ///
942    /// HOW:
943    /// - Stream `1`, an empty chunk and `2`.
944    /// - Expect `1`, `2`, then end of stream.
945    #[ntex::test]
946    async fn boxed_body_skips_empty_chunks() {
947        let mut body = BoxedBodyStream::new(stream::iter(
948            ["1", "", "2"]
949                .iter()
950                .map(|&v| Ok(Bytes::from(v)) as Result<Bytes, Rc<dyn Error>>),
951        ));
952        assert_eq!(
953            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
954            Some(Bytes::from("1")),
955        );
956        assert_eq!(
957            poll_fn(|cx| body.poll_next_chunk(cx)).await.unwrap().ok(),
958            Some(Bytes::from("2")),
959        );
960        assert!(poll_fn(|cx| body.poll_next_chunk(cx)).await.is_none());
961    }
962}