Struct WebSocket

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

WebSocket stream for both clients and servers.

The WebSocket struct manages all aspects of WebSocket communication, handling mandatory frames (close, ping, and pong frames) and protocol compliance checks. It abstracts away details related to framing and compression, which are managed by the underlying ReadHalf and WriteHalf structures.

A WebSocket instance can be created via high-level functions like WebSocket::connect, or through a custom stream setup with WebSocket::handshake.

§Connecting

To establish a WebSocket connection as a client:

use tokio::net::TcpStream;
use yawc::{WebSocket, frame::OpCode};
use futures::StreamExt;
use tokio_rustls::TlsConnector;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let ws = WebSocket::connect("wss://echo.websocket.org".parse()?).await?;
    // Use `ws` for WebSocket communication
    Ok(())
}

§Ping and Pong Handling as a Client

When acting as a client, if a Ping frame is received from the server, WebSocket automatically replies with a Pong frame. However, the Ping frame is still made available to the user before the automatic response:

use tokio::net::TcpStream;
use yawc::{WebSocket, frame::OpCode};
use futures::StreamExt;

async fn client_loop(mut ws: WebSocket) -> anyhow::Result<()> {
    while let Some(frame) = ws.next().await {
        match frame.opcode {
            OpCode::Ping => {
                let ping_text = std::str::from_utf8(&frame.payload).unwrap();
                println!("Received ping with text: {ping_text}");
                // The WebSocket automatically sends a Pong in response
            }
            _ => {}
        }
    }

    Ok(())
}

§Splitting the WebSocket

For concurrent reading and writing operations, use futures::StreamExt::split from the futures crate, which maintains all WebSocket protocol handling while enabling simultaneous reads and writes. This is the recommended approach for most concurrent WebSocket operations.

In contrast, WebSocket::split_stream is a low-level API that bypasses critical WebSocket protocol management and should rarely be used directly. It disables automatic control frame handling (like Ping/Pong), connection health monitoring, and other protocol-level features. Only use this method if you need direct access to the underlying frame processing and are prepared to handle all protocol requirements manually.

After calling WebSocket::split_stream, you get direct access to the raw ReadHalf and WriteHalf components, as well as the underlying HttpStream for direct stream access. Read more about their behavior in their respective documentation.

Implementations§

Source§

impl WebSocket

Source

pub fn connect(url: Url) -> WebSocketBuilder

Establishes a WebSocket connection to the specified url.

This asynchronous function supports both ws:// (non-secure) and wss:// (secure) schemes, allowing for secure WebSocket connections when needed. For secure connections, a default TLS configuration will be used.

§Parameters
  • url: The WebSocket URL to connect to. This can include both ws and wss schemes.
§Returns

A Result containing either a connected WebSocket instance or an error if the connection could not be established.

§Examples
use yawc::WebSocket;

#[tokio::main]
async fn main() -> yawc::Result<()> {
   let ws = WebSocket::connect("wss://echo.websocket.org".parse()?).await?;
   // Use `ws` to send and receive messages
   Ok(())
}
§Errors

This function will return an error if:

  • The URL provided is invalid or not a WebSocket URL.
  • A network or TLS error occurs while trying to establish the connection.
§Notes
  • By default, no custom options are applied during the connection process. Use Options::default() for standard WebSocket behavior.
  • For secure connections requiring custom TLS settings, use WebSocketBuilder::with_connector() instead.
Source

pub async fn handshake<S: AsyncWrite + AsyncRead + Send + Unpin + 'static>( url: Url, io: S, options: Options, ) -> Result<WebSocket>

Performs a WebSocket handshake over an existing connection.

This asynchronous function establishes a WebSocket connection by performing the handshake with a pre-existing TCP stream or similar I/O type. It can be used when an active connection to a server exists, bypassing the need to initiate a new connection for the WebSocket.

§Parameters
  • url: The WebSocket URL to connect to, which should specify either ws or wss scheme.
  • io: An I/O stream that implements AsyncWrite and AsyncRead, allowing WebSocket communication over this stream after the handshake completes. Typically, this is a TcpStream.
  • options: Options to configure the WebSocket connection, such as compression and ping intervals.
§Returns

A Result containing either an initialized WebSocket instance upon successful handshake or an error if the handshake fails.

§Examples
use tokio::net::TcpStream;
use yawc::{WebSocket, Result, Options};

async fn handle_client(
    url: url::Url,
    socket: TcpStream,
) -> Result<()> {
    let mut ws = WebSocket::handshake(url, socket, Options::default()).await?;
    // Use `ws` to send and receive messages after a successful handshake
    Ok(())
}
§Errors

This function may return an error if:

  • The URL provided is invalid or does not specify a WebSocket URL.
  • The handshake response does not meet WebSocket protocol requirements (e.g., missing required headers).
  • A network or I/O error occurs during the handshake process.
§Notes
  • The function handles setting up necessary WebSocket headers, including Host, Upgrade, Connection, Sec-WebSocket-Key, and Sec-WebSocket-Version.
  • If compression is enabled via Options, it will be negotiated as part of the handshake.
§Usage

This function is useful when handling WebSocket connections with existing streams, such as when managing multiple connections in a server context.

Source

pub async fn handshake_with_request<S: AsyncWrite + AsyncRead + Send + Unpin + 'static>( url: Url, io: S, options: Options, builder: HttpRequestBuilder, ) -> Result<WebSocket>

Performs a WebSocket handshake with a customizable HTTP request.

This method extends the basic handshake functionality by allowing you to provide a custom HTTP request builder, which can be used to set additional headers or customize the request before performing the WebSocket handshake.

§Parameters
  • url: The WebSocket URL to connect to
  • io: The I/O stream to use for the WebSocket connection
  • options: Configuration options for the WebSocket connection
  • builder: A custom HTTP request builder for customizing the handshake request
§Returns

A Result containing the established WebSocket connection if successful

§Example
use yawc::{WebSocket, Options, Result};
use tokio::net::TcpStream;

async fn connect() -> Result<WebSocket> {
    let stream = TcpStream::connect("example.com:80").await.unwrap();
    let builder = yawc::HttpRequest::builder()
        .header("User-Agent", "My Custom WebSocket Client")
        .header("Authorization", "Bearer token123");

    WebSocket::handshake_with_request(
        "ws://example.com/socket".parse().unwrap(),
        stream,
        Options::default(),
        builder
    ).await
}
Source

pub async fn reqwest( url: Url, client: Client, options: Options, ) -> Result<WebSocket>

Available on crate feature reqwest only.

Performs a WebSocket handshake when using the reqwest HTTP client.

This function is only available when the reqwest feature is enabled. It provides WebSocket handshake functionality using the reqwest::Client for HTTP request handling and connection management.

§Parameters
  • url: The WebSocket URL to connect to, supporting both ws and wss schemes.
  • client: A configured reqwest::Client instance that will be used to initiate the connection.
  • options: Options for configuring connection behavior like compression and payload limits.
§Returns

A Result containing either a connected WebSocket instance or an error if the handshake fails.

§Example
use reqwest::Client;
use yawc::{WebSocket, Options, Result};

async fn connect_ws(url: String) -> Result<()> {
    let client = Client::new();
    let ws = WebSocket::reqwest(
        url.parse()?,
        client,
        Options::default()
    ).await?;

    // Use WebSocket for communication
    Ok(())
}
§Notes
  • This function requires the reqwest feature to be enabled in your Cargo.toml
  • Handles WebSocket protocol negotiation including compression if configured
Source

pub fn upgrade<B>(request: impl BorrowMut<Request<B>>) -> UpgradeResult

Upgrades an HTTP connection to a WebSocket one.

Validates incoming HTTP request headers and handles protocol switching to establish a WebSocket connection. Returns a response to be sent back to the client and a future that will resolve into the WebSocket stream.

The response must be sent to the client before the upgrade future is awaited. Verification of headers like Origin, Sec-WebSocket-Protocol and Sec-WebSocket-Extensions is left to the caller.

Note: Connection and Upgrade headers must be validated separately. You can use header inspection to confirm this is a valid WebSocket upgrade request.

§Parameters
  • request: The incoming HTTP request to upgrade
§Returns

Returns a tuple containing:

  • Response with SWITCHING_PROTOCOLS status to send back
  • UpgradeFut that resolves to the WebSocket stream
§Example
use hyper::{
    body::{Bytes, Incoming},
    server::conn::http1,
    service::service_fn,
    Request, Response,
};
use yawc::{Result, WebSocket, UpgradeFut, Options};

async fn handle_client(fut: UpgradeFut) -> yawc::Result<()> {
    let ws = fut.await?;
    Ok(())
}

async fn server_upgrade(mut req: Request<Incoming>) -> anyhow::Result<yawc::HttpResponse> {
    let (response, fut) = WebSocket::upgrade_with_options(
        &mut req,
        Options::default()
    )?;

    tokio::task::spawn(async move {
        if let Err(e) = handle_client(fut).await {
            eprintln!("Error in websocket connection: {}", e);
        }
    });

    Ok(response)
}
§Errors

Returns error if:

  • Sec-WebSocket-Key header is missing
  • Sec-WebSocket-Version is not “13”
Source

pub fn upgrade_with_options<B>( request: impl BorrowMut<Request<B>>, options: Options, ) -> UpgradeResult

Attempts to upgrade an incoming hyper::Request to a WebSocket connection with customizable options.

Similar to WebSocket::upgrade, this function verifies the required WebSocket headers and, if successful, returns an HTTP response to switch protocols along with an upgrade future for the WebSocket stream. Additionally, it applies the specified options, which may define parameters such as compression settings, UTF-8 validation, and maximum payload size.

§Parameters
  • request: A mutable reference to the HTTP request to upgrade.
  • options: Options that define parameters for the WebSocket connection, including compression and payload limits.
§Returns

A Result containing:

  • A Response with SWITCHING_PROTOCOLS status, which should be sent to the client.
  • An UpgradeFut future that resolves to the WebSocket stream once the response is sent.
§Notes
  • options.compression: If enabled and supported by both client and server, the WebSocket connection will use compression.
  • options.max_payload_read: Specifies the maximum size for received messages.
  • The upgrade request must be verified for WebSocket headers before calling this function, as it does not inspect Connection or Upgrade headers.
§Example
use hyper::{Request, body::Incoming};
use yawc::{Result, WebSocket, Options};

async fn handle_websocket_with_options(request: Request<Incoming>) -> Result<()> {
    let options = Options::default();
    let (response, upgrade) = WebSocket::upgrade_with_options(request, options)?;
    // Send `response` back to client, then await `upgrade` for WebSocket stream
    Ok(())
}
§Errors

This function returns an error if:

  • The Sec-WebSocket-Key header is missing.
  • The Sec-WebSocket-Version header is not set to “13”.
Source

pub unsafe fn split_stream( self, ) -> (Framed<HttpStream, Codec>, ReadHalf, WriteHalf)

Splits the WebSocket into its low-level components for advanced usage.

This method breaks down the WebSocket into three parts:

  • Framed<HttpStream, Codec>: The raw stream with codec for handling WebSocket frames
  • ReadHalf: Low-level component for receiving and processing frames
  • WriteHalf: Low-level component for sending frames
§Safety

This function is unsafe because:

  • It splits ownership of shared state between components without synchronization
  • You must ensure proper coordination between the split halves to maintain protocol correctness
  • Misuse of the split components can cause protocol violations or memory corruption
  • Manual management of component lifetimes is required to prevent use-after-free
§Warning

This is a low-level API that should rarely be used directly. For most concurrent read/write use cases, use StreamExt::split instead, which preserves the WebSocket’s built-in protocol handling while enabling concurrent access.

Using this method bypasses critical WebSocket protocol management:

  • Automatic Ping/Pong frame handling stops working
  • Connection health monitoring is disabled
  • Protocol compliance becomes your responsibility

Direct use of this API requires deep understanding of:

  • WebSocket protocol details including control frame handling
  • Proper bidirectional communication management
  • Connection health monitoring implementations
  • Thread safety and synchronization for concurrent access
§Returns

A tuple of the raw frame-handling stream and the read/write components.

§Example
use yawc::WebSocket;

async fn connect() -> yawc::Result<()> {
    let ws = WebSocket::connect("ws://example.com/ws".parse()?).await?;
    // Advanced usage - requires manual protocol handling
    let (raw_stream, read_half, write_half) = unsafe { ws.split_stream() };
    // Must implement control frame handling, connection monitoring etc.
    Ok(())
}
Source

pub fn poll_next_frame( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<FrameView>>

Polls for the next frame in the WebSocket stream and handles protocol-level concerns.

This method manages asynchronous frame retrieval and ensures proper protocol handling, including connection cleanup, frame validation, and error responses.

§Protocol Flow
  1. Polls underlying stream for next frame
  2. For received frames:
    • Processes and returns valid frames
    • Sends appropriate close frame for protocol violations
    • Flushes pending frames before connection closure
  3. Begins cleanup when connection is closed
§Frame Handling
  • Valid frames are processed and returned for application use
  • Protocol violations trigger graceful shutdown with appropriate status code
  • Control frames (ping/pong/close) receive special handling
  • Fragmented messages are reassembled before delivery
§Error Responses
§Parameters
  • cx: Task context for managing asynchronous polling
§Returns
  • Poll::Ready(Ok(Frame)): Successfully received and processed frame
  • Poll::Ready(Err(WebSocketError)): Protocol violation or other error
  • Poll::Pending: More data needed for complete frame
Source

pub async fn next_frame(&mut self) -> Result<FrameView>

Helper function to asynchronously retrieve the next frame from the WebSocket stream.

This is a convenience wrapper around WebSocket::poll_next_frame that uses poll_fn to convert the polling interface into an async/await interface. It allows users to simply await the next frame rather than manually handling polling.

§Returns
  • Ok(Frame) if a frame was successfully received
  • Err(WebSocketError) if an error occurred while receiving the frame
Source

pub async fn send_json<T: Serialize>(&mut self, data: &T) -> Result<()>

Available on crate feature json only.

Serializes data to JSON and sends it as a text frame over the WebSocket.

This method takes a reference to data, serializes it to JSON, and sends it as a text frame over the WebSocket connection. The method is only available when the json feature is enabled.

§Type Parameters
  • T: The type of data to serialize. Must implement serde::Serialize.
§Parameters
  • data: Reference to the data to serialize and send.
§Returns
  • Ok(()) if the data was successfully serialized and sent.
  • Err if there was an error serializing the data or sending the frame.
§Feature

This method requires the json feature to be enabled in your Cargo.toml:

[dependencies]
yawc = { version = "0.1", features = ["json"] }

Trait Implementations§

Source§

impl Sink<FrameView> for WebSocket

Source§

fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Checks if the WebSocket is ready to send a frame.

This method first flushes any obligated frames, ensuring that pending data is sent before allowing new frames to be added. If the flush is successful, it polls the readiness of the write_half to send the next frame.

§Parameters
  • cx: The current task’s execution context, used to manage asynchronous polling.
§Returns
  • Poll::Ready(Ok(())) if the WebSocket is ready to send.
  • Poll::Pending if the WebSocket is not yet ready.
Source§

fn start_send(self: Pin<&mut Self>, item: FrameView) -> Result<(), Self::Error>

Begins sending a frame to the WebSocket.

Adds the specified frame to the write_half for transmission. This method does not immediately send the frame; it merely prepares the frame for sending.

§Parameters
  • item: The Frame to be sent.
§Returns
  • Ok(()) if the frame was successfully prepared for sending.
  • Err(WebSocketError) if an error occurs while preparing the frame.
Source§

fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Polls to flush all pending frames in the WebSocket stream.

Ensures that any frames waiting to be sent are fully flushed to the network.

§Parameters
  • cx: The current task’s execution context, used to manage asynchronous polling.
§Returns
  • Poll::Ready(Ok(())) if all pending frames have been flushed.
  • Poll::Pending if there are still frames waiting to be flushed.
Source§

fn poll_close( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Polls the connection to close the WebSocket stream.

Initiates a graceful shutdown of the WebSocket by sending a close frame. This method will attempt to complete any pending frame transmissions before closing the connection.

§Parameters
  • cx: The current task’s execution context, used to manage asynchronous polling.
§Returns
  • Poll::Ready(Ok(())) if the WebSocket is successfully closed.
  • Poll::Pending if the close process is still in progress.
Source§

type Error = WebSocketError

The type of value produced by the sink when an error occurs.
Source§

impl Stream for WebSocket

Source§

fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Self::Item>>

Polls for the next frame from the WebSocket stream.

If the you want to receive the Result of reading from the WebSocket, use WebSocket::poll_next_frame instead.

This method handles asynchronous frame retrieval, managing both connection closure and frame-specific protocol compliance checks.

The method will return None when the WebSocket connection has been closed, signaling the end of the stream. In most cases, WebSocket will complete any pending obligations and flush frames before fully terminating the connection.

§Parameters
  • cx: The current task’s execution context, used to manage asynchronous polling.
§Returns
  • Poll::Ready(Some(Frame)) if a frame is successfully received.
  • Poll::Ready(None) if the connection is closed, indicating no more frames will be received.
Source§

type Item = FrameView

Values yielded by the stream.
Source§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. 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> 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, Item> SinkExt<Item> for T
where T: Sink<Item> + ?Sized,

Source§

fn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F>
where F: FnMut(U) -> Fut, Fut: Future<Output = Result<Item, E>>, E: From<Self::Error>, Self: Sized,

Composes a function in front of the sink. Read more
Source§

fn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F>
where F: FnMut(U) -> St, St: Stream<Item = Result<Item, Self::Error>>, Self: Sized,

Composes a function in front of the sink. Read more
Source§

fn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F>
where F: FnOnce(Self::Error) -> E, Self: Sized,

Transforms the error returned by the sink.
Source§

fn sink_err_into<E>(self) -> SinkErrInto<Self, Item, E>
where Self: Sized, Self::Error: Into<E>,

Map this sink’s error to a different error type using the Into trait. Read more
Source§

fn buffer(self, capacity: usize) -> Buffer<Self, Item>
where Self: Sized,

Adds a fixed-size buffer to the current sink. Read more
Source§

fn close(&mut self) -> Close<'_, Self, Item>
where Self: Unpin,

Close the sink.
Source§

fn fanout<Si>(self, other: Si) -> Fanout<Self, Si>
where Self: Sized, Item: Clone, Si: Sink<Item, Error = Self::Error>,

Fanout items to multiple sinks. Read more
Source§

fn flush(&mut self) -> Flush<'_, Self, Item>
where Self: Unpin,

Flush the sink, processing all pending items. Read more
Source§

fn send(&mut self, item: Item) -> Send<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been fully processed into the sink, including flushing. Read more
Source§

fn feed(&mut self, item: Item) -> Feed<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been received by the sink. Read more
Source§

fn send_all<'a, St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St>
where St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized, Self: Unpin,

A future that completes after the given stream has been fully processed into the sink, including flushing. Read more
Source§

fn left_sink<Si2>(self) -> Either<Self, Si2>
where Si2: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this sink in an Either sink, making it the left-hand variant of that Either. Read more
Source§

fn right_sink<Si1>(self) -> Either<Si1, Self>
where Si1: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this stream in an Either stream, making it the right-hand variant of that Either. Read more
Source§

fn poll_ready_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_ready on Unpin sink types.
Source§

fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error>
where Self: Unpin,

A convenience method for calling Sink::start_send on Unpin sink types.
Source§

fn poll_flush_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_flush on Unpin sink types.
Source§

fn poll_close_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_close on Unpin sink types.
Source§

impl<T> StreamExt for T
where T: Stream + ?Sized,

Source§

fn next(&mut self) -> Next<'_, Self>
where Self: Unpin,

Creates a future that resolves to the next item in the stream. Read more
Source§

fn into_future(self) -> StreamFuture<Self>
where Self: Sized + Unpin,

Converts this stream into a future of (next_item, tail_of_stream). If the stream terminates, then the next item is None. Read more
Source§

fn map<T, F>(self, f: F) -> Map<Self, F>
where F: FnMut(Self::Item) -> T, Self: Sized,

Maps this stream’s items to a different type, returning a new stream of the resulting type. Read more
Source§

fn enumerate(self) -> Enumerate<Self>
where Self: Sized,

Creates a stream which gives the current iteration count as well as the next value. Read more
Source§

fn filter<Fut, F>(self, f: F) -> Filter<Self, Fut, F>
where F: FnMut(&Self::Item) -> Fut, Fut: Future<Output = bool>, Self: Sized,

Filters the values produced by this stream according to the provided asynchronous predicate. Read more
Source§

fn filter_map<Fut, T, F>(self, f: F) -> FilterMap<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future<Output = Option<T>>, Self: Sized,

Filters the values produced by this stream while simultaneously mapping them to a different type according to the provided asynchronous closure. Read more
Source§

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future, Self: Sized,

Computes from this stream’s items new items of a different type using an asynchronous closure. Read more
Source§

fn collect<C>(self) -> Collect<Self, C>
where C: Default + Extend<Self::Item>, Self: Sized,

Transforms a stream into a collection, returning a future representing the result of that computation. Read more
Source§

fn unzip<A, B, FromA, FromB>(self) -> Unzip<Self, FromA, FromB>
where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Stream<Item = (A, B)>,

Converts a stream of pairs into a future, which resolves to pair of containers. Read more
Source§

fn concat(self) -> Concat<Self>
where Self: Sized, Self::Item: Extend<<Self::Item as IntoIterator>::Item> + IntoIterator + Default,

Concatenate all items of a stream into a single extendable destination, returning a future representing the end result. Read more
Source§

fn count(self) -> Count<Self>
where Self: Sized,

Drives the stream to completion, counting the number of items. Read more
Source§

fn cycle(self) -> Cycle<Self>
where Self: Sized + Clone,

Repeats a stream endlessly. Read more
Source§

fn fold<T, Fut, F>(self, init: T, f: F) -> Fold<Self, Fut, T, F>
where F: FnMut(T, Self::Item) -> Fut, Fut: Future<Output = T>, Self: Sized,

Execute an accumulating asynchronous computation over a stream, collecting all the values into one final result. Read more
Source§

fn any<Fut, F>(self, f: F) -> Any<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future<Output = bool>, Self: Sized,

Execute predicate over asynchronous stream, and return true if any element in stream satisfied a predicate. Read more
Source§

fn all<Fut, F>(self, f: F) -> All<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future<Output = bool>, Self: Sized,

Execute predicate over asynchronous stream, and return true if all element in stream satisfied a predicate. Read more
Source§

fn flatten(self) -> Flatten<Self>
where Self::Item: Stream, Self: Sized,

Flattens a stream of streams into just one continuous stream. Read more
Source§

fn flatten_unordered( self, limit: impl Into<Option<usize>>, ) -> FlattenUnorderedWithFlowController<Self, ()>
where Self::Item: Stream + Unpin, Self: Sized,

Flattens a stream of streams into just one continuous stream. Polls inner streams produced by the base stream concurrently. Read more
Source§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where F: FnMut(Self::Item) -> U, U: Stream, Self: Sized,

Maps a stream like StreamExt::map but flattens nested Streams. Read more
Source§

fn flat_map_unordered<U, F>( self, limit: impl Into<Option<usize>>, f: F, ) -> FlatMapUnordered<Self, U, F>
where U: Stream + Unpin, F: FnMut(Self::Item) -> U, Self: Sized,

Maps a stream like StreamExt::map but flattens nested Streams and polls them concurrently, yielding items in any order, as they made available. Read more
Source§

fn scan<S, B, Fut, F>(self, initial_state: S, f: F) -> Scan<Self, S, Fut, F>
where F: FnMut(&mut S, Self::Item) -> Fut, Fut: Future<Output = Option<B>>, Self: Sized,

Combinator similar to StreamExt::fold that holds internal state and produces a new stream. Read more
Source§

fn skip_while<Fut, F>(self, f: F) -> SkipWhile<Self, Fut, F>
where F: FnMut(&Self::Item) -> Fut, Fut: Future<Output = bool>, Self: Sized,

Skip elements on this stream while the provided asynchronous predicate resolves to true. Read more
Source§

fn take_while<Fut, F>(self, f: F) -> TakeWhile<Self, Fut, F>
where F: FnMut(&Self::Item) -> Fut, Fut: Future<Output = bool>, Self: Sized,

Take elements from this stream while the provided asynchronous predicate resolves to true. Read more
Source§

fn take_until<Fut>(self, fut: Fut) -> TakeUntil<Self, Fut>
where Fut: Future, Self: Sized,

Take elements from this stream until the provided future resolves. Read more
Source§

fn for_each<Fut, F>(self, f: F) -> ForEach<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future<Output = ()>, Self: Sized,

Runs this stream to completion, executing the provided asynchronous closure for each element on the stream. Read more
Source§

fn for_each_concurrent<Fut, F>( self, limit: impl Into<Option<usize>>, f: F, ) -> ForEachConcurrent<Self, Fut, F>
where F: FnMut(Self::Item) -> Fut, Fut: Future<Output = ()>, Self: Sized,

Runs this stream to completion, executing the provided asynchronous closure for each element on the stream concurrently as elements become available. Read more
Source§

fn take(self, n: usize) -> Take<Self>
where Self: Sized,

Creates a new stream of at most n items of the underlying stream. Read more
Source§

fn skip(self, n: usize) -> Skip<Self>
where Self: Sized,

Creates a new stream which skips n items of the underlying stream. Read more
Source§

fn fuse(self) -> Fuse<Self>
where Self: Sized,

Fuse a stream such that poll_next will never again be called once it has finished. This method can be used to turn any Stream into a FusedStream. Read more
Source§

fn by_ref(&mut self) -> &mut Self

Borrows a stream, rather than consuming it. Read more
Source§

fn catch_unwind(self) -> CatchUnwind<Self>
where Self: Sized + UnwindSafe,

Catches unwinding panics while polling the stream. Read more
Source§

fn boxed<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + Send + 'a>>
where Self: Sized + Send + 'a,

Wrap the stream in a Box, pinning it. Read more
Source§

fn boxed_local<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a>>
where Self: Sized + 'a,

Wrap the stream in a Box, pinning it. Read more
Source§

fn buffered(self, n: usize) -> Buffered<Self>
where Self::Item: Future, Self: Sized,

An adaptor for creating a buffered list of pending futures. Read more
Source§

fn buffer_unordered(self, n: usize) -> BufferUnordered<Self>
where Self::Item: Future, Self: Sized,

An adaptor for creating a buffered list of pending futures (unordered). Read more
Source§

fn zip<St>(self, other: St) -> Zip<Self, St>
where St: Stream, Self: Sized,

An adapter for zipping two streams together. Read more
Source§

fn chain<St>(self, other: St) -> Chain<Self, St>
where St: Stream<Item = Self::Item>, Self: Sized,

Adapter for chaining two streams. Read more
Source§

fn peekable(self) -> Peekable<Self>
where Self: Sized,

Creates a new stream which exposes a peek method. Read more
Source§

fn chunks(self, capacity: usize) -> Chunks<Self>
where Self: Sized,

An adaptor for chunking up items of the stream inside a vector. Read more
Source§

fn ready_chunks(self, capacity: usize) -> ReadyChunks<Self>
where Self: Sized,

An adaptor for chunking up ready items of the stream inside a vector. Read more
Source§

fn forward<S>(self, sink: S) -> Forward<Self, S>
where S: Sink<Self::Ok, Error = Self::Error>, Self: Sized + TryStream,

A future that completes after the given stream has been fully processed into the sink and the sink has been flushed and closed. Read more
Source§

fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
where Self: Sized + Sink<Item>,

Splits this Stream + Sink object into separate Sink and Stream objects. Read more
Source§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where F: FnMut(&Self::Item), Self: Sized,

Do something with each item of this stream, afterwards passing it on. Read more
Source§

fn left_stream<B>(self) -> Either<Self, B>
where B: Stream<Item = Self::Item>, Self: Sized,

Wrap this stream in an Either stream, making it the left-hand variant of that Either. Read more
Source§

fn right_stream<B>(self) -> Either<B, Self>
where B: Stream<Item = Self::Item>, Self: Sized,

Wrap this stream in an Either stream, making it the right-hand variant of that Either. Read more
Source§

fn poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
where Self: Unpin,

A convenience method for calling Stream::poll_next on Unpin stream types.
Source§

fn select_next_some(&mut self) -> SelectNextSome<'_, Self>
where Self: Unpin + FusedStream,

Returns a Future that resolves when the next item in this stream is ready. 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T