hyper/body/
mod.rs

1//! Streaming bodies for Requests and Responses
2//!
3//! For both [Clients](crate::client) and [Servers](crate::server), requests and
4//! responses use streaming bodies, instead of complete buffering. This
5//! allows applications to not use memory they don't need, and allows exerting
6//! back-pressure on connections by only reading when asked.
7//!
8//! There are two pieces to this in hyper:
9//!
10//! - **The [`HttpBody`](HttpBody) trait** describes all possible bodies.
11//!   hyper allows any body type that implements `HttpBody`, allowing
12//!   applications to have fine-grained control over their streaming.
13//! - **The [`Body`](Body) concrete type**, which is an implementation of
14//!   `HttpBody`, and returned by hyper as a "receive stream" (so, for server
15//!   requests and client responses). It is also a decent default implementation
16//!   if you don't have very custom needs of your send streams.
17
18pub use bytes::{Buf, Bytes};
19pub use http_body::Body as HttpBody;
20pub use http_body::SizeHint;
21
22#[cfg_attr(feature = "deprecated", allow(deprecated))]
23pub use self::aggregate::aggregate;
24pub use self::body::{Body, Sender};
25pub(crate) use self::length::DecodedLength;
26#[cfg_attr(feature = "deprecated", allow(deprecated))]
27pub use self::to_bytes::to_bytes;
28
29mod aggregate;
30mod body;
31mod length;
32mod to_bytes;
33
34/// An optimization to try to take a full body if immediately available.
35///
36/// This is currently limited to *only* `hyper::Body`s.
37#[cfg(feature = "http1")]
38pub(crate) fn take_full_data<T: HttpBody + 'static>(body: &mut T) -> Option<T::Data> {
39    use std::any::{Any, TypeId};
40
41    // This static type check can be optimized at compile-time.
42    if TypeId::of::<T>() == TypeId::of::<Body>() {
43        let mut full = (body as &mut dyn Any)
44            .downcast_mut::<Body>()
45            .expect("must be Body")
46            .take_full_data();
47        // This second cast is required to make the type system happy.
48        // Without it, the compiler cannot reason that the type is actually
49        // `T::Data`. Oh wells.
50        //
51        // It's still a measurable win!
52        (&mut full as &mut dyn Any)
53            .downcast_mut::<Option<T::Data>>()
54            .expect("must be T::Data")
55            .take()
56    } else {
57        None
58    }
59}
60
61fn _assert_send_sync() {
62    fn _assert_send<T: Send>() {}
63    fn _assert_sync<T: Sync>() {}
64
65    _assert_send::<Body>();
66    _assert_sync::<Body>();
67}