Skip to content

Commit

Permalink
Add String impl for body (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
LucioFranco authored May 20, 2022
1 parent a97da64 commit 730e9bd
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ pub use self::next::{Data, Trailers};
pub use self::size_hint::SizeHint;

use self::combinators::{BoxBody, MapData, MapErr, UnsyncBoxBody};
use bytes::Buf;
use bytes::{Buf, Bytes};
use http::HeaderMap;
use std::convert::Infallible;
use std::ops;
use std::pin::Pin;
use std::task::{Context, Poll};
Expand Down Expand Up @@ -283,6 +284,38 @@ impl<B: Body> Body for http::Response<B> {
}
}

impl Body for String {
type Data = Bytes;
type Error = Infallible;

fn poll_data(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
if !self.is_empty() {
let s = std::mem::take(&mut *self);
Poll::Ready(Some(Ok(s.into_bytes().into())))
} else {
Poll::Ready(None)
}
}

fn poll_trailers(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<Option<HeaderMap>, Self::Error>> {
Poll::Ready(Ok(None))
}

fn is_end_stream(&self) -> bool {
self.is_empty()
}

fn size_hint(&self) -> SizeHint {
SizeHint::with_exact(self.len() as u64)
}
}

#[cfg(test)]
fn _assert_bounds() {
fn can_be_trait_object(_: &dyn Body<Data = std::io::Cursor<Vec<u8>>, Error = std::io::Error>) {}
Expand Down

0 comments on commit 730e9bd

Please sign in to comment.