Skip to main content

HttpBodyBuilder

Struct HttpBodyBuilder 

Source
pub struct HttpBodyBuilder { /* private fields */ }
Expand description

Builder for creating optimized HTTP bodies.

This builder optimizes memory usage and performance for HTTP bodies by providing:

  • Memory pooling for better performance
  • Runtime-specific optimizations
  • Easier testing with the test-util feature

§Examples

// Create different body types
let text_body: HttpBody = builder.text("Hello world");
let empty_body: HttpBody = builder.empty();
let binary_body: HttpBody = builder.slice(&[1, 2, 3, 4]);

§Testing

With the test-util feature enabled, you can create a test instance using HttpBodyBuilder::new_fake().

Implementations§

Source§

impl HttpBodyBuilder

Source

pub fn new_fake() -> HttpBodyBuilder

Creates a test-friendly HttpBodyBuilder instance.

Useful for unit tests. Available with the test-util feature, this allows creating and working with HTTP bodies without any real network or server setup.

Uses a frozen clock, so body data receive timeouts will never fire.

§Examples
let builder = HttpBodyBuilder::new_fake();
let text_body = builder.text("Test content");
Source

pub fn new(memory: GlobalPool, clock: &Clock) -> HttpBodyBuilder

Creates a new instance of HttpBodyBuilder.

This method uses a per-thread memory pool from GlobalPool.

Source

pub fn with_custom_memory( memory: impl MemoryShared, clock: &Clock, ) -> HttpBodyBuilder

Creates a new instance of HttpBodyBuilder with custom memory.

When using this method, the memory is shared across all threads as opposed to the global per-thread memory used by HttpBodyBuilder::new.

Source

pub fn with_options(self, options: HttpBodyOptions) -> HttpBodyBuilder

Sets default HttpBodyOptions for all bodies created by this builder.

Per-call options passed to body or stream are merged on top: the per-call value wins when both sides set the same field.

Source

pub fn body<B>(&self, body: B, options: &HttpBodyOptions) -> HttpBody
where B: Body<Data = BytesView> + Send + 'static, <B as Body>::Error: Into<HttpError>,

Creates an HttpBody from any body implementation.

Use this to integrate custom types that implement http_body::Body with the HttpBody system. Useful for third-party libraries or your own custom body implementations.

When options contains a timeout, the body is wrapped with an idle timeout that limits how long the body may go without yielding a frame.

§Examples
// Your custom body type
struct CustomBody(Vec<u8>);

impl Body for CustomBody {
    type Data = BytesView;
    type Error = HttpError;

    fn poll_frame(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
        // Implementation details...
        Poll::Ready(None)
    }
}

// Create HttpBody from your custom body
let custom_body = CustomBody(vec![1, 2, 3, 4]);
let body = builder.body(custom_body, &HttpBodyOptions::default());
Source

pub fn stream<S>(&self, stream: S, options: &HttpBodyOptions) -> HttpBody
where S: Stream<Item = Result<BytesView, HttpError>> + Send + 'static,

Creates a body from a stream of byte chunks.

Accepts a Stream of BytesView chunks and creates a streaming body from them.

When options contains a timeout, the stream is wrapped with an idle timeout that limits how long the body may go without yielding a frame.

§Examples
let chunks = vec![
    Ok(BytesView::copied_from_slice(b"hello ", &builder)),
    Ok(BytesView::copied_from_slice(b"world", &builder)),
];
let body = builder.stream(futures::stream::iter(chunks), &HttpBodyOptions::default());

assert_eq!(body.content_length(), None); // unknown length for streams
Source

pub fn text(&self, str: impl AsRef<str>) -> HttpBody

Creates a body from text.

Works with both string literals and String types.

§Examples
let body1 = builder.text("Hello, world!"); // From &str
let body2 = builder.text(String::from("Hello, world!")); // From String

assert_eq!(body1.content_length(), body2.content_length());
Source

pub fn slice(&self, data: impl AsRef<[u8]>) -> HttpBody

Creates a body from a slice of bytes.

Use this when you have a single slice of raw bytes that needs to be sent in a request or response.

§Performance

This will copy the contents of the byte slice. For more efficiency, you should consider using bytes().

§Examples
// "Hello" in ASCII
let data = [0x48, 0x65, 0x6C, 0x6C, 0x6F];
let body = builder.slice(&data);

assert_eq!(body.content_length(), Some(5));
Source

pub fn bytes(&self, b: impl Into<BytesView>) -> HttpBody

Creates a body from an existing BytesView.

Use this when you already have a BytesView and want to use it as an HTTP body.

§Performance

This method does not copy the contents of the BytesView, providing greater efficiency compared to slice().

§Examples
// Create a body from existing bytes of data
let body = builder.bytes(BytesView::new());
assert_eq!(body.content_length(), Some(0));
Source

pub fn empty(&self) -> HttpBody

Creates an empty body (zero bytes).

Use this for HTTP methods that don’t need a body like GET or HEAD requests, or for responses that only need status codes or headers.

Source

pub fn json<T>(&self, data: &T) -> Result<HttpBody, JsonError>
where T: Serialize,

Creates a body from a JSON-serializable value.

Automatically handles serialization and creates an HTTP body ready to send. Available with the json feature.

§Errors

Returns an error if the JSON serialization fails.

§Examples
#[derive(Serialize)]
struct User {
    id: u32,
    name: String,
}

let user = User {
    id: 1,
    name: String::from("Alice"),
};

// Create a body containing the JSON representation of user
let body = builder.json(&user)?;

Trait Implementations§

Source§

impl AsRef<Clock> for HttpBodyBuilder

Source§

fn as_ref(&self) -> &Clock

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<HttpBodyBuilder> for HttpClient

Source§

fn as_ref(&self) -> &HttpBodyBuilder

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for HttpBodyBuilder

Source§

fn clone(&self) -> HttpBodyBuilder

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpBodyBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl HasMemory for HttpBodyBuilder

Source§

fn memory(&self) -> impl MemoryShared

Returns a sharing-compatible memory provider. Read more
Source§

impl Memory for HttpBodyBuilder

Source§

fn reserve(&self, min_bytes: usize) -> BytesBuf

Reserves at least min_bytes bytes of memory capacity. Read more
Source§

impl ThreadAware for HttpBodyBuilder

Source§

fn relocate(&mut self, source: Option<Affinity>, destination: Affinity)

Relocate this value in place to the destination affinity. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> MemoryShared for T
where T: Memory + Send + Sync + 'static,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more