pub struct Body { /* private fields */ }Expand description
Flexible HTTP body that can represent data in various forms.
Body is the core type for representing HTTP request and response bodies.
It can efficiently handle different data sources:
- In-memory data: Bytes, strings, vectors
- Streaming data: Files, network streams, async readers
- Structured data: JSON, form data (with appropriate features)
The body automatically manages the underlying representation and provides zero-copy conversions where possible.
§Examples
use http_kit::Body;
// Create from string
let body = Body::from_bytes("Hello, world!");
// Create empty body
let empty = Body::empty();
// Check if empty (when size is known)
if let Some(true) = body.is_empty() {
println!("Body is empty");
}Implementations§
Source§impl Body
impl Body
Sourcepub const fn empty() -> Self
pub const fn empty() -> Self
Creates a new empty body.
This creates a body with zero bytes that can be used as a placeholder or default value.
§Examples
use http_kit::Body;
let body = Body::empty();
assert_eq!(body.len(), Some(0));Sourcepub const fn frozen() -> Self
pub const fn frozen() -> Self
Creates a new frozen body that cannot provide data.
A frozen body represents a body that has been consumed and can no longer provide data. This is typically used internally after a body has been taken or consumed.
§Examples
use http_kit::Body;
let body = Body::frozen();
assert!(body.is_frozen());Sourcepub fn from_reader(
reader: impl AsyncBufRead + Send + Sync + 'static,
length: impl Into<Option<usize>>,
) -> Self
pub fn from_reader( reader: impl AsyncBufRead + Send + Sync + 'static, length: impl Into<Option<usize>>, ) -> Self
Creates a body from an async buffered reader.
This method allows streaming data from any source that implements
AsyncBufRead, such as files, network connections, or in-memory buffers.
The optional length hint can improve performance for operations that
benefit from knowing the total size.
§Arguments
reader- Any type implementingAsyncBufRead + Send + Sync + 'staticlength- Optional hint about the total number of bytes to read
§Examples
use http_kit::Body;
use async_fs::File;
use futures_lite::io::BufReader;
let file = File::open("data.txt").await?;
let metadata = file.metadata().await?;
let reader = BufReader::new(file);
let body = Body::from_reader(reader, metadata.len() as usize);Sourcepub fn from_stream<T, E, S>(stream: S) -> Self
pub fn from_stream<T, E, S>(stream: S) -> Self
Creates a body from an async stream of data chunks.
This method allows creating a body from any stream that yields
Result<T, E> where T can be converted to Bytes. This is useful
for handling data from network sources, databases, or custom generators.
§Type Parameters
T- Data type that can be converted toBytesE- Error type that can be converted to a boxed errorS- Stream type yieldingResult<T, E>
§Examples
use http_kit::Body;
use futures_lite::stream;
let data_stream = stream::iter(vec![
Ok::<_, std::io::Error>("Hello, ".as_bytes()),
Ok("world!".as_bytes()),
]);
let body = Body::from_stream(data_stream);Sourcepub fn from_bytes(data: impl Into<Bytes>) -> Self
pub fn from_bytes(data: impl Into<Bytes>) -> Self
Creates a body from bytes or byte-like data.
This method accepts any type that can be converted to Bytes,
including String, Vec<u8>, &str, &[u8], and Bytes itself.
The conversion is zero-copy when possible.
§Examples
use http_kit::Body;
// From string slice
let body1 = Body::from_bytes("Hello, world!");
// From String
let body2 = Body::from_bytes("Hello, world!".to_string());
// From byte vector
let body3 = Body::from_bytes(vec![72, 101, 108, 108, 111]);Sourcepub fn from_json<T: Serialize>(value: T) -> Result<Self, Error>
pub fn from_json<T: Serialize>(value: T) -> Result<Self, Error>
Creates a body by serializing an object to JSON.
This method serializes any Serialize type to JSON and creates
a body containing the JSON string. The resulting body will have
UTF-8 encoded JSON content.
§Arguments
value- Any type implementingserde::Serialize
§Errors
Returns serde_json::Error if serialization fails.
§Examples
use http_kit::Body;
use serde::Serialize;
#[derive(Serialize)]
struct User {
name: String,
age: u32,
}
let user = User {
name: "Alice".to_string(),
age: 30,
};
let body = Body::from_json(&user)?;Sourcepub fn from_form<T: Serialize>(value: T) -> Result<Self, Error>
pub fn from_form<T: Serialize>(value: T) -> Result<Self, Error>
Creates a body by serializing an object to URL-encoded form data.
This method serializes any Serialize type to application/x-www-form-urlencoded
format, commonly used for HTML form submissions.
§Arguments
value- Any type implementingserde::Serialize
§Errors
Returns serde_urlencoded::ser::Error if serialization fails.
§Examples
use http_kit::Body;
use serde::Serialize;
#[derive(Serialize)]
struct LoginForm {
username: String,
password: String,
}
let form = LoginForm {
username: "user".to_string(),
password: "pass".to_string(),
};
let body = Body::from_form(&form)?;Sourcepub const fn len(&self) -> Option<usize>
pub const fn len(&self) -> Option<usize>
Returns the length of the body in bytes, if known.
This method returns Some(length) for in-memory bodies where the size
is immediately available. For streaming bodies (files, readers, streams),
it returns None since the total size may not be known until the entire
body is consumed.
The returned length is primarily used for optimizations like setting
Content-Length headers, but should be considered a hint rather than
a guarantee.
§Examples
use http_kit::Body;
let body = Body::from_bytes("Hello, world!");
assert_eq!(body.len(), Some(13));
let empty = Body::empty();
assert_eq!(empty.len(), Some(0));Sourcepub const fn is_empty(&self) -> Option<bool>
pub const fn is_empty(&self) -> Option<bool>
Returns whether the body is empty, if the length is known.
This method returns Some(true) if the body is known to be empty,
Some(false) if the body is known to contain data, and None if
the body length cannot be determined without consuming it.
§Examples
use http_kit::Body;
let empty = Body::empty();
assert_eq!(empty.is_empty(), Some(true));
let body = Body::from_bytes("data");
assert_eq!(body.is_empty(), Some(false));Sourcepub async fn into_bytes(self) -> Result<Bytes, Error>
pub async fn into_bytes(self) -> Result<Bytes, Error>
Consumes the body and returns all its data as Bytes.
This method reads the entire body into memory and returns it as a
Bytes object. For large bodies or streams, this may consume significant
memory. For streaming bodies, all data will be read and concatenated.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
- The underlying stream produces an error
§Examples
use http_kit::Body;
let body = Body::from_bytes("Hello, world!");
let bytes = body.into_bytes().await?;
assert_eq!(bytes, "Hello, world!");Sourcepub async fn into_string(self) -> Result<ByteStr, Error>
pub async fn into_string(self) -> Result<ByteStr, Error>
Consumes the body and returns its data as a UTF-8 string.
This method reads the entire body into memory and converts it to a
UTF-8 string, returning a ByteStr which provides string-like operations
while maintaining the underlying byte representation.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
- The body contains invalid UTF-8 sequences
§Examples
use http_kit::Body;
let body = Body::from_bytes("Hello, world!");
let text = body.into_string().await?;
assert_eq!(text, "Hello, world!");Sourcepub fn into_reader(self) -> impl AsyncBufRead + Send + Sync
pub fn into_reader(self) -> impl AsyncBufRead + Send + Sync
Converts the body into an async buffered reader.
This method wraps the body in a type that implements AsyncBufRead,
allowing it to be used anywhere that expects an async reader. This is
useful for streaming the body data to other async I/O operations.
§Examples
use http_kit::Body;
use futures_lite::AsyncBufReadExt;
let body = Body::from_bytes("line1\nline2\nline3");
let mut reader = body.into_reader();
let mut line = String::new();
reader.read_line(&mut line).await?;
assert_eq!(line, "line1\n");Sourcepub async fn as_bytes(&mut self) -> Result<&[u8], Error>
pub async fn as_bytes(&mut self) -> Result<&[u8], Error>
Returns a reference to the body data as bytes.
This method ensures the body data is available as a byte slice and returns a reference to it. For streaming bodies, this will consume and buffer all data in memory. The body is modified to store the buffered data internally.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("Hello, world!");
let bytes = body.as_bytes().await?;
assert_eq!(bytes, b"Hello, world!");Sourcepub async fn as_str(&mut self) -> Result<&str, Error>
pub async fn as_str(&mut self) -> Result<&str, Error>
Returns a reference to the body data as a UTF-8 string slice.
This method ensures the body data is available as a string slice and returns a reference to it. For streaming bodies, this will consume and buffer all data in memory first. The body is modified to store the buffered data internally.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
- The body contains invalid UTF-8 sequences
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("Hello, world!");
let text = body.as_str().await?;
assert_eq!(text, "Hello, world!");Sourcepub async fn into_json<'a, T>(&'a mut self) -> Result<T, Error>where
T: Deserialize<'a>,
pub async fn into_json<'a, T>(&'a mut self) -> Result<T, Error>where
T: Deserialize<'a>,
Deserializes the body data as JSON into the specified type.
This method reads the body data and attempts to deserialize it as JSON. The deserialization is performed with zero-copy when possible by working directly with the buffered byte data.
§Warning
This method does not validate the Content-Type header. If you need
MIME type validation, use Request::into_json() or Response::into_json()
instead, which check for the application/json content type.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
- The JSON is malformed or doesn’t match the target type
§Examples
use http_kit::Body;
use serde::Deserialize;
#[derive(Deserialize, PartialEq, Debug)]
struct User {
name: String,
age: u32,
}
let json_data = r#"{"name": "Alice", "age": 30}"#;
let mut body = Body::from_bytes(json_data);
let user: User = body.into_json().await?;
assert_eq!(user.name, "Alice");Sourcepub async fn into_form<'a, T>(&'a mut self) -> Result<T, Error>where
T: Deserialize<'a>,
pub async fn into_form<'a, T>(&'a mut self) -> Result<T, Error>where
T: Deserialize<'a>,
Deserializes the body data as URL-encoded form data into the specified type.
This method reads the body data and attempts to deserialize it as
application/x-www-form-urlencoded data. The deserialization is performed
with zero-copy when possible by working directly with the buffered byte data.
§Warning
This method does not validate the Content-Type header. If you need
MIME type validation, use Request::into_form() or Response::into_form()
instead, which check for the application/x-www-form-urlencoded content type.
§Errors
Returns an error if:
- The body is frozen (already consumed)
- An I/O error occurs while reading streaming data
- The form data is malformed or doesn’t match the target type
§Examples
use http_kit::Body;
use serde::Deserialize;
#[derive(Deserialize, PartialEq, Debug)]
struct LoginForm {
username: String,
password: String,
}
let form_data = "username=alice&password=secret123";
let mut body = Body::from_bytes(form_data);
let form: LoginForm = body.into_form().await?;
assert_eq!(form.username, "alice");Sourcepub fn replace(&mut self, body: Body) -> Body
pub fn replace(&mut self, body: Body) -> Body
Replaces this body with a new body and returns the old body.
This method swaps the current body with the provided body, returning the original body value. This can be useful for chaining operations or temporarily substituting body content.
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("original");
let old_body = body.replace(Body::from_bytes("replacement"));
// `body` now contains "replacement"
// `old_body` contains "original"Sourcepub fn swap(&mut self, body: &mut Body) -> Result<(), BodyFrozen>
pub fn swap(&mut self, body: &mut Body) -> Result<(), BodyFrozen>
Swaps the contents of this body with another body.
This method exchanges the contents of two bodies, provided that this body is not frozen. If the body is frozen (already consumed), the operation fails and returns an error.
§Errors
Returns BodyFrozen if this body has been frozen/consumed.
§Examples
use http_kit::Body;
let mut body1 = Body::from_bytes("first");
let mut body2 = Body::from_bytes("second");
body1.swap(&mut body2)?;
// Now body1 contains "second" and body2 contains "first"Sourcepub fn take(&mut self) -> Result<Self, BodyFrozen>
pub fn take(&mut self) -> Result<Self, BodyFrozen>
Consumes and takes the body, leaving a frozen body in its place.
This method extracts the body content and replaces it with a frozen (unusable) body. This is useful when you need to move the body to another location while ensuring the original cannot be used again.
§Errors
Returns BodyFrozen if the body is already frozen.
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("Hello, world!");
let taken_body = body.take()?;
// `taken_body` contains the original data
// `body` is now frozen and cannot be used
assert!(body.is_frozen());Sourcepub const fn is_frozen(&self) -> bool
pub const fn is_frozen(&self) -> bool
Returns true if the body is frozen (consumed), false otherwise.
A frozen body is one that has been consumed by operations like take()
and can no longer provide data. This is different from an empty body,
which still has a valid state but contains no data.
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("data");
assert!(!body.is_frozen());
let _taken = body.take().unwrap();
assert!(body.is_frozen());
let frozen = Body::frozen();
assert!(frozen.is_frozen());Sourcepub fn freeze(&mut self)
pub fn freeze(&mut self)
Freezes the body, making it unusable and dropping its content.
This method converts the body to a frozen state, discarding any data it contained. After freezing, the body cannot be used for any operations and will return errors if accessed.
§Examples
use http_kit::Body;
let mut body = Body::from_bytes("Hello, world!");
body.freeze();
assert!(body.is_frozen());
// Any further operations on `body` will failTrait Implementations§
Source§impl Stream for Body
impl Stream for Body
Auto Trait Implementations§
impl !Freeze for Body
impl !RefUnwindSafe for Body
impl Send for Body
impl Sync for Body
impl Unpin for Body
impl !UnwindSafe for Body
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<S> StreamExt for S
impl<S> StreamExt for S
Source§fn next(&mut self) -> NextFuture<'_, Self> ⓘwhere
Self: Unpin,
fn next(&mut self) -> NextFuture<'_, Self> ⓘwhere
Self: Unpin,
Source§fn try_next<T, E>(&mut self) -> TryNextFuture<'_, Self> ⓘ
fn try_next<T, E>(&mut self) -> TryNextFuture<'_, Self> ⓘ
Source§fn count(self) -> CountFuture<Self> ⓘwhere
Self: Sized,
fn count(self) -> CountFuture<Self> ⓘwhere
Self: Sized,
Source§fn map<T, F>(self, f: F) -> Map<Self, F>
fn map<T, F>(self, f: F) -> Map<Self, F>
Source§fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
Source§fn then<F, Fut>(self, f: F) -> Then<Self, F, Fut>
fn then<F, Fut>(self, f: F) -> Then<Self, F, Fut>
Source§fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
Source§fn take(self, n: usize) -> Take<Self>where
Self: Sized,
fn take(self, n: usize) -> Take<Self>where
Self: Sized,
n items of the stream. Read moreSource§fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
Source§fn skip(self, n: usize) -> Skip<Self>where
Self: Sized,
fn skip(self, n: usize) -> Skip<Self>where
Self: Sized,
n items of the stream. Read moreSource§fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
Source§fn step_by(self, step: usize) -> StepBy<Self>where
Self: Sized,
fn step_by(self, step: usize) -> StepBy<Self>where
Self: Sized,
stepth item. Read moreSource§fn chain<U>(self, other: U) -> Chain<Self, U>
fn chain<U>(self, other: U) -> Chain<Self, U>
Source§fn collect<C>(self) -> CollectFuture<Self, C> ⓘ
fn collect<C>(self) -> CollectFuture<Self, C> ⓘ
Source§fn try_collect<T, E, C>(self) -> TryCollectFuture<Self, C> ⓘ
fn try_collect<T, E, C>(self) -> TryCollectFuture<Self, C> ⓘ
Source§fn partition<B, P>(self, predicate: P) -> PartitionFuture<Self, P, B> ⓘ
fn partition<B, P>(self, predicate: P) -> PartitionFuture<Self, P, B> ⓘ
predicate is true and those for which it is
false, and then collects them into two collections. Read moreSource§fn fold<T, F>(self, init: T, f: F) -> FoldFuture<Self, F, T> ⓘ
fn fold<T, F>(self, init: T, f: F) -> FoldFuture<Self, F, T> ⓘ
Source§fn try_fold<T, E, F, B>(
&mut self,
init: B,
f: F,
) -> TryFoldFuture<'_, Self, F, B> ⓘ
fn try_fold<T, E, F, B>( &mut self, init: B, f: F, ) -> TryFoldFuture<'_, Self, F, B> ⓘ
Source§fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
Source§fn enumerate(self) -> Enumerate<Self>where
Self: Sized,
fn enumerate(self) -> Enumerate<Self>where
Self: Sized,
(index, item). Read moreSource§fn inspect<F>(self, f: F) -> Inspect<Self, F>
fn inspect<F>(self, f: F) -> Inspect<Self, F>
Source§fn nth(&mut self, n: usize) -> NthFuture<'_, Self> ⓘwhere
Self: Unpin,
fn nth(&mut self, n: usize) -> NthFuture<'_, Self> ⓘwhere
Self: Unpin,
nth item of the stream. Read moreSource§fn last(self) -> LastFuture<Self> ⓘwhere
Self: Sized,
fn last(self) -> LastFuture<Self> ⓘwhere
Self: Sized,
Source§fn find<P>(&mut self, predicate: P) -> FindFuture<'_, Self, P> ⓘ
fn find<P>(&mut self, predicate: P) -> FindFuture<'_, Self, P> ⓘ
Source§fn find_map<F, B>(&mut self, f: F) -> FindMapFuture<'_, Self, F> ⓘ
fn find_map<F, B>(&mut self, f: F) -> FindMapFuture<'_, Self, F> ⓘ
Source§fn position<P>(&mut self, predicate: P) -> PositionFuture<'_, Self, P> ⓘ
fn position<P>(&mut self, predicate: P) -> PositionFuture<'_, Self, P> ⓘ
Source§fn for_each<F>(self, f: F) -> ForEachFuture<Self, F> ⓘ
fn for_each<F>(self, f: F) -> ForEachFuture<Self, F> ⓘ
Source§fn try_for_each<F, E>(&mut self, f: F) -> TryForEachFuture<'_, Self, F> ⓘ
fn try_for_each<F, E>(&mut self, f: F) -> TryForEachFuture<'_, Self, F> ⓘ
Source§fn zip<U>(self, other: U) -> Zip<Self, U>
fn zip<U>(self, other: U) -> Zip<Self, U>
Source§fn unzip<A, B, FromA, FromB>(self) -> UnzipFuture<Self, FromA, FromB> ⓘ
fn unzip<A, B, FromA, FromB>(self) -> UnzipFuture<Self, FromA, FromB> ⓘ
Source§fn race<S>(self, other: S) -> Race<Self, S>
fn race<S>(self, other: S) -> Race<Self, S>
other stream, with no preference for either stream when both are ready. Read more