1 use bytes::{Buf, BufMut, Bytes};
2 
3 use super::HttpBody;
4 
5 /// Concatenate the buffers from a body into a single `Bytes` asynchronously.
6 ///
7 /// This may require copying the data into a single buffer. If you don't need
8 /// a contiguous buffer, prefer the [`aggregate`](crate::body::aggregate())
9 /// function.
to_bytes<T>(body: T) -> Result<Bytes, T::Error> where T: HttpBody,10 pub async fn to_bytes<T>(body: T) -> Result<Bytes, T::Error>
11 where
12     T: HttpBody,
13 {
14     futures_util::pin_mut!(body);
15 
16     // If there's only 1 chunk, we can just return Buf::to_bytes()
17     let mut first = if let Some(buf) = body.data().await {
18         buf?
19     } else {
20         return Ok(Bytes::new());
21     };
22 
23     let second = if let Some(buf) = body.data().await {
24         buf?
25     } else {
26         return Ok(first.to_bytes());
27     };
28 
29     // With more than 1 buf, we gotta flatten into a Vec first.
30     let cap = first.remaining() + second.remaining() + body.size_hint().lower() as usize;
31     let mut vec = Vec::with_capacity(cap);
32     vec.put(first);
33     vec.put(second);
34 
35     while let Some(buf) = body.data().await {
36         vec.put(buf?);
37     }
38 
39     Ok(vec.into())
40 }
41