aws_smithy_http_server/
body.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! HTTP body utilities.
7
8// Used in the codegen in trait bounds.
9#[doc(hidden)]
10pub use http_body::Body as HttpBody;
11
12pub use hyper::body::Body;
13
14use bytes::Bytes;
15
16use crate::error::{BoxError, Error};
17
18/// The primary [`Body`] returned by the generated `smithy-rs` service.
19pub type BoxBody = http_body::combinators::UnsyncBoxBody<Bytes, Error>;
20
21// `boxed` is used in the codegen of the implementation of the operation `Handler` trait.
22/// Convert a [`http_body::Body`] into a [`BoxBody`].
23pub fn boxed<B>(body: B) -> BoxBody
24where
25    B: http_body::Body<Data = Bytes> + Send + 'static,
26    B::Error: Into<BoxError>,
27{
28    try_downcast(body).unwrap_or_else(|body| body.map_err(Error::new).boxed_unsync())
29}
30
31#[doc(hidden)]
32pub(crate) fn try_downcast<T, K>(k: K) -> Result<T, K>
33where
34    T: 'static,
35    K: Send + 'static,
36{
37    let mut k = Some(k);
38    if let Some(k) = <dyn std::any::Any>::downcast_mut::<Option<T>>(&mut k) {
39        Ok(k.take().unwrap())
40    } else {
41        Err(k.unwrap())
42    }
43}
44
45pub(crate) fn empty() -> BoxBody {
46    boxed(http_body::Empty::new())
47}
48
49/// Convert anything that can be converted into a [`hyper::body::Body`] into a [`BoxBody`].
50/// This simplifies codegen a little bit.
51#[doc(hidden)]
52pub fn to_boxed<B>(body: B) -> BoxBody
53where
54    Body: From<B>,
55{
56    boxed(Body::from(body))
57}