Debian Codegraph @

src/model/body.rs

raw symbols SCIP
1 use crate::model::HeaderMap;
2 #[cfg(feature = "flate2")]
3 use flate2::read::{DeflateDecoder, GzDecoder};
4 use std::borrow::Cow;
5 use std::fmt;
6 use std::io::{Cursor, Error, ErrorKind, Read, Result};
7
8 /// A request or response [body](https://httpwg.org/http-core/draft-ietf-httpbis-messaging-latest.html#message.body).
9 ///
10 /// It implements the [`Read`] API.
11 pub struct Body(BodyAlt);
12
13 enum BodyAlt {
14 SimpleOwned(Cursor<Vec<u8>>),
15 SimpleBorrowed(&'static [u8]),
16 Sized {
17 content: Box<dyn Read>,
18 total_len: u64,
19 consumed_len: u64,
20 },
21 Chunked(Box<dyn ChunkedTransferPayload>),
22 #[cfg(feature = "flate2")]
23 DecodingDeflate(DeflateDecoder<Box<Body>>),
24 #[cfg(feature = "flate2")]
25 DecodingGzip(GzDecoder<Box<Body>>),
26 }
27
28 impl Body {
29 /// Creates a new body from a [`Read`] implementation.
30 ///
31 /// If the body is sent as an HTTP request or response it will be streamed using [chunked transfer encoding](https://httpwg.org/http-core/draft-ietf-httpbis-messaging-latest.html#chunked.encoding).
32 #[inline]
33 pub fn from_read(read: impl Read + 'static) -> Self {
34 Self::from_chunked_transfer_payload(SimpleChunkedTransferEncoding(read))
35 }
36
37 #[inline]
38 pub(crate) fn from_read_and_len(read: impl Read + 'static, len: u64) -> Self {
39 Self(BodyAlt::Sized {
40 total_len: len,
41 consumed_len: 0,
42 content: Box::new(read.take(len)),
43 })
44 }
45
46 /// Creates a [chunked transfer encoding](https://httpwg.org/http-core/draft-ietf-httpbis-messaging-latest.html#chunked.encoding) body with optional [trailers](https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#trailer.fields).
47 #[inline]
48 pub fn from_chunked_transfer_payload(payload: impl ChunkedTransferPayload + 'static) -> Self {
49 Self(BodyAlt::Chunked(Box::new(payload)))
50 }
51
52 #[cfg(feature = "flate2")]
53 pub(crate) fn decode_gzip(self) -> Self {
54 Self(BodyAlt::DecodingGzip(GzDecoder::new(Box::new(self))))
55 }
56
57 #[cfg(feature = "flate2")]
58 pub(crate) fn decode_deflate(self) -> Self {
59 Self(BodyAlt::DecodingDeflate(DeflateDecoder::new(Box::new(
60 self,
61 ))))
62 }
63
64 /// The empty body
65 #[inline]
66 pub fn empty() -> Self {
67 Self(BodyAlt::SimpleBorrowed(b""))
68 }
69
70 /// The number of bytes in the body (if known).
71 #[allow(clippy::len_without_is_empty)]
72 #[inline]
73 pub fn len(&self) -> Option<u64> {
74 match &self.0 {
75 BodyAlt::SimpleOwned(d) => Some(d.get_ref().len().try_into().unwrap()),
76 BodyAlt::SimpleBorrowed(d) => Some(d.len().try_into().unwrap()),
77 BodyAlt::Sized { total_len, .. } => Some(*total_len),
78 BodyAlt::Chunked(_) => None,
79 #[cfg(feature = "flate2")]
80 BodyAlt::DecodingDeflate(_) | BodyAlt::DecodingGzip(_) => None,
81 }
82 }
83
84 /// Returns the chunked transfer encoding trailers if they exists and are already received.
85 /// You should fully consume the body before attempting to fetch them.
86 #[inline]
87 pub fn trailers(&self) -> Option<&HeaderMap> {
88 match &self.0 {
89 BodyAlt::SimpleOwned(_) | BodyAlt::SimpleBorrowed(_) | BodyAlt::Sized { .. } => None,
90 BodyAlt::Chunked(c) => c.trailers(),
91 #[cfg(feature = "flate2")]
92 BodyAlt::DecodingDeflate(c) => c.get_ref().trailers(),
93 #[cfg(feature = "flate2")]
94 BodyAlt::DecodingGzip(c) => c.get_ref().trailers(),
95 }
96 }
97
98 /// Reads the full body into a vector.
99 ///
100 /// <div class="warning">Beware of the body size!</div>
101 ///
102 /// ```
103 /// use oxhttp::model::Body;
104 /// use std::io::Cursor;
105 ///
106 /// let mut body = Body::from_read(b"foo".as_ref());
107 /// assert_eq!(&body.to_vec()?, b"foo");
108 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
109 /// ```
110 #[inline]
111 pub fn to_vec(mut self) -> Result<Vec<u8>> {
112 let mut buf = Vec::new();
113 self.read_to_end(&mut buf)?;
114 Ok(buf)
115 }
116
117 /// Reads the full body into a string.
118 ///
119 /// <div class="warning">Beware of the body size!</div>
120 ///
121 /// ```
122 /// use oxhttp::model::Body;
123 /// use std::io::Cursor;
124 ///
125 /// let mut body = Body::from_read(b"foo".as_ref());
126 /// assert_eq!(&body.to_string()?, "foo");
127 /// # Result::<_,Box<dyn std::error::Error>>::Ok(())
128 /// ```
129 #[inline]
130 pub fn to_string(mut self) -> Result<String> {
131 let mut buf = String::new();
132 self.read_to_string(&mut buf)?;
133 Ok(buf)
134 }
135
136 fn debug_fields<'a, 'b, 'c>(
137 &'b self,
138 s: &'c mut fmt::DebugStruct<'b, 'a>,
139 ) -> &'c mut fmt::DebugStruct<'b, 'a> {
140 match &self.0 {
141 BodyAlt::SimpleOwned(d) => s.field("content-length", &d.get_ref().len()),
142 BodyAlt::SimpleBorrowed(d) => s.field("content-length", &d.len()),
143 BodyAlt::Sized { total_len, .. } => s.field("content-length", total_len),
144 BodyAlt::Chunked(_) => s.field("transfer-encoding", &"chunked"),
145 #[cfg(feature = "flate2")]
146 BodyAlt::DecodingDeflate(inner) => inner
147 .get_ref()
148 .debug_fields(s.field("content-encoding", &"deflate")),
149 #[cfg(feature = "flate2")]
150 BodyAlt::DecodingGzip(inner) => inner
151 .get_ref()
152 .debug_fields(s.field("content-encoding", &"gzip")),
153 }
154 }
155 }
156
157 impl Read for Body {
158 #[inline]
159 fn read(&mut self, mut buf: &mut [u8]) -> Result<usize> {
160 match &mut self.0 {
161 BodyAlt::SimpleOwned(c) => c.read(buf),
162 BodyAlt::SimpleBorrowed(c) => c.read(buf),
163 BodyAlt::Sized {
164 content,
165 consumed_len,
166 total_len,
167 } => {
168 let remaining_size = *total_len - *consumed_len;
169 if remaining_size < u64::try_from(buf.len()).unwrap() {
170 buf = &mut buf[..usize::try_from(remaining_size).unwrap()];
171 }
172 if buf.is_empty() {
173 return Ok(0); // Nothing to read
174 }
175 let read = content.read(buf)?;
176 *consumed_len += u64::try_from(read).unwrap();
177 if read == 0 {
178 // We are missing some bytes
179 return Err(Error::new(ErrorKind::ConnectionAborted, format!("The body was expected to contain {total_len} bytes but we have been able to only read {consumed_len}")));
180 }
181 Ok(read)
182 }
183 BodyAlt::Chunked(inner) => inner.read(buf),
184 #[cfg(feature = "flate2")]
185 BodyAlt::DecodingDeflate(inner) => inner.read(buf),
186 #[cfg(feature = "flate2")]
187 BodyAlt::DecodingGzip(inner) => inner.read(buf),
188 }
189 }
190 }
191
192 impl Default for Body {
193 #[inline]
194 fn default() -> Self {
195 Self::empty()
196 }
197 }
198
199 impl From<Vec<u8>> for Body {
200 #[inline]
201 fn from(data: Vec<u8>) -> Self {
202 Self(BodyAlt::SimpleOwned(Cursor::new(data)))
203 }
204 }
205
206 impl From<String> for Body {
207 #[inline]
208 fn from(data: String) -> Self {
209 data.into_bytes().into()
210 }
211 }
212
213 impl From<&'static [u8]> for Body {
214 #[inline]
215 fn from(data: &'static [u8]) -> Self {
216 Self(BodyAlt::SimpleBorrowed(data))
217 }
218 }
219
220 impl From<&'static str> for Body {
221 #[inline]
222 fn from(data: &'static str) -> Self {
223 data.as_bytes().into()
224 }
225 }
226
227 impl From<Cow<'static, [u8]>> for Body {
228 #[inline]
229 fn from(data: Cow<'static, [u8]>) -> Self {
230 match data {
231 Cow::Borrowed(data) => data.into(),
232 Cow::Owned(data) => data.into(),
233 }
234 }
235 }
236
237 impl From<Cow<'static, str>> for Body {
238 #[inline]
239 fn from(data: Cow<'static, str>) -> Self {
240 match data {
241 Cow::Borrowed(data) => data.into(),
242 Cow::Owned(data) => data.into(),
243 }
244 }
245 }
246
247 impl From<()> for Body {
248 #[inline]
249 fn from(_: ()) -> Self {
250 Self::empty()
251 }
252 }
253
254 impl fmt::Debug for Body {
255 #[inline]
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 self.debug_fields(&mut f.debug_struct("Body")).finish()
258 }
259 }
260
261 /// Trait to give to [`Body::from_chunked_transfer_payload`] a body to serialize
262 /// as [chunked transfer encoding](https://httpwg.org/http-core/draft-ietf-httpbis-messaging-latest.html#chunked.encoding).
263 ///
264 /// It allows to provide [trailers](https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#trailer.fields) to serialize.
265 pub trait ChunkedTransferPayload: Read {
266 /// The [trailers](https://httpwg.org/http-core/draft-ietf-httpbis-semantics-latest.html#trailer.fields) to serialize.
267 fn trailers(&self) -> Option<&HeaderMap>;
268 }
269
270 struct SimpleChunkedTransferEncoding<R: Read>(R);
271
272 impl<R: Read> Read for SimpleChunkedTransferEncoding<R> {
273 #[inline]
274 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
275 self.0.read(buf)
276 }
277 }
278
279 impl<R: Read> ChunkedTransferPayload for SimpleChunkedTransferEncoding<R> {
280 #[inline]
281 fn trailers(&self) -> Option<&HeaderMap> {
282 None
283 }
284 }