### Create a GET Request in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/request/struct.Request Demonstrates how to use `Request::get` to build an HTTP GET request with a specified URI and an empty body. This example shows the basic usage of the request builder pattern. ```Rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Rust HTTP Request Creation and Sending Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Request Demonstrates how to use `http::Request::builder()` to construct an HTTP GET request with a URI and custom headers, and then send it. Includes conditional header addition based on a helper function. ```Rust use http::{Request, Response}; let mut request = Request::builder() .uri("https://www.rust-lang.org/") .header("User-Agent", "my-awesome-agent/1.0"); if needs_awesome_header() { request = request.header("Awesome", "yes"); } let response = send(request.body(()).unwrap()); fn send(req: Request<()>) -> Response<()> { // ... } ``` -------------------------------- ### Rust HTTP Method Usage Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/method/struct.Method Demonstrates basic usage of the `http::Method` struct in Rust. This example shows how to create a `Method` instance from bytes, compare it to a constant, check for idempotency, and convert it to a string slice. ```Rust use http::Method; assert_eq!(Method::GET, Method::from_bytes(b"GET").unwrap()); assert!(Method::GET.is_idempotent()); assert_eq!(Method::POST.as_str(), "POST"); ``` -------------------------------- ### Rust `str::parse` Usage Examples Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/protocol/frame/struct.Utf8Bytes Provides practical examples for using the `parse` method, demonstrating basic usage with type annotation, explicit type inference using the 'turbofish' syntax, and handling scenarios where parsing fails. ```Rust let four: u32 = "4".parse().unwrap(); assert_eq!(4, four); ``` ```Rust let four = "4".parse::(); assert_eq!(Ok(4), four); ``` ```Rust let nope = "j".parse::(); assert!(nope.is_err()); ``` -------------------------------- ### Rust StatusCode Basic Usage Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/status/struct.StatusCode Illustrates basic usage of the `StatusCode` struct in Rust. This example demonstrates how to import the struct, create instances from `u16` values, retrieve the `u16` representation, and check for success status codes. ```Rust use http::StatusCode; assert_eq!(StatusCode::from_u16(200).unwrap(), StatusCode::OK); assert_eq!(StatusCode::NOT_FOUND.as_u16(), 404); assert!(StatusCode::OK.is_success()); ``` -------------------------------- ### Rust `trim_prefix` Method Usage Examples Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/struct.Utf8Bytes Illustrates the usage of the `trim_prefix` method in Rust, showing cases where the prefix is present and removed, absent and the original string is returned, and an example of method chaining with `trim_suffix`. ```Rust #![feature(trim_prefix_suffix)] // Prefix present - removes it assert_eq!("foo:bar".trim_prefix("foo:"), "bar"); assert_eq!("foofoo".trim_prefix("foo"), "foo"); // Prefix absent - returns original string assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar"); // Method chaining example assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` -------------------------------- ### Rust HTTP Request Inspection Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Request Illustrates how to inspect an incoming `http::Request` to check its URI, headers, and body. Includes an example of returning a 404 Not Found response if the URI does not match a specific path. ```Rust use http::{Request, Response, StatusCode}; fn respond_to(req: Request<()>) -> http::Result> { if req.uri() != "/awesome-url" { return Response::builder() .status(StatusCode::NOT_FOUND) .body(()) } let has_awesome_header = req.headers().contains_key("Awesome"); let body = req.body(); // ... } ``` -------------------------------- ### Rust String trim_start Method Examples Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/struct.Utf8Bytes Demonstrates the `trim_start` method in Rust for removing leading whitespace from strings. Examples include basic usage with newlines and tabs, and handling of different text directionalities (English and Hebrew characters) while preserving non-leading content. ```Rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` ```Rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### Example: Get Value from `OccupiedEntry` in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.OccupiedEntry Illustrates how to get an immutable reference to the first value associated with an `OccupiedEntry` in a `HeaderMap` using the `get()` method. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` -------------------------------- ### ExtensionContext Instance Methods API Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/extension/interface/struct.ExtensionContext API documentation for the methods implemented directly on the `ExtensionContext` struct, including its constructor and methods for managing associated metadata. These methods allow for creating new instances and interacting with the context's data. ```APIDOC ExtensionContext Methods: pub fn new(connection_id: u64) -> Self - Description: Creates a new `ExtensionContext` instance with a specified connection ID. - Parameters: - connection_id: u64 - A unique identifier for the connection. - Returns: Self - A new `ExtensionContext` instance. pub fn with_metadata(self, key: K, value: V) -> Self where K: Into, V: Into - Description: Adds a key-value pair to the context's metadata. This method consumes `self` and returns a new `Self`, enabling method chaining. - Parameters: - key: K (Into) - The key for the metadata entry. - value: V (Into) - The value for the metadata entry. - Returns: Self - The `ExtensionContext` instance with the added metadata. pub fn get_metadata(&self, key: &str) -> Option<&String> - Description: Retrieves a reference to the metadata value associated with the given key. - Parameters: - key: &str - The key to look up in the metadata. - Returns: Option<&String> - An `Option` containing a reference to the `String` value if the key exists, otherwise `None`. ``` -------------------------------- ### Rust HTTP Response Creation and Basic Handling Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/response/struct.Response Examples demonstrating how to construct `http::Response` objects using the builder pattern, set headers and status codes, and implement basic HTTP handlers like a 404 Not Found response. ```Rust use http::{Request, Response, StatusCode}; fn respond_to(req: Request<()>) -> http::Result> { let mut builder = Response::builder() .header("Foo", "Bar") .status(StatusCode::OK); if req.headers().contains_key("Another-Header") { builder = builder.header("Another-Header", "Ack"); } builder.body(()) } ``` ```Rust use http::{Request, Response, StatusCode}; fn not_found(_req: Request<()>) -> http::Result> { Response::builder() .status(StatusCode::NOT_FOUND) .body(()) } ``` -------------------------------- ### Rust Slice Pointer Range Containment Check Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/struct.Bytes Illustrates the use of `as_ptr_range` to get the start and end raw pointers of a slice. The example then uses the `contains` method on the returned range to check if a given pointer falls within the slice's memory bounds, which is useful for validating pointer ownership or membership. ```Rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### Rust MessageExtension Struct Initialization and Configuration Methods Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/extension/interface/struct.MessageExtension Provides methods for creating a new `MessageExtension` instance and configuring its version and description. These methods are part of a builder pattern, allowing chained calls for setup. ```APIDOC impl MessageExtension pub fn new(name: &'static str, handler: F) -> Self - Description: Creates a new MessageExtension instance. - Parameters: - name: &'static str - The static name of the extension. - handler: F - The handler function for the extension. - Returns: Self - A new MessageExtension instance. pub fn with_version(self, version: &'static str) -> Self - Description: Sets the version for the MessageExtension. - Parameters: - version: &'static str - The static version string. - Returns: Self - The MessageExtension instance with the updated version. pub fn with_description(self, description: &'static str) -> Self - Description: Sets the description for the MessageExtension. - Parameters: - description: &'static str - The static description string. - Returns: Self - The MessageExtension instance with the updated description. ``` -------------------------------- ### Set URI path and query using Rust Builder Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Builder Example of building a `Uri` in Rust by setting only its path and query string components. ```Rust let uri = uri::Builder::new() .path_and_query("/hello?foo=bar") .build() .unwrap(); ``` -------------------------------- ### HeaderMap get header value Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.HeaderMap Illustrates retrieving a header value from a `HeaderMap` using the `get` method. This example shows how to check for `None`, insert new values, and append additional values while still retrieving the first one. ```Rust let mut map = HeaderMap::new(); assert!(map.get("host").is_none()); map.insert(HOST, "hello".parse().unwrap()); assert_eq!(map.get(HOST).unwrap(), &"hello"); assert_eq!(map.get("host").unwrap(), &"hello"); map.append(HOST, "world".parse().unwrap()); assert_eq!(map.get("host").unwrap(), &"hello"); ``` -------------------------------- ### Get canonical reason from http::StatusCode in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.StatusCode This Rust example shows how to get the standardized reason phrase associated with an `http::StatusCode` using the `canonical_reason` method. It confirms that `StatusCode::OK` returns `Some("OK")`. ```Rust let status = http::StatusCode::OK; assert_eq!(status.canonical_reason(), Some("OK")); ``` -------------------------------- ### API Reference: `http::Response` Struct and Methods Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Response Detailed API documentation for the `http::Response` struct, including its definition, constructor methods (`new`), and the builder pattern (`builder`) for flexible response creation. This covers the primary ways to instantiate and configure HTTP responses. ```APIDOC pub struct Response { /* private fields */ } - Represents an HTTP response, consisting of a head and a potentially optional body. - The body component is generic, enabling arbitrary types (e.g., `Vec`, `Stream`, deserialized values). pub fn builder() -> Builder - Creates a new builder-style object to manufacture a `Response`. - Returns: An instance of `http::response::Builder`. - Example: let response = Response::builder() .status(200) .header("X-Custom-Foo", "Bar") .body(()) .unwrap(); pub fn new(body: T) -> Response - Creates a new blank `Response` with the specified body. - Parameters: - body: The body content for the response (type T). - Returns: A new `Response` instance. - Details: The component parts of this response (e.g., status, headers) will be set to their default values (e.g., OK status, no headers). ``` -------------------------------- ### Rust Slice: `rsplitn` Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/struct.Bytes Demonstrates how to use the `rsplitn` method on a Rust slice to split it from the end based on a predicate, limiting the number of splits. The example splits a vector by numbers divisible by 3, starting from the end, into at most 2 groups. ```Rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### Inspecting and Responding to an HTTP Request in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/request/index This Rust example illustrates how to inspect an incoming HTTP `Request` to check its URI and headers. It also shows how to construct an HTTP `Response`, including setting a status code like `NOT_FOUND`, based on the request's properties. ```Rust use http::{Request, Response, StatusCode}; fn respond_to(req: Request<()>) -> http::Result> { if req.uri() != "/awesome-url" { return Response::builder() .status(StatusCode::NOT_FOUND) .body(()) } let has_awesome_header = req.headers().contains_key("Awesome"); let body = req.body(); // ... } ``` -------------------------------- ### Example for `str::encode_utf16` in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/protocol/frame/struct.Utf8Bytes Demonstrates how to use the `encode_utf16` method to get the UTF-16 length of a string and compare it to its UTF-8 length. ```Rust let text = "Zażółć gęślą jaźń"; let utf8_len = text.len(); let utf16_len = text.encode_utf16().count(); assert!(utf16_len <= utf8_len); ``` -------------------------------- ### Build a complete URI using Rust Builder Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Builder Demonstrates how to construct a complete `Uri` using the `Builder` pattern in Rust, setting scheme, authority, and path/query in a chained manner. ```Rust let uri = uri::Builder::new() .scheme("https") .authority("hyper.rs") .path_and_query("/") .build() .unwrap(); ``` -------------------------------- ### Mutate Request Version in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Request Demonstrates how to get a mutable reference to the HTTP version of a `Request` and modify it, for example, changing it to `HTTP_2`. ```Rust let mut request: Request<()> = Request::default(); *request.version_mut() = Version::HTTP_2; assert_eq!(request.version(), Version::HTTP_2); ``` -------------------------------- ### Tungstenite Crate Modules Overview Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/index This section provides an overview of the modules within the `tungstenite` Rust crate, which offers lightweight and flexible WebSockets for Rust. Each module is briefly described, outlining its primary function and purpose within the library. ```APIDOC Crate: tungstenite Description: Lightweight, flexible WebSockets for Rust. Modules: - buffer: A buffer for reading data from the network. - client: Methods to connect to a WebSocket as a client. - error: Error handling. - handshake: WebSocket handshake control. - http: A general purpose library of common HTTP types. - protocol: Generic WebSocket message stream. - stream: Convenience wrapper for streams to switch between plain TCP and TLS at runtime. - util: Helper traits to ease non-blocking handling. ``` -------------------------------- ### MaybePSTSender Core Methods API Reference Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/prelude/struct.MaybePSTSender This section details the primary methods available on the `MaybePSTSender` struct, including checking connection status and sending messages. These methods are optimized for performance, offering fast path rejections and lock-free checks where applicable. ```APIDOC MaybePSTSender Methods: pub fn is_connected(&self) -> bool - Fast path check without acquiring lock - Returns: bool pub async fn send(&self, msg: Message) -> EResult<(), ReconnectTError> - Optimized send with fast path rejection - Parameters: - msg: stream_tungstenite::tokio_tungstenite::tungstenite::Message - The message to send. - Returns: eyre::Result<()> on success, or stream_tungstenite::errors::ReconnectTError on error. ``` -------------------------------- ### Example: Get Key from `OccupiedEntry` in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.OccupiedEntry Demonstrates how to retrieve a reference to the key of an `OccupiedEntry` within a `HeaderMap` using the `key()` method. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); if let Entry::Occupied(e) = map.entry("host") { assert_eq!("host", e.key()); } ``` -------------------------------- ### Get Host from Authority in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Authority This example demonstrates how to parse an authority string and extract its host component using the `Authority::host()` method in Rust. ```Rust let authority: Authority = "example.org:80".parse().unwrap(); assert_eq!(authority.host(), "example.org"); ``` -------------------------------- ### HTTP URI Builder API Reference (Rust) Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Builder Comprehensive API documentation for the `http::uri::Builder` struct in Rust, detailing methods for constructing `Uri` instances. Includes `new` for initialization, and setters for `scheme`, `authority`, and `path_and_query` components. ```APIDOC impl Builder pub fn new() -> Builder - Creates a new default instance of `Builder` to construct a `Uri`. - Returns: `Builder` instance. pub fn scheme(self, scheme: T) -> Builder - Set the `Scheme` for this URI. - Parameters: - scheme: T (Type convertible to `Scheme`) - Returns: `Builder` instance. pub fn authority(self, auth: T) -> Builder - Set the `Authority` for this URI. - Parameters: - auth: T (Type convertible to `Authority`) - Returns: `Builder` instance. pub fn path_and_query(self, p_and_q: T) -> Builder - Set the `PathAndQuery` for this URI. - Parameters: - p_and_q: T (Type convertible to `PathAndQuery`) - Returns: `Builder` instance. ``` -------------------------------- ### API Documentation for Rust ExtensionCapabilities Struct Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/extension/interface/struct.ExtensionCapabilities Comprehensive API documentation for the `ExtensionCapabilities` struct, detailing its fields, associated methods, and implemented traits. This includes parameter types, return values, and brief descriptions for each element. ```APIDOC Struct: ExtensionCapabilities Description: Extension capabilities to indicate what an extension can handle. Fields: handles_messages: bool Description: Indicates if the extension handles messages. handles_lifecycle: bool Description: Indicates if the extension handles lifecycle events. Methods: new(): Self Description: Creates a new default ExtensionCapabilities instance. with_messages(self): Self Description: Returns a new ExtensionCapabilities instance with 'handles_messages' set to true. with_lifecycle(self): Self Description: Returns a new ExtensionCapabilities instance with 'handles_lifecycle' set to true. with_all(self): Self Description: Returns a new ExtensionCapabilities instance with all capabilities set to true. Trait Implementations: Clone: fn clone(&self): ExtensionCapabilities Description: Returns a duplicate of the value. const fn clone_from(&mut self, source: &Self) Description: Performs copy-assignment from 'source'. Parameters: source: &Self - The source to copy from. Debug: fn fmt(&self, f: &mut Formatter<'_>): Result Description: Formats the value using the given formatter. Parameters: f: &mut Formatter<'_> - The formatter to use. Default: fn default(): ExtensionCapabilities Description: Returns the "default value" for a type. ``` -------------------------------- ### Get Port as u16 from Authority in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Authority This example illustrates how to directly obtain the port component of an `Authority` as a `u16` integer using the `Authority::port_u16()` method. ```Rust let authority: Authority = "example.org:80".parse().unwrap(); assert_eq!(authority.port_u16(), Some(80)); ``` -------------------------------- ### Rust `Extensions` Method: `len` Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Extensions Demonstrates how to get the number of extensions currently stored in the `Extensions` instance. It shows the length before and after inserting a value. ```Rust let mut ext = Extensions::new(); assert_eq!(ext.len(), 0); ext.insert(5i32); assert_eq!(ext.len(), 1); ``` -------------------------------- ### HTTP Response Structs Reference Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/response/index Detailed documentation for key HTTP response structs used in the `stream_tungstenite` library, providing insights into their purpose and components. ```APIDOC Structs: Builder - Description: An HTTP response builder - Type: struct stream_tungstenite::tokio_tungstenite::tungstenite::http::response::Builder Parts - Description: Component parts of an HTTP `Response` - Type: struct stream_tungstenite::tokio_tungstenite::tungstenite::http::response::Parts Response - Description: Represents an HTTP response - Type: struct stream_tungstenite::tokio_tungstenite::tungstenite::http::response::Response ``` -------------------------------- ### Build HTTP Requests with Specific Methods (CONNECT, PATCH, TRACE) Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/request/struct.Request These methods provide a convenient way to start building an `http::Request` by pre-setting the HTTP method (CONNECT, PATCH, or TRACE) and the target URI. They return a `Builder` instance, allowing for further customization of the request before finalization. ```APIDOC pub fn connect(uri: T) -> Builder - Creates a new `Builder` initialized with a CONNECT method and the given URI. - Parameters: - uri: T, The URI for the request. Must implement `TryInto`. - Returns: An instance of `Builder` for constructing the `Request`. pub fn patch(uri: T) -> Builder - Creates a new `Builder` initialized with a PATCH method and the given URI. - Parameters: - uri: T, The URI for the request. Must implement `TryInto`. - Returns: An instance of `Builder` for constructing the `Request`. pub fn trace(uri: T) -> Builder - Creates a new `Builder` initialized with a TRACE method and the given URI. - Parameters: - uri: T, The URI for the request. Must implement `TryInto`. - Returns: An instance of `Builder` for constructing the `Request`. ``` ```Rust let request = Request::connect("https://www.rust-lang.org/") .body(()) .unwrap(); let request = Request::patch("https://www.rust-lang.org/") .body(()) .unwrap(); let request = Request::trace("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Example: Get Mutable Value from `OccupiedEntry` in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.OccupiedEntry Shows how to obtain a mutable reference to the first value in an `OccupiedEntry` for modification using the `get_mut()` method. ```Rust let mut map = HeaderMap::default(); map.insert(HOST, "hello.world".to_string()); if let Entry::Occupied(mut e) = map.entry("host") { e.get_mut().push_str("-2"); assert_eq!(e.get(), &"hello.world-2"); } ``` -------------------------------- ### Get Port from Authority in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Authority These examples show how to retrieve the port component from an `Authority` instance using the `Authority::port()` method. It covers cases with and without an explicit port. ```Rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_u16(), 80); assert_eq!(port.as_str(), "80"); ``` ```Rust let authority: Authority = "example.org".parse().unwrap(); assert!(authority.port().is_none()); ``` -------------------------------- ### Rust `Extensions::get` Method Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Extensions Illustrates how to retrieve an immutable reference to a value stored in the `Extensions` struct using the `get` method, showing how to check for its presence. ```Rust let mut ext = Extensions::new(); assert!(ext.get::().is_none()); ext.insert(5i32); assert_eq!(ext.get::(), Some(&5i32)); ``` -------------------------------- ### Tungstenite ClientHandshake API Reference Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/handshake/client/struct.ClientHandshake Detailed API documentation for the `ClientHandshake` struct in the `tungstenite` Rust library, including its `start` method for initiating handshakes, `Debug` trait implementation for formatting, and `HandshakeRole` trait implementation. ```APIDOC pub struct ClientHandshake { /* private fields */ } - Represents the client's role in a WebSocket handshake. - Generic over a stream type `S`. impl ClientHandshake where S: Read + Write pub fn start( stream: S, request: Request<()> config: Option ) -> Result>, Error> - Initiates a client handshake. - Parameters: - stream: The underlying stream (e.g., TCP stream) that implements `Read` and `Write`. - request: The HTTP request to send for the handshake. - config: Optional WebSocket configuration settings. - Returns: A `Result` containing `MidHandshake` on success, or an `Error` on failure. impl Debug for ClientHandshake where S: Debug fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> - Formats the `ClientHandshake` value for debugging purposes. - Parameters: - f: The formatter to write into. - Returns: A `Result` indicating success or a formatting `Error`. impl HandshakeRole for ClientHandshake where S: Read + Write - Indicates that `ClientHandshake` fulfills the `HandshakeRole` trait, defining common behavior for handshake participants. ``` -------------------------------- ### Get Length of HeaderValue in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.HeaderValue Shows how to retrieve the byte length of a `HeaderValue` instance using the `len` method. The example confirms the expected length for a given header value. ```Rust let val = HeaderValue::from_static("hello"); assert_eq!(val.len(), 5); ``` -------------------------------- ### HTTP Response Builder Methods and Trait Implementations Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/response/struct.Builder Detailed API documentation for the `http::response::Builder` struct, including methods for managing extensions, setting the response body, and implementations of the `Debug` and `Default` traits. ```APIDOC pub fn extensions_ref(&self) -> Option<&[Extensions]> - Description: Get a reference to the extensions for this response builder. - Returns: `Option<&[Extensions]>` - Returns `None` if the builder has an error. pub fn extensions_mut(&mut self) -> Option<&mut [Extensions]> - Description: Get a mutable reference to the extensions for this response builder. - Returns: `Option<&mut [Extensions]>` - Returns `None` if the builder has an error. pub fn body(self, body: T) -> Result, Error> - Description: Consumes this builder, using the provided `body` to return a constructed `Response`. - Parameters: - body: The body to use for the response. - Returns: `Result, Error>` - An error may be returned if any previously configured argument failed to parse or convert. impl Debug for Builder: fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> - Description: Formats the value using the given formatter. impl Default for Builder: fn default() -> Builder - Description: Returns the “default value” for a type. ``` -------------------------------- ### Get Port as u16 in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Port Demonstrates how to extract and convert the port number from a `Port` instance into a `u16` integer. This example parses an authority string and asserts the numerical port value. ```Rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_u16(), 80); ``` -------------------------------- ### HeaderMap API Reference Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.HeaderMap Comprehensive API documentation for key methods of the Rust `HeaderMap` type, covering capacity management and header value retrieval. This includes `reserve`, `try_reserve`, `get`, `get_mut`, and `get_all` methods. ```APIDOC HeaderMap API: pub fn reserve(&mut self, additional: usize) - Description: Reserves capacity for at least `additional` more headers to be inserted into the `HeaderMap`. The map may reserve more space to avoid frequent reallocations. This is a “best effort” to avoid allocations until `additional` more headers are inserted. - Parameters: - additional: The minimum additional capacity to reserve. - Panics: Panics if the new allocation size overflows `HeaderMap` `MAX_SIZE`. - See example: "HeaderMap reserve capacity" pub fn try_reserve(&mut self, additional: usize) -> Result<(), MaxSizeReached> - Description: Reserves capacity for at least `additional` more headers to be inserted into the `HeaderMap`. Similar to `reserve`, but returns an error instead of panicking if the value is too large. - Parameters: - additional: The minimum additional capacity to reserve. - Returns: `Ok(())` on success, or `Err(MaxSizeReached)` if the new allocation size overflows `HeaderMap` `MAX_SIZE`. - See example: "HeaderMap try_reserve capacity" pub fn get(&self, key: K) -> Option<&T> where K: AsHeaderName, - Description: Returns a reference to the value associated with the key. If multiple values exist, the first one is returned. Returns `None` if no values are associated. Use `get_all` for all values. - Parameters: - key: The header name to look up (implements `AsHeaderName`). - Returns: An `Option` containing a reference to the header value, or `None`. - See example: "HeaderMap get header value" pub fn get_mut(&mut self, key: K) -> Option<&mut T> where K: AsHeaderName, - Description: Returns a mutable reference to the value associated with the key. If multiple values exist, the first one is returned. Returns `None` if no values are associated. Use `entry` for all values. - Parameters: - key: The header name to look up (implements `AsHeaderName`). - Returns: An `Option` containing a mutable reference to the header value, or `None`. - See example: "HeaderMap get_mut header value" pub fn get_all(&self, key: K) -> GetAll<'_, T> where K: AsHeaderName, - Description: Returns a view of all values associated with a key. The returned view does not incur any allocations and allows iterating the values. - Parameters: - key: The header name to look up (implements `AsHeaderName`). - Returns: A `GetAll` struct allowing iteration over all values for the key. ``` -------------------------------- ### Check if Rust String Starts With Prefix Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/struct.Utf8Bytes Illustrates the usage of the `starts_with` method in Rust to determine if a string slice begins with a specified prefix. This example uses a simple string literal as the pattern. ```Rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` -------------------------------- ### Get Port as String Slice in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Port Illustrates how to retrieve the port number as a string slice (`&str`) from a `Port` instance. The example shows parsing an authority string and asserting the string representation of the port. ```Rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_str(), "80"); ``` -------------------------------- ### Rust ExtensionCapabilities Associated Methods Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/extension/interface/struct.ExtensionCapabilities Provides methods for constructing and modifying `ExtensionCapabilities` instances. These include a default constructor and builder-style methods to easily set specific capabilities or enable all of them. ```Rust pub fn new() -> Self pub fn with_messages(self) -> Self pub fn with_lifecycle(self) -> Self pub fn with_all(self) -> Self ``` -------------------------------- ### Get u16 from http::StatusCode in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.StatusCode This Rust example illustrates how to retrieve the `u16` integer representation of an `http::StatusCode` instance using the `as_u16` method. It confirms that `StatusCode::OK` correctly returns 200. ```Rust let status = http::StatusCode::OK; assert_eq!(status.as_u16(), 200); ``` -------------------------------- ### ExtensionRegistry Methods API Reference Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/extension/interface/struct.ExtensionRegistry Comprehensive API documentation for the `ExtensionRegistry` struct, detailing its methods for managing, registering, retrieving, and interacting with extensions. This includes methods for initialization, dynamic registration, querying extensions by type, and notifying extensions of events or messages. ```APIDOC ExtensionRegistry Methods: pub fn new(connection_id: u64) -> Self - Description: Creates a new `ExtensionRegistry` instance. - Parameters: - connection_id: u64 - An identifier for the connection. - Returns: Self - A new `ExtensionRegistry` instance. pub async fn register(&self, extension: E) -> EResult<()> - Description: Registers a new extension with the registry. - Parameters: - extension: E - The extension to register. Must implement `Extension` and be `'static`. - Returns: EResult<()> - An `eyre::Result` indicating success or failure. pub async fn get_extensions(&self) -> Vec> - Description: Retrieves all registered extensions. - Parameters: None. - Returns: Vec> - A vector of `Arc` pointers to all registered extensions. pub async fn get_message_extensions(&self) -> Vec> - Description: Retrieves extensions specifically designed to handle messages. - Parameters: None. - Returns: Vec> - A vector of `Arc` pointers to message-handling extensions. pub async fn get_lifecycle_extensions(&self) -> Vec> - Description: Retrieves extensions that manage lifecycle events. - Parameters: None. - Returns: Vec> - A vector of `Arc` pointers to lifecycle-handling extensions. pub async fn notify_event(&self, event: ExtensionEvent) -> EResult<()> - Description: Notifies all registered extensions of a specific event. - Parameters: - event: ExtensionEvent - The event to notify extensions about. - Returns: EResult<()> - An `eyre::Result` indicating success or failure. pub async fn notify_message(&self, message: &[Message]) -> EResult<()> - Description: Notifies message-handling extensions about an incoming message. - Parameters: - message: &[Message] - The message to notify extensions about. - Returns: EResult<()> - An `eyre::Result` indicating success or failure. pub async fn update_context(&self, connection_id: u64, reconnect_count: u64) - Description: Updates the context for extensions, typically used during reconnection. - Parameters: - connection_id: u64 - The updated connection identifier. - reconnect_count: u64 - The current reconnection attempt count. - Returns: None. pub async fn shutdown(&self) -> EResult<()> - Description: Initiates the graceful shutdown process for all registered extensions. - Parameters: None. - Returns: EResult<()> - An `eyre::Result` indicating success or failure. ``` -------------------------------- ### Get Host from Absolute Rust `Uri` Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Uri Shows how to retrieve the host subcomponent from an absolute `Uri` using the `host()` method. The example parses a URI with a host and port and asserts that only the host part is returned. ```Rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.host(), Some("example.org")); ``` -------------------------------- ### HeaderMap Basic Usage Example Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.HeaderMap Illustrates fundamental operations of the `HeaderMap`, including inserting new headers, checking for the existence of a key, accessing header values by key, and removing headers. ```Rust let mut headers = HeaderMap::new(); headers.insert(HOST, "example.com".parse().unwrap()); headers.insert(CONTENT_LENGTH, "123".parse().unwrap()); assert!(headers.contains_key(HOST)); assert!(!headers.contains_key(LOCATION)); assert_eq!(headers[HOST], "example.com"); headers.remove(HOST); assert!(!headers.contains_key(HOST)); ``` -------------------------------- ### Get Authority from Absolute Rust `Uri` Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Uri Illustrates how to extract the authority component from an absolute `Uri` using the `authority()` method. The example parses a URI with a host and port and asserts the correct authority string. ```Rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.authority().map(|a| a.as_str()), Some("example.org:80")); ``` -------------------------------- ### Creating an HTTP Request with Builder in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/request/index This example demonstrates how to construct an HTTP `Request` object using the `Request::builder()` in Rust. It shows how to set the URI and add headers, including conditional header addition, and then prepare the request body before sending. ```Rust use http::{Request, Response}; let mut request = Request::builder() .uri("https://www.rust-lang.org/") .header("User-Agent", "my-awesome-agent/1.0"); if needs_awesome_header() { request = request.header("Awesome", "yes"); } let response = send(request.body(()).unwrap()); fn send(req: Request<()>) -> Response<()> { // ... } ``` -------------------------------- ### Get Scheme String from Absolute Rust `Uri` Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.Uri Provides an example of retrieving the scheme component of an absolute `Uri` as a string slice using the `scheme_str()` method. The assertion confirms the 'http' scheme is returned. ```Rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme_str(), Some("http")); ``` -------------------------------- ### Rust `Builder` Struct API Documentation Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/uri/struct.Builder Comprehensive API documentation for the `Builder` struct, including its core `build` method and implementations of `Debug`, `Default`, and `From` traits, used for constructing and managing `Uri` objects. ```APIDOC pub fn build(self) -> Result - Consumes this builder, and tries to construct a valid `Uri` from the configured pieces. - Returns: `Result` - Errors: This function may return an error if any previously configured argument failed to parse or get converted to the internal representation (e.g., invalid scheme). Additionally, if the parts don’t fit into any of the valid forms of URI, a new error is returned. impl Debug for Builder fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> - Formats the value using the given formatter. - Parameters: - f: A mutable reference to a `Formatter` instance. - Returns: `Result<(), Error>` impl Default for Builder fn default() -> Builder - Returns the “default value” for a type, which is a default `Builder` instance. - Returns: `Builder` impl From for Builder fn from(uri: Uri) -> Builder - Converts a `Uri` instance into a `Builder` instance. - Parameters: - uri: The `Uri` instance to convert. - Returns: `Builder` ``` -------------------------------- ### Get string from http::StatusCode in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/struct.StatusCode This Rust example demonstrates how to obtain the numerical string representation of an `http::StatusCode` using the `as_str` method. It verifies that `StatusCode::OK` returns the string "200". ```Rust let status = http::StatusCode::OK; assert_eq!(status.as_str(), "200"); ``` -------------------------------- ### Rust `VacantEntry` Struct and Methods API Documentation Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/header/struct.VacantEntry Comprehensive API documentation for the `VacantEntry` struct and its associated methods, detailing their signatures, parameters, return types, and functionality within the `http::header::map` module. ```APIDOC Struct: VacantEntry<'a, T> - Description: A view into a single empty location in a `HeaderMap`. This struct is returned as part of the `Entry` enum. Implementation: impl<'a, T> VacantEntry<'a, T> Method: pub fn key(&self) -> &[HeaderName] - Description: Returns a reference to the entry’s key. - Parameters: None - Returns: A reference to the `HeaderName` key. Method: pub fn into_key(self) -> HeaderName - Description: Takes ownership of the key, consuming the `VacantEntry`. - Parameters: None - Returns: The `HeaderName` key. Method: pub fn insert(self, value: T) -> &'a mut T - Description: Inserts the provided `value` into the entry. The value will be associated with this entry’s key. A mutable reference to the inserted value will be returned. - Parameters: - value: The value to insert into the `HeaderMap`. - Returns: A mutable reference to the inserted value. Method: pub fn try_insert(self, value: T) -> Result< &'a mut T, MaxSizeReached > - Description: Attempts to insert the provided `value` into the entry. The value will be associated with this entry’s key. A mutable reference to the inserted value will be returned on success, or a `MaxSizeReached` error if the map is full. - Parameters: - value: The value to insert into the `HeaderMap`. - Returns: A `Result` containing a mutable reference to the inserted value on success, or `MaxSizeReached` on failure. Method: pub fn insert_entry(self, value: T) -> OccupiedEntry<'a, T> - Description: Inserts the provided `value` into the entry. The value will be associated with this entry’s key. The new `OccupiedEntry` is returned, allowing for further manipulation of the now-occupied entry. - Parameters: - value: The value to insert into the `HeaderMap`. - Returns: An `OccupiedEntry` representing the newly filled entry. Method: pub fn try_insert_entry(self, value: T) -> Result< OccupiedEntry<'a, T>, MaxSizeReached > - Description: Attempts to insert the provided `value` into the entry. The value will be associated with this entry’s key. The new `OccupiedEntry` is returned on success, or a `MaxSizeReached` error if the map is full. - Parameters: - value: The value to insert into the `HeaderMap`. - Returns: A `Result` containing an `OccupiedEntry` on success, or `MaxSizeReached` on failure. ``` -------------------------------- ### Get Mutable Extensions from Response Builder in Rust Source: https://docs.rs/stream-tungstenite/latest/stream_tungstenite/tokio_tungstenite/tungstenite/http/response/struct.Builder Illustrates how to obtain a mutable reference to the extensions of an HTTP `Response::builder`. This example shows adding an initial extension, retrieving a mutable reference, and then inserting another extension. ```Rust let mut res = Response::builder().extension("My Extension"); let mut extensions = res.extensions_mut().unwrap(); assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension")); extensions.insert(5u32); assert_eq!(extensions.get::(), Some(&5u32)); ```