ReadableStream

Struct ReadableStream 

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

A readable stream representing request or response body data.

ReadableStream provides a unified interface for handling different types of body content in HTTP requests and responses. It follows the WHATWG Fetch specification for body handling, including the “used” flag to prevent multiple consumption of the same body.

§Body Consumption

Each body can only be consumed once. After calling any of the consumption methods (text(), json(), array_buffer(), etc.), the body is marked as used and subsequent calls will return an error.

§Examples

use fetchttp::ReadableStream;

// Create and consume a text body
let stream = ReadableStream::from_text("Hello, World!");
let text = stream.text().await.unwrap();
assert_eq!(text, "Hello, World!");

// Create and consume a JSON body
let data = serde_json::json!({"name": "John", "age": 30});
let stream = ReadableStream::from_json(&data);
let parsed: serde_json::Value = stream.json().await.unwrap();
assert_eq!(parsed["name"], "John");

Implementations§

Source§

impl ReadableStream

Source

pub fn empty() -> Self

Create an empty readable stream.

§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::empty();
let text = stream.text().await.unwrap();
assert_eq!(text, "");
Source

pub fn from_text(text: &str) -> Self

Create a readable stream from text content.

The text will be encoded as UTF-8 when converted to bytes.

§Arguments
  • text - The text content for the stream
§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_text("Hello, World!");
let content = stream.text().await.unwrap();
assert_eq!(content, "Hello, World!");
Source

pub fn from_bytes(bytes: Bytes) -> Self

Create a readable stream from binary data.

§Arguments
  • bytes - The binary data for the stream
§Examples
use fetchttp::ReadableStream;
use bytes::Bytes;

let data = Bytes::from(b"binary data".to_vec());
let stream = ReadableStream::from_bytes(data);
let bytes = stream.array_buffer().await.unwrap();
assert_eq!(bytes, b"binary data");
Source

pub fn from_json(value: &Value) -> Self

Create a readable stream from JSON data.

The JSON value will be serialized when the stream is consumed. This automatically sets the appropriate content type for HTTP requests.

§Arguments
  • value - The JSON value for the stream
§Examples
use fetchttp::ReadableStream;
use serde_json::json;

let data = json!({"name": "Alice", "age": 25});
let stream = ReadableStream::from_json(&data);
let parsed: serde_json::Value = stream.json().await.unwrap();
assert_eq!(parsed["name"], "Alice");
Source

pub fn locked(&self) -> bool

Check if the stream is locked.

In this implementation, streams are never locked as we don’t support multiple readers. This method exists for WHATWG Fetch API compatibility.

§Returns

Always returns false in this implementation.

§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_text("test");
assert!(!stream.locked());
Source

pub async fn array_buffer(self) -> Result<Bytes>

Consume the stream and return the content as bytes.

This method consumes the entire stream and returns the content as a Bytes object. After calling this method, the stream is marked as used.

§Returns

The stream content as bytes, or an error if the stream was already used or if serialization fails.

§Errors
  • TypeError - If the stream was already used or JSON serialization fails
§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_text("Hello");
let bytes = stream.array_buffer().await.unwrap();
assert_eq!(bytes, b"Hello");
Source

pub async fn blob(self) -> Result<Bytes>

Consume the stream and return the content as a blob (bytes).

This is an alias for array_buffer() and exists for WHATWG Fetch API compatibility. In web browsers, blobs and array buffers are different, but in this implementation they are the same.

§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_bytes(b"data".to_vec().into());
let blob = stream.blob().await.unwrap();
assert_eq!(blob, b"data");
Source

pub async fn form_data(self) -> Result<String>

Consume the stream and return the content as form data.

Currently this is implemented as an alias for text() since we don’t have specialized form data parsing. This exists for WHATWG Fetch API compatibility.

§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_text("key=value&foo=bar");
let form_data = stream.form_data().await.unwrap();
assert_eq!(form_data, "key=value&foo=bar");
Source

pub async fn json<T: DeserializeOwned>(self) -> Result<T>

Consume the stream and parse the content as JSON.

This method deserializes the stream content as JSON into the specified type. The type must implement serde::de::DeserializeOwned.

§Type Parameters
  • T - The type to deserialize the JSON into
§Returns

The deserialized JSON data, or an error if the stream was already used or if JSON parsing fails.

§Errors
  • TypeError - If the stream was already used or JSON parsing fails
§Examples
use fetchttp::ReadableStream;
use serde_json::json;
use serde::Deserialize;

#[derive(Deserialize, Debug, PartialEq)]
struct User {
    name: String,
    age: u32,
}

let data = json!({"name": "Alice", "age": 30});
let stream = ReadableStream::from_json(&data);

let user: User = stream.json().await.unwrap();
assert_eq!(user.name, "Alice");
assert_eq!(user.age, 30);
Source

pub async fn text(self) -> Result<String>

Consume the stream and return the content as text.

This method consumes the entire stream and returns the content as a UTF-8 string. For binary data, this will attempt UTF-8 decoding.

§Returns

The stream content as a string, or an error if the stream was already used or if UTF-8 decoding fails.

§Errors
  • TypeError - If the stream was already used or UTF-8 decoding fails
§Examples
use fetchttp::ReadableStream;

let stream = ReadableStream::from_text("Hello, World!");
let text = stream.text().await.unwrap();
assert_eq!(text, "Hello, World!");

Trait Implementations§

Source§

impl Clone for ReadableStream

Source§

fn clone(&self) -> ReadableStream

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ReadableStream

Source§

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

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

impl From<&str> for ReadableStream

Source§

fn from(text: &str) -> Self

Converts to this type from the input type.
Source§

impl From<Bytes> for ReadableStream

Source§

fn from(bytes: Bytes) -> Self

Converts to this type from the input type.
Source§

impl From<String> for ReadableStream

Source§

fn from(text: String) -> Self

Converts to this type from the input type.
Source§

impl From<Value> for ReadableStream

Source§

fn from(value: Value) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for ReadableStream

Source§

fn from(bytes: Vec<u8>) -> Self

Converts to this type from the input type.

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> 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> 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