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
22pub use self::aggregate::aggregate;
23pub use self::body::{Body, Sender};
24pub(crate) use self::length::DecodedLength;
25pub use self::to_bytes::to_bytes;
26
27mod aggregate;
28mod body;
29mod length;
30mod to_bytes;
31
32/// An optimization to try to take a full body if immediately available.
33///
34/// This is currently limited to *only* `hyper::Body`s.
35#[cfg(feature = "http1")]
36pub(crate) fn take_full_data<T: HttpBody + 'static>(body: &mut T) -> Option<T::Data> {
37    use std::any::{Any, TypeId};
38
39    // This static type check can be optimized at compile-time.
40    if TypeId::of::<T>() == TypeId::of::<Body>() {
41        let mut full = (body as &mut dyn Any)
42            .downcast_mut::<Body>()
43            .expect("must be Body")
44            .take_full_data();
45        // This second cast is required to make the type system happy.
46        // Without it, the compiler cannot reason that the type is actually
47        // `T::Data`. Oh wells.
48        //
49        // It's still a measurable win!
50        (&mut full as &mut dyn Any)
51            .downcast_mut::<Option<T::Data>>()
52            .expect("must be T::Data")
53            .take()
54    } else {
55        None
56    }
57}
58
59fn _assert_send_sync() {
60    fn _assert_send<T: Send>() {}
61    fn _assert_sync<T: Sync>() {}
62
63    _assert_send::<Body>();
64    _assert_sync::<Body>();
65}