use crate::shared_body::SharedBody;
pub trait SharedBodyExt: http_body::Body {
fn into_shared(self) -> SharedBody<Self>
where
Self: Sized + Unpin,
Self::Data: Clone,
Self::Error: Clone,
{
SharedBody::new(self)
}
}
impl<B> SharedBodyExt for B where B: http_body::Body {}
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
use futures_util::stream;
use http_body::Frame;
use http_body_util::{BodyExt, StreamBody};
#[tokio::test]
async fn test_into_shared_trait_works() {
let chunks = vec!["test", "data"];
let stream = stream::iter(
chunks
.into_iter()
.map(|s| Ok::<_, std::convert::Infallible>(Frame::data(Bytes::from(s)))),
);
let body = StreamBody::new(stream);
let shared_body: SharedBody<_> = body.into_shared();
let result = shared_body.collect().await.unwrap().to_bytes();
assert_eq!(result, Bytes::from("testdata"));
}
#[tokio::test]
async fn test_into_shared_with_multiple_consumers() {
let chunks = vec!["hello", "world"];
let stream = stream::iter(
chunks
.into_iter()
.map(|s| Ok::<_, std::convert::Infallible>(Frame::data(Bytes::from(s)))),
);
let body = StreamBody::new(stream);
let shared_body = body.into_shared();
let consumer1 = shared_body.clone();
let consumer2 = shared_body.clone();
let result1 = consumer1.collect().await.unwrap().to_bytes();
let result2 = consumer2.collect().await.unwrap().to_bytes();
assert_eq!(result1, Bytes::from("helloworld"));
assert_eq!(result2, Bytes::from("helloworld"));
}
}