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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use futures_lite::{io, prelude::*, ready};
use serde::{de::DeserializeOwned, Serialize};

use std::fmt::{self, Debug};
use std::pin::Pin;
use std::task::{Context, Poll};

use crate::{mime, Mime};
use crate::{Status, StatusCode};

pin_project_lite::pin_project! {
    /// A streaming HTTP body.
    ///
    /// `Body` represents the HTTP body of both `Request` and `Response`. It's completely
    /// streaming, and implements `AsyncBufRead` to make reading from it both convenient and
    /// performant.
    ///
    /// Both `Request` and `Response` take `Body` by `Into<Body>`, which means that passing string
    /// literals, byte vectors, but also concrete `Body` instances are all valid. This makes it
    /// easy to create both quick HTTP requests, but also have fine grained control over how bodies
    /// are streamed out.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, Response, StatusCode};
    /// use async_std::io::Cursor;
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    /// req.set_body("Hello Chashu");
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    /// let cursor = Cursor::new("Hello Nori");
    /// let body = Body::from_reader(cursor, Some(10)); // set the body length
    /// req.set_body(body);
    /// ```
    ///
    /// # Length
    ///
    /// One of the details of `Body` to be aware of is the `length` parameter. The value of
    /// `length` is used by HTTP implementations to determine how to treat the stream. If a length
    /// is known ahead of time, it's _strongly_ recommended to pass it.
    ///
    /// Casting from `Vec<u8>`, `String`, or similar to `Body` will automatically set the value of
    /// `length`.
    ///
    /// # Content Encoding
    ///
    /// By default `Body` will come with a fallback Mime type that is used by `Request` and
    /// `Response` if no other type has been set, and no other Mime type can be inferred.
    ///
    /// It's _strongly_ recommended to always set a mime type on both the `Request` and `Response`,
    /// and not rely on the fallback mechanisms. However, they're still there if you need them.
    pub struct Body {
        #[pin]
        reader: Box<dyn AsyncBufRead + Unpin + Send + Sync + 'static>,
        mime: Mime,
        length: Option<usize>,
        bytes_read: usize
    }
}

impl Body {
    /// Create a new empty `Body`.
    ///
    /// The body will have a length of `0`, and the Mime type set to `application/octet-stream` if
    /// no other mime type has been set or can be sniffed.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, Response, StatusCode};
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    /// req.set_body(Body::empty());
    /// ```
    pub fn empty() -> Self {
        Self {
            reader: Box::new(io::empty()),
            mime: mime::BYTE_STREAM,
            length: Some(0),
            bytes_read: 0,
        }
    }

    /// Create a `Body` from a reader with an optional length.
    ///
    /// The Mime type is set to `application/octet-stream` if no other mime type has been set or can
    /// be sniffed. If a `Body` has no length, HTTP implementations will often switch over to
    /// framed messages such as [Chunked
    /// Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding).
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, Response, StatusCode};
    /// use async_std::io::Cursor;
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    ///
    /// let cursor = Cursor::new("Hello Nori");
    /// let len = 10;
    /// req.set_body(Body::from_reader(cursor, Some(len)));
    /// ```
    pub fn from_reader(
        reader: impl AsyncBufRead + Unpin + Send + Sync + 'static,
        len: Option<usize>,
    ) -> Self {
        Self {
            reader: Box::new(reader),
            mime: mime::BYTE_STREAM,
            length: len,
            bytes_read: 0,
        }
    }

    /// Get the inner reader from the `Body`
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::io::prelude::*;
    /// use http_types::Body;
    /// use async_std::io::Cursor;
    ///
    /// let cursor = Cursor::new("Hello Nori");
    /// let body = Body::from_reader(cursor, None);
    /// let _ = body.into_reader();
    /// ```
    pub fn into_reader(self) -> Box<dyn AsyncBufRead + Unpin + Send + Sync + 'static> {
        self.reader
    }

    /// Create a `Body` from a Vec of bytes.
    ///
    /// The Mime type is set to `application/octet-stream` if no other mime type has been set or can
    /// be sniffed. If a `Body` has no length, HTTP implementations will often switch over to
    /// framed messages such as [Chunked
    /// Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding).
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, Response, StatusCode};
    /// use async_std::io::Cursor;
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    ///
    /// let input = vec![1, 2, 3];
    /// req.set_body(Body::from_bytes(input));
    /// ```
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Self {
            mime: mime::BYTE_STREAM,
            length: Some(bytes.len()),
            reader: Box::new(io::Cursor::new(bytes)),
            bytes_read: 0,
        }
    }

    /// Parse the body into a `Vec<u8>`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    ///
    /// let bytes = vec![1, 2, 3];
    /// let body = Body::from_bytes(bytes);
    ///
    /// let bytes: Vec<u8> = body.into_bytes().await?;
    /// assert_eq!(bytes, vec![1, 2, 3]);
    /// # Ok(()) }) }
    /// ```
    pub async fn into_bytes(mut self) -> crate::Result<Vec<u8>> {
        let mut buf = Vec::with_capacity(1024);
        self.read_to_end(&mut buf)
            .await
            .status(StatusCode::UnprocessableEntity)?;
        Ok(buf)
    }

    /// Create a `Body` from a String
    ///
    /// The Mime type is set to `text/plain` if no other mime type has been set or can
    /// be sniffed. If a `Body` has no length, HTTP implementations will often switch over to
    /// framed messages such as [Chunked
    /// Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding).
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, Response, StatusCode};
    /// use async_std::io::Cursor;
    ///
    /// let mut req = Response::new(StatusCode::Ok);
    ///
    /// let input = String::from("hello Nori!");
    /// req.set_body(Body::from_string(input));
    /// ```
    pub fn from_string(s: String) -> Self {
        Self {
            mime: mime::PLAIN,
            length: Some(s.len()),
            reader: Box::new(io::Cursor::new(s.into_bytes())),
            bytes_read: 0,
        }
    }

    /// Read the body as a string
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    /// use async_std::io::Cursor;
    ///
    /// let cursor = Cursor::new("Hello Nori");
    /// let body = Body::from_reader(cursor, None);
    /// assert_eq!(&body.into_string().await.unwrap(), "Hello Nori");
    /// # Ok(()) }) }
    /// ```
    pub async fn into_string(mut self) -> crate::Result<String> {
        let mut result = String::with_capacity(self.len().unwrap_or(0));
        self.read_to_string(&mut result)
            .await
            .status(StatusCode::UnprocessableEntity)?;
        Ok(result)
    }

    /// Creates a `Body` from a type, serializing it as JSON.
    ///
    /// # Mime
    ///
    /// The encoding is set to `application/json`.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::{Body, convert::json};
    ///
    /// let body = Body::from_json(&json!({ "name": "Chashu" }));
    /// # drop(body);
    /// ```
    pub fn from_json(json: &impl Serialize) -> crate::Result<Self> {
        let bytes = serde_json::to_vec(&json)?;
        let body = Self {
            length: Some(bytes.len()),
            reader: Box::new(io::Cursor::new(bytes)),
            mime: mime::JSON,
            bytes_read: 0,
        };
        Ok(body)
    }

    /// Parse the body as JSON, serializing it to a struct.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    /// use http_types::convert::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Serialize, Deserialize)]
    /// struct Cat { name: String }
    ///
    /// let cat = Cat { name: String::from("chashu") };
    /// let body = Body::from_json(&cat)?;
    ///
    /// let cat: Cat = body.into_json().await?;
    /// assert_eq!(&cat.name, "chashu");
    /// # Ok(()) }) }
    /// ```
    pub async fn into_json<T: DeserializeOwned>(mut self) -> crate::Result<T> {
        let mut buf = Vec::with_capacity(1024);
        self.read_to_end(&mut buf).await?;
        Ok(serde_json::from_slice(&buf).status(StatusCode::UnprocessableEntity)?)
    }

    /// Creates a `Body` from a type, serializing it using form encoding.
    ///
    /// # Mime
    ///
    /// The encoding is set to `application/x-www-form-urlencoded`.
    ///
    /// # Errors
    ///
    /// An error will be returned if the encoding failed.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    /// use http_types::convert::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Serialize, Deserialize)]
    /// struct Cat { name: String }
    ///
    /// let cat = Cat { name: String::from("chashu") };
    /// let body = Body::from_form(&cat)?;
    ///
    /// let cat: Cat = body.into_form().await?;
    /// assert_eq!(&cat.name, "chashu");
    /// # Ok(()) }) }
    /// ```
    pub fn from_form(form: &impl Serialize) -> crate::Result<Self> {
        let query = serde_urlencoded::to_string(form)?;
        let bytes = query.into_bytes();

        let body = Self {
            length: Some(bytes.len()),
            reader: Box::new(io::Cursor::new(bytes)),
            mime: mime::FORM,
            bytes_read: 0,
        };
        Ok(body)
    }

    /// Parse the body from form encoding into a type.
    ///
    /// # Errors
    ///
    /// An error is returned if the underlying IO stream errors, or if the body
    /// could not be deserialized into the type.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    /// use http_types::convert::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Serialize, Deserialize)]
    /// struct Cat { name: String }
    ///
    /// let cat = Cat { name: String::from("chashu") };
    /// let body = Body::from_form(&cat)?;
    ///
    /// let cat: Cat = body.into_form().await?;
    /// assert_eq!(&cat.name, "chashu");
    /// # Ok(()) }) }
    /// ```
    pub async fn into_form<T: DeserializeOwned>(self) -> crate::Result<T> {
        let s = self.into_string().await?;
        Ok(serde_urlencoded::from_str(&s).status(StatusCode::UnprocessableEntity)?)
    }

    /// Create a `Body` from a file.
    ///
    /// The Mime type set to `application/octet-stream` if no other mime type has
    /// been set or can be sniffed.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::{Body, Response, StatusCode};
    ///
    /// let mut res = Response::new(StatusCode::Ok);
    /// res.set_body(Body::from_file("/path/to/file").await?);
    /// # Ok(()) }) }
    /// ```
    #[cfg(all(feature = "fs", not(target_os = "unknown")))]
    pub async fn from_file<P>(path: P) -> io::Result<Self>
    where
        P: AsRef<std::path::Path>,
    {
        let path = path.as_ref();
        let mut file = async_std::fs::File::open(path).await?;
        let len = file.metadata().await?.len();

        // Look at magic bytes first, look at extension second, fall back to
        // octet stream.
        let mime = peek_mime(&mut file)
            .await?
            .or_else(|| guess_ext(path))
            .unwrap_or(mime::BYTE_STREAM);

        Ok(Self {
            mime,
            length: Some(len as usize),
            reader: Box::new(io::BufReader::new(file)),
            bytes_read: 0,
        })
    }

    /// Get the length of the body in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use http_types::Body;
    /// use async_std::io::Cursor;
    ///
    /// let cursor = Cursor::new("Hello Nori");
    /// let len = 10;
    /// let body = Body::from_reader(cursor, Some(len));
    /// assert_eq!(body.len(), Some(10));
    /// ```
    pub fn len(&self) -> Option<usize> {
        self.length
    }

    /// Returns `true` if the body has a length of zero, and `false` otherwise.
    pub fn is_empty(&self) -> Option<bool> {
        self.length.map(|length| length == 0)
    }

    /// Returns the mime type of this Body.
    pub fn mime(&self) -> &Mime {
        &self.mime
    }

    /// Sets the mime type of this Body.
    pub fn set_mime(&mut self, mime: impl Into<Mime>) {
        self.mime = mime.into();
    }

    /// Create a Body by chaining another Body after this one, consuming both.
    ///
    /// If both Body instances have a length, and their sum does not overflow,
    /// the resulting Body will have a length.
    ///
    /// If both Body instances have the same fallback MIME type, the resulting
    /// Body will have the same fallback MIME type; otherwise, the resulting
    /// Body will have the fallback MIME type `application/octet-stream`.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
    /// use http_types::Body;
    /// use async_std::io::Cursor;
    ///
    /// let cursor = Cursor::new("Hello ");
    /// let body = Body::from_reader(cursor, None).chain(Body::from("Nori"));
    /// assert_eq!(&body.into_string().await.unwrap(), "Hello Nori");
    /// # Ok(()) }) }
    /// ```
    pub fn chain(self, other: Body) -> Self {
        let mime = if self.mime == other.mime {
            self.mime.clone()
        } else {
            mime::BYTE_STREAM
        };
        let length = match (self.length, other.length) {
            (Some(l1), Some(l2)) => (l1 - self.bytes_read).checked_add(l2 - other.bytes_read),
            _ => None,
        };
        Self {
            mime,
            length,
            reader: Box::new(futures_lite::io::AsyncReadExt::chain(self, other)),
            bytes_read: 0,
        }
    }
}

impl Debug for Body {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Body")
            .field("reader", &"<hidden>")
            .field("length", &self.length)
            .field("bytes_read", &self.bytes_read)
            .finish()
    }
}

impl From<serde_json::Value> for Body {
    fn from(json_value: serde_json::Value) -> Self {
        Self::from_json(&json_value).unwrap()
    }
}

impl From<String> for Body {
    fn from(s: String) -> Self {
        Self::from_string(s)
    }
}

impl<'a> From<&'a str> for Body {
    fn from(s: &'a str) -> Self {
        Self::from_string(s.to_owned())
    }
}

impl From<Vec<u8>> for Body {
    fn from(b: Vec<u8>) -> Self {
        Self::from_bytes(b)
    }
}

impl<'a> From<&'a [u8]> for Body {
    fn from(b: &'a [u8]) -> Self {
        Self::from_bytes(b.to_owned())
    }
}

impl AsyncRead for Body {
    #[allow(missing_doc_code_examples)]
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut buf = match self.length {
            None => buf,
            Some(length) if length == self.bytes_read => return Poll::Ready(Ok(0)),
            Some(length) => {
                let max_len = (length - self.bytes_read).min(buf.len());
                &mut buf[0..max_len]
            }
        };

        let bytes = ready!(Pin::new(&mut self.reader).poll_read(cx, &mut buf))?;
        self.bytes_read += bytes;
        Poll::Ready(Ok(bytes))
    }
}

impl AsyncBufRead for Body {
    #[allow(missing_doc_code_examples)]
    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&'_ [u8]>> {
        self.project().reader.poll_fill_buf(cx)
    }

    fn consume(mut self: Pin<&mut Self>, amt: usize) {
        Pin::new(&mut self.reader).consume(amt)
    }
}

/// Look at first few bytes of a file to determine the mime type.
/// This is used for various binary formats such as images and videos.
#[cfg(all(feature = "fs", not(target_os = "unknown")))]
async fn peek_mime(file: &mut async_std::fs::File) -> io::Result<Option<Mime>> {
    // We need to read the first 300 bytes to correctly infer formats such as tar.
    let mut buf = [0_u8; 300];
    file.read(&mut buf).await?;
    let mime = Mime::sniff(&buf).ok();

    // Reset the file cursor back to the start.
    file.seek(io::SeekFrom::Start(0)).await?;
    Ok(mime)
}

/// Look at the extension of a file to determine the mime type.
/// This is useful for plain-text formats such as HTML and CSS.
#[cfg(all(feature = "fs", not(target_os = "unknown")))]
fn guess_ext(path: &std::path::Path) -> Option<Mime> {
    let ext = path.extension().map(|p| p.to_str()).flatten();
    ext.and_then(Mime::from_extension)
}

#[cfg(test)]
mod test {
    use super::*;
    use async_std::io::Cursor;
    use serde::Deserialize;

    #[async_std::test]
    async fn json_status() {
        #[derive(Debug, Deserialize)]
        struct Foo {
            inner: String,
        }
        let body = Body::empty();
        let res = body.into_json::<Foo>().await;
        assert_eq!(res.unwrap_err().status(), 422);
    }

    #[async_std::test]
    async fn form_status() {
        #[derive(Debug, Deserialize)]
        struct Foo {
            inner: String,
        }
        let body = Body::empty();
        let res = body.into_form::<Foo>().await;
        assert_eq!(res.unwrap_err().status(), 422);
    }

    async fn read_with_buffers_of_size<R>(reader: &mut R, size: usize) -> crate::Result<String>
    where
        R: AsyncRead + Unpin,
    {
        let mut return_buffer = vec![];
        loop {
            let mut buf = vec![0; size];
            match reader.read(&mut buf).await? {
                0 => break Ok(String::from_utf8(return_buffer)?),
                bytes_read => return_buffer.extend_from_slice(&buf[..bytes_read]),
            }
        }
    }

    #[async_std::test]
    async fn attempting_to_read_past_length() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from_reader(Cursor::new("hello world"), Some(5));
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello"
            );
            assert_eq!(body.bytes_read, 5);
        }

        Ok(())
    }

    #[async_std::test]
    async fn attempting_to_read_when_length_is_greater_than_content() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from_reader(Cursor::new("hello world"), Some(15));
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn attempting_to_read_when_length_is_exactly_right() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from_reader(Cursor::new("hello world"), Some(11));
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn reading_in_various_buffer_lengths_when_there_is_no_length() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from_reader(Cursor::new("hello world"), None);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_strings() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from("hello ").chain(Body::from("world"));
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::PLAIN);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_mixed_bytes_string() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from(&b"hello "[..]).chain(Body::from("world"));
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_mixed_reader_string() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body =
                Body::from_reader(Cursor::new("hello "), Some(6)).chain(Body::from("world"));
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_mixed_nolen_len() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body =
                Body::from_reader(Cursor::new("hello "), None).chain(Body::from("world"));
            assert_eq!(body.len(), None);
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_mixed_len_nolen() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body =
                Body::from("hello ").chain(Body::from_reader(Cursor::new("world"), None));
            assert_eq!(body.len(), None);
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_short() -> crate::Result<()> {
        for buf_len in 1..26 {
            let mut body = Body::from_reader(Cursor::new("hello xyz"), Some(6))
                .chain(Body::from_reader(Cursor::new("world abc"), Some(5)));
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_many() -> crate::Result<()> {
        for buf_len in 1..13 {
            let mut body = Body::from("hello")
                .chain(Body::from(&b" "[..]))
                .chain(Body::from("world"));
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }

    #[async_std::test]
    async fn chain_skip_start() -> crate::Result<()> {
        for buf_len in 1..26 {
            let mut body1 = Body::from_reader(Cursor::new("1234 hello xyz"), Some(11));
            let mut buf = vec![0; 5];
            body1.read(&mut buf).await?;
            assert_eq!(buf, b"1234 ");

            let mut body2 = Body::from_reader(Cursor::new("321 world abc"), Some(9));
            let mut buf = vec![0; 4];
            body2.read(&mut buf).await?;
            assert_eq!(buf, b"321 ");

            let mut body = body1.chain(body2);
            assert_eq!(body.len(), Some(11));
            assert_eq!(body.mime(), &mime::BYTE_STREAM);
            assert_eq!(
                read_with_buffers_of_size(&mut body, buf_len).await?,
                "hello world"
            );
            assert_eq!(body.bytes_read, 11);
        }

        Ok(())
    }
}