### Rust Generic Search Examples Source: https://docs.quic.tech/tokio_quiche/buf_factory/struct.QuicheBuf_search= Demonstrates example search queries for Rust types and generic function signatures. These examples are useful for navigating documentation and understanding type transformations. ```rust * std::vec ``` ```rust * u32 -> bool ``` ```rust * Option, (T -> U) -> Option ``` -------------------------------- ### Example: Recreate Box from NonNull Pointer (Nightly) Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=u32+-%3E+bool Demonstrates recreating a `Box` from a `NonNull` pointer previously obtained via `Box::into_non_null`. This example requires the `box_vec_non_null` feature gate. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### Starting an HTTP/3 Server with tokio_quiche Source: https://docs.quic.tech/tokio_quiche/index This snippet demonstrates how to start an HTTP/3 server using tokio_quiche. It listens for incoming QUIC connections on a UDP socket and spawns a new tokio task to handle each connection. The ServerH3Driver is used to manage the HTTP/3 protocol over the QUIC connection. ```rust use futures::stream::StreamExt; use tokio_quiche::http3::settings::Http3Settings; use tokio_quiche::listen; use tokio_quiche::metrics::DefaultMetrics; use tokio_quiche::quic::SimpleConnectionIdGenerator; use tokio_quiche::ConnectionParams; use tokio_quiche::ServerH3Driver; let socket = tokio::net::UdpSocket::bind("0.0.0.0:443").await?; let mut listeners = listen( [socket], ConnectionParams::default(), SimpleConnectionIdGenerator, DefaultMetrics, )?; let mut accept_stream = &mut listeners[0]; while let Some(conn) = accept_stream.next().await { let (driver, mut controller) = ServerH3Driver::new(Http3Settings::default()); conn?.start(driver); tokio::spawn(async move { // `controller` is the handle to our established HTTP/3 connection. // For example, inbound requests are available as H3Events via: let event = controller.event_receiver_mut().recv().await; }); } ``` -------------------------------- ### Rust Search Examples Source: https://docs.quic.tech/tokio_quiche/quic/struct.ConnectionShutdownBehaviour_search= Illustrative examples of search queries for Rust types and common functional patterns. These examples help users find relevant types and function signatures within the Rust documentation or codebase. ```text std::vec u32 -> bool Option, (T -> U) -> Option ``` -------------------------------- ### Start Listening for QUIC Connections (Rust) Source: https://docs.quic.tech/tokio_quiche/fn.listen_search=u32+-%3E+bool The `listen` function starts listening for inbound QUIC connections on the provided sockets. It converts each socket into a `QuicListener` with default parameters and then passes these to `listen_with_capabilities`. This function requires an iterator of sockets, connection parameters, a connection ID generator, and metrics. ```rust pub fn listen( sockets: impl IntoIterator, params: ConnectionParams<'_>, cid_generator: impl ConnectionIdGenerator<'static> + Clone, metrics: M, ) -> Result>> where S: TryInto, M: Metrics, { // ... function implementation ... } ``` -------------------------------- ### Start Listening for QUIC Connections (Rust) Source: https://docs.quic.tech/tokio_quiche/fn.listen_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This function starts listening for inbound QUIC connections on the provided sockets. Each socket is converted into a `QuicListener` with default parameters before being passed to `listen_with_capabilities`. It requires a generic socket type `S` that can be converted into a `QuicListener`, a `ConnectionParams` struct, a `ConnectionIdGenerator`, and a `Metrics` implementation. ```rust pub fn listen( sockets: impl IntoIterator, params: ConnectionParams<'_>, cid_generator: impl ConnectionIdGenerator<'static> + Clone, metrics: M, ) -> Result>> where S: TryInto, M: Metrics, { // Implementation details... } ``` -------------------------------- ### Tokio MPSC Unbounded Channel: Getting Length Example Source: https://docs.quic.tech/tokio_quiche/http3/driver/type.ClientEventStream_search=std%3A%3Avec Demonstrates how to retrieve the number of messages currently in an MPSC unbounded channel using `len()`. The example checks the length when the channel is empty and after one message is sent. ```rust use tokio::sync::mpsc; let (tx, rx) = mpsc::unbounded_channel(); assert_eq!(0, rx.len()); tx.send(0).unwrap(); assert_eq!(1, rx.len()); ``` -------------------------------- ### Functions Source: https://docs.quic.tech/tokio_quiche/quic/index_search=u32+-%3E+bool Entry points for establishing QUIC connections: `connect` for clients with default configuration and `connect_with_config` for custom configurations. ```APIDOC ## Functions ### `connect` **Description:** Connects to an HTTP/3 server using the provided `socket` and the default client configuration. **Method:** `POST` (or relevant HTTP method for initial connection setup) **Endpoint:** `/` (or relevant connection endpoint) ### `connect_with_config` **Description:** Connects to a QUIC server using the provided `socket` and a custom `ApplicationOverQuic` configuration. **Method:** `POST` (or relevant HTTP method for initial connection setup) **Endpoint:** `/` (or relevant connection endpoint) ``` -------------------------------- ### Get Stream Position Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=std%3A%3Avec Returns the current seek position from the start of the stream. This is part of the `Seek` trait implementation for boxed types. ```rust fn stream_position(&mut self) -> Result ``` -------------------------------- ### Example: Manually Create Box from Raw Pointer Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=u32+-%3E+bool Illustrates manually creating a `Box` from scratch using the global allocator and `Box::from_raw`. This involves allocating memory, writing a value, and then converting the raw pointer to a `Box`. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Get Handshake Start Time - Rust Source: https://docs.quic.tech/tokio_quiche/quic/struct.HandshakeInfo_search= Retrieves the time at which a QUIC connection was created from a HandshakeInfo instance. This method returns an `Instant` value. ```rust pub fn start_time(&self) -> Instant ``` -------------------------------- ### Iterate Over Readable Streams (Rust) Source: https://docs.quic.tech/tokio_quiche/quic/type.QuicheConnection_search= Provides an iterator over streams that currently have outstanding data to be read. Streams included are those that were readable at the time the iterator was created. To get updated information, a new iterator must be created. The example shows iterating and reading data from these streams. ```rust // Iterate over readable streams. for stream_id in conn.readable() { // Stream is readable, read until there's no more data. while let Ok((read, fin)) = conn.stream_recv(stream_id, &mut buf) { println!("Got {} bytes on stream {}", read, stream_id); } } ``` -------------------------------- ### Example: Recreate Box from Raw Pointer Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=u32+-%3E+bool Demonstrates how to safely recreate a `Box` from a raw pointer that was previously obtained using `Box::into_raw`. This ensures proper memory management and deallocation. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Settings and Configuration Source: https://docs.quic.tech/tokio_quiche/all_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E APIs for configuring QUIC and HTTP/3 settings, including connection parameters and TLS certificates. ```APIDOC ## Settings and Configuration ### Description APIs related to the configuration and settings for QUIC and HTTP/3 protocols. ### Structs - `settings::ConnectionParams` - `settings::Hooks` - `settings::QuicSettings` - `settings::TlsCertificatePaths` ### Enums - `settings::CertificateKind` ### Usage Notes These structures and enums define how QUIC and HTTP/3 connections are configured, including network parameters, security settings, and custom behavior hooks. Interaction with these settings would typically occur during connection establishment or through a configuration management API. ``` -------------------------------- ### Get Element Offset in Slice (Rust Nightly) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=std%3A%3Avec The `element_offset` method returns the index of an element within a slice using pointer arithmetic. It returns `None` if the element is not found at the start of an element. This API is experimental and requires the `substr_range` feature. It panics if `T` is zero-sized. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Handle QUIC Connection Establishment Callback (Rust) Source: https://docs.quic.tech/tokio_quiche/quic/connection/trait.ApplicationOverQuic The `on_conn_established` method within the `ApplicationOverQuic` trait is a callback function that gets invoked after a QUIC connection has been successfully established. Implementations of this method can be used to perform custom setup or initialization for the application logic immediately following the handshake. Errors returned from this method will halt the worker loop and initiate the connection closing process. ```rust fn on_conn_established( &mut self, qconn: &mut QuicheConnection, handshake_info: &HandshakeInfo, ) -> QuicResult<()>; ``` -------------------------------- ### SocketCapabilitiesBuilder Source: https://docs.quic.tech/tokio_quiche/socket/index_search=std%3A%3Avec Builder to enable Linux sockopts that enhance QUIC performance. ```APIDOC ## Struct SocketCapabilitiesBuilder ### Description Builder to enable Linux sockopts which improve QUIC performance. ### Method (Not applicable - this is a struct definition) ### Endpoint (Not applicable - this is a struct definition) ### Parameters (Not applicable - this is a struct definition) ### Request Example (Not applicable - this is a struct definition) ### Response #### Success Response (N/A) (Not applicable - this is a struct definition) #### Response Example (Not applicable - this is a struct definition) ``` -------------------------------- ### Start Full QUIC Connection Lifecycle Source: https://docs.quic.tech/tokio_quiche/struct.InitialQuicConnection_search=std%3A%3Avec Initiates and manages the entire lifecycle of a QUIC connection, from handshake to closure, within separate Tokio tasks. This method combines the functionality of `handshake` and `resume` into a single call, simplifying the process of establishing and running a connection. ```rust pub fn start(self, app: A) -> QuicConnection ``` -------------------------------- ### Iterate and Send on QUIC Paths Source: https://docs.quic.tech/tokio_quiche/quic/type.QuicheConnection_search= This example demonstrates how to iterate over available QUIC paths for a given local address and send data on each path. It uses `paths_iter` to get destination socket addresses and `send_on_path` to prepare data for sending. The loop continues until `quiche::Error::Done` is returned, indicating no more data can be sent on the current path, or until another error occurs. The prepared data is then sent over the network socket. ```rust for dest in conn.paths_iter(local) { loop { let (write, send_info) = match conn.send_on_path(&mut out, Some(local), Some(dest)) { Ok(v) => v, Err(quiche::Error::Done) => { // Done writing for this destination. break; }, Err(e) => { // An error occurred, handle it. break; }, }; socket.send_to(&out[..write], &send_info.to).unwrap(); } } ``` -------------------------------- ### Build Socket Capabilities for QUIC Performance (Rust) Source: https://docs.quic.tech/tokio_quiche/socket/struct.SocketCapabilitiesBuilder_search= Demonstrates how to use SocketCapabilitiesBuilder to configure Linux socket options for optimizing QUIC performance. This involves creating a builder, enabling specific sockopts like GSO, gro, and txtime, and finally consuming the builder to get the SocketCapabilities. ```rust use tokio_quiche::socket::{SocketCapabilitiesBuilder, SocketCapabilities}; use std::os::fd::AsFd; // Assume 'socket' is a type that implements AsFd, like a tokio::net::UdpSocket async fn configure_socket(socket: &S) -> Result> { let mut builder = SocketCapabilitiesBuilder::new(socket); // Enable Generic Segmentation Offload (GSO) builder.gso()?; // Enable Receive Buffer Overflow detection builder.check_udp_drop()?; // Enable transmit time control for QUIC pacing builder.txtime()?; // Enable wall-clock timestamp for received packets builder.rxtime()?; // Enable Generic Receive Offload (GRO) builder.gro()?; // Enable IP_PKTINFO for IPv4 outbound source IP control builder.ipv4_pktinfo()?; // Enable IP_RECVORIGDSTADDR for IPv4 original destination address reporting builder.ipv4_recvorigdstaddr()?; // Enable IPV6_RECVPKTINFO for IPv6 outbound source IP control builder.ipv6_pktinfo()?; // Enable IPV6_RECVORIGDSTADDR for IPv6 original destination address reporting builder.ipv6_recvorigdstaddr()?; // Disable kernel PMTUD and set DF flag for IPv4 builder.ip_mtu_discover_probe()?; // Disable kernel PMTUD and set DF flag for IPv6 builder.ipv6_mtu_discover_probe()?; // Check if non-local source binding is allowed (requires elevated permissions) let allows_nonlocal = builder.allows_nonlocal_source()?; if !allows_nonlocal { // Handle the case where non-local source binding is not enabled, // which might cause issues with PKTINFO sockopts. eprintln!("Warning: Non-local source binding is not enabled. PKTINFO sockopts may cause errors."); } // Enable rcvmark builder.rcvmark()?; // Consume the builder to get the final configuration let capabilities = builder.finish(); Ok(capabilities) } ``` -------------------------------- ### QUIC Listener Functions Source: https://docs.quic.tech/tokio_quiche/all_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions for setting up QUIC listeners to accept incoming connections. ```APIDOC ## QUIC Listener Functions ### Description Functions for creating and managing QUIC listeners. ### Methods - `listen` - `listen_with_capabilities` ### Functions #### `listen` - **Description**: Creates a standard QUIC listener. - **Method**: `POST` (or similar, depending on context) - **Endpoint**: `/quic/listen` #### `listen_with_capabilities` - **Description**: Creates a QUIC listener with specified capabilities. - **Method**: `POST` (or similar, depending on context) - **Endpoint**: `/quic/listen_with_capabilities` ### Parameters - **Path Parameters**: None - **Query Parameters**: None - **Request Body**: (Details would depend on specific implementation, e.g., address, port, capabilities) ### Request Example ```json { "address": "0.0.0.0", "port": 443, "capabilities": ["some_capability"] } ``` ### Response #### Success Response (200) - **listener_id** (string) - Identifier for the created listener. #### Response Example ```json { "listener_id": "some_listener_identifier" } ``` ``` -------------------------------- ### UnboundedReceiver Example Source: https://docs.quic.tech/tokio_quiche/http3/driver/type.ClientEventStream_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to use `poll_recv_many` with an `UnboundedReceiver` to receive multiple messages into a buffer. ```APIDOC ## Example Usage of `poll_recv_many` ### Description This example shows how to create a future that polls an `UnboundedReceiver` to receive multiple messages into a provided buffer up to a specified limit. ### Method `poll_recv_many` (used within a `Future` implementation) ### Endpoint N/A (This is a library usage example, not an API endpoint) ### Parameters None directly for this code block, but parameters are used within the `MyReceiverFuture` struct and its `impl Future`. #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```rust use std::task::{Context, Poll}; use std::pin::Pin; use tokio::sync::mpsc; use futures::Future; struct MyReceiverFuture<'a> { receiver: mpsc::UnboundedReceiver, buffer: &'a mut Vec, limit: usize, } impl<'a> Future for MyReceiverFuture<'a> { type Output = usize; // Number of messages received fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { let MyReceiverFuture { receiver, buffer, limit } = &mut *self; // Now `receiver` and `buffer` are mutable references, and `limit` is copied match receiver.poll_recv_many(cx, *buffer, *limit) { Poll::Pending => Poll::Pending, Poll::Ready(count) => Poll::Ready(count), } } } let (tx, rx) = mpsc::unbounded_channel::(); let mut buffer = Vec::new(); let my_receiver_future = MyReceiverFuture { receiver: rx, buffer: &mut buffer, limit: 3, }; for i in 0..10 { tx.send(i).expect("Unable to send integer"); } // This would typically be awaited in an async context // let count = my_receiver_future.await; // assert_eq!(count, 3); // assert_eq!(buffer, vec![0,1,2]) ``` ### Response #### Success Response (200) N/A (This is a library usage example) #### Response Example N/A ``` -------------------------------- ### Example: Manually Create Box from NonNull Pointer (Nightly) Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=u32+-%3E+bool Shows how to manually create a `Box` using the global allocator and `Box::from_non_null`. This involves allocating memory, creating a `NonNull` pointer, writing a value, and converting it to a `Box`. Requires the `box_vec_non_null` feature. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### listen_with_capabilities Source: https://docs.quic.tech/tokio_quiche/fn.listen_with_capabilities_search=u32+-%3E+bool Starts listening for inbound QUIC connections on the given `QuicListener`s. Each socket starts a separate tokio task to process and route inbound packets. ```APIDOC ## listen_with_capabilities ### Description Starts listening for inbound QUIC connections on the given `QuicListener`s. Each socket starts a separate tokio task to process and route inbound packets. This task emits connections on the respective `QuicConnectionStream` after receiving the client’s QUIC initial and (optionally) validating its IP address. The task shuts down when the returned stream is closed (or dropped) and all previously-yielded connections are closed. ### Method (Not specified in the provided text, likely a function call within a library) ### Endpoint (Not applicable for a library function) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (Not applicable for a library function) ### Response #### Success Response - **Vec>** - A vector of QUIC connection streams. #### Response Example (Not applicable for a library function) ``` -------------------------------- ### Connection Configuration Methods Source: https://docs.quic.tech/tokio_quiche/quic/type.QuicheConnection_search=u32+-%3E+bool Provides documentation for methods used to configure the QUIC connection, such as setting keylog writers, qlog writers, and session resumption. ```APIDOC ## Connection Configuration ### `set_keylog` Sets keylog output to the designated `Writer`. This needs to be called as soon as the connection is created, to avoid missing some early logs. #### Method ```rust pub fn set_keylog(&mut self, writer: Box) ``` #### Parameters - **writer** (Box) - The writer to which keylog information will be sent. ### `set_qlog` Sets qlog output to the designated `Writer`. Only events included in `QlogLevel::Base` are written. The serialization format is JSON-SEQ. This needs to be called as soon as the connection is created, to avoid missing some early logs. #### Method ```rust pub fn set_qlog(&mut self, writer: Box, title: String, description: String) ``` #### Parameters - **writer** (Box) - The writer to which qlog information will be sent. - **title** (String) - The title for the qlog session. - **description** (String) - A description for the qlog session. ### `set_qlog_with_level` Sets qlog output to the designated `Writer`. Only qlog events included in the specified `QlogLevel` are written. The serialization format is JSON-SEQ. This needs to be called as soon as the connection is created, to avoid missing some early logs. #### Method ```rust pub fn set_qlog_with_level(&mut self, writer: Box, title: String, description: String, qlog_level: QlogLevel) ``` #### Parameters - **writer** (Box) - The writer to which qlog information will be sent. - **title** (String) - The title for the qlog session. - **description** (String) - A description for the qlog session. - **qlog_level** (QlogLevel) - The verbosity level for qlog events. ### `qlog_streamer` Returns a mutable reference to the QlogStreamer, if it exists. #### Method ```rust pub fn qlog_streamer(&mut self) -> Option<&mut QlogStreamer> ``` #### Returns - Option<&mut QlogStreamer>: A mutable reference to the QlogStreamer, or None if it does not exist. ### `set_session` Configures the given session for resumption. On the client, this can be used to offer the given serialized session, as returned by `session()`, for resumption. This must only be called immediately after creating a connection, that is, before any packet is sent or received. #### Method ```rust pub fn set_session(&mut self, session: &[u8]) -> Result<(), Error> ``` #### Parameters - **session** (&[u8]) - The serialized session data. #### Returns - Result<(), Error>: Ok if the session was set successfully, or an Error. ### `set_max_idle_timeout` Sets the `max_idle_timeout` transport parameter, in milliseconds. This must only be called immediately after creating a connection, that is, before any packet is sent or received. The default value is infinite, that is, no timeout is used unless already configured when creating the connection. #### Method ```rust pub fn set_max_idle_timeout(&mut self, v: u64) -> Result<(), Error> ``` #### Parameters - **v** (u64) - The maximum idle timeout in milliseconds. #### Returns - Result<(), Error>: Ok if the timeout was set successfully, or an Error. ``` -------------------------------- ### Rust Unsafe Slice as_chunks_unchecked Example Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=u32+-%3E+bool Provides examples of the `unsafe fn as_chunks_unchecked` method for Rust slices, which splits a slice into fixed-size array chunks. This function requires the slice length to be an exact multiple of the chunk size (`N`) and `N` to be non-zero. The examples demonstrate safe usage and mention why certain calls would be unsound. ```rust let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!']; let chunks: &[[char; 1]] = unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]); let chunks: &[[char; 3]] = unsafe { slice.as_chunks_unchecked() }; assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]); ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.quic.tech/tokio_quiche/socket/struct.SocketCapabilitiesBuilder_search= This section covers the `TryFrom` and `TryInto` trait implementations for type conversions. ```APIDOC ### impl TryFrom for T #### Description Provides a way to attempt conversion from type `U` into type `T`, returning a `Result`. #### Type Alias - **Error** (>::Error) - The type returned in the event of a conversion error. #### Method - **try_from**(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T #### Description Provides a way to attempt conversion from type `T` into type `U`, returning a `Result`. #### Type Alias - **Error** (>::Error) - The type returned in the event of a conversion error. #### Method - **try_into**(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### Get Underlying Array Reference (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Attempts to get a reference to the underlying array if its length `N` exactly matches the slice's length. Returns `None` otherwise. ```rust let arr = [1, 2, 3]; let slice = &arr[..]; // This will succeed because N matches the slice length let arr_ref: Option<&[i32; 3]> = slice.as_array::<3>(); assert!(arr_ref.is_some()); // This will fail because N does not match let arr_ref_fail: Option<&[i32; 2]> = slice.as_array::<2>(); assert!(arr_ref_fail.is_none()); ``` -------------------------------- ### Handle QUIC Connection Establishment (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/type.ClientH3Driver_search=u32+-%3E+bool A callback function executed after a successful QUIC handshake. It allows for customization of the ApplicationOverQuic implementation. ```rust fn on_conn_established( &mut self, quiche_conn: &mut QuicheConnection, handshake_info: &HandshakeInfo, ) -> QuicResult<()> ``` -------------------------------- ### Get Element or Subslice by Index (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Safely gets a reference to an element or subslice using various index types (position or range). Returns None if the index is out of bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Get Current Capacity of Tokio MPSC Channel Source: https://docs.quic.tech/tokio_quiche/http3/driver/type.InboundFrameStream_search= Demonstrates how to use `rx.capacity()` to get the current available buffer space in an MPSC channel. This value changes as messages are sent and received. ```rust use tokio::sync::mpsc; let (tx, mut rx) = mpsc::channel::<()>(5); assert_eq!(rx.capacity(), 5); // Making a reservation drops the capacity by one. let permit = tx.reserve().await.unwrap(); assert_eq!(rx.capacity(), 4); assert_eq!(rx.len(), 0); // Sending and receiving a value increases the capacity by one. permit.send(()); assert_eq!(rx.len(), 1); rx.recv().await.unwrap(); assert_eq!(rx.capacity(), 5); // Directly sending a message drops the capacity by one. tx.send(()).await.unwrap(); assert_eq!(rx.capacity(), 4); assert_eq!(rx.len(), 1); // Receiving the message increases the capacity by one. rx.recv().await.unwrap(); assert_eq!(rx.capacity(), 5); assert_eq!(rx.len(), 0); ``` -------------------------------- ### connect_with_config Source: https://docs.quic.tech/tokio_quiche/quic/fn.connect_with_config_search=std%3A%3Avec Establishes a QUIC connection to a server using a provided socket, host, connection parameters, and an application handler. ```APIDOC ## connect_with_config ### Description Connects to a QUIC server using `socket` and the provided `ApplicationOverQuic`. When the future resolves, the connection has completed its handshake and `app` is running in the worker task. In case the handshake failed, we close the connection automatically and the future will resolve with an error. ### Method ASYNC FUNCTION ### Endpoint N/A (This is a function call, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // This is a Rust function signature, not a typical request body example. // Actual usage would involve concrete types for Socket, ConnectionParams, and ApplicationOverQuic. pub async fn connect_with_config( socket: Socket, host: Option<&str>, params: &ConnectionParams<'_>, app: App, ) -> QuicResult where Tx: DatagramSocketSend + Send + 'static, Rx: DatagramSocketRecv + Unpin + 'static, App: ApplicationOverQuic, { // ... implementation details ... } ``` ### Response #### Success Response (QuicResult) - **QuicConnection** - Represents an established QUIC connection. #### Response Example ```rust // The function returns a Result, so success is represented by Ok(QuicConnection) Ok(QuicConnection { /* ... connection details ... */ }) ``` ### Note tokio-quiche currently only supports one client connection per socket. Sharing a socket among multiple connections will lead to lost packets as both connections try to read from the shared socket. ``` -------------------------------- ### apply_max_capabilities Method Source: https://docs.quic.tech/tokio_quiche/socket/struct.QuicListener_search=u32+-%3E+bool Tries to enable all sockopts supported by the crate for this socket. ```APIDOC ## Method: apply_max_capabilities ### Description Tries to enable all sockopts supported by the crate for this socket. See `SocketCapabilities::apply_all_and_get_compatibility` for details. ### Method `&mut self` ### Endpoint N/A (Instance method) ### Parameters None ### Request Body None ### Response None (Modifies the `QuicListener` in place) ### Request Example ```rust // Assuming `listener` is a mutable reference to a QuicListener instance listener.apply_max_capabilities(); ``` ### Response Example N/A ``` -------------------------------- ### Tokio MPSC Unbounded Channel: Checking Emptiness Example Source: https://docs.quic.tech/tokio_quiche/http3/driver/type.ClientEventStream_search=std%3A%3Avec Shows how to check if an MPSC unbounded channel is empty using `is_empty()`. The example verifies the channel's state when initially empty and after a message has been sent. ```rust use tokio::sync::mpsc; let (tx, rx) = mpsc::unbounded_channel(); assert!(rx.is_empty()); tx.send(0).unwrap(); assert!(!rx.is_empty()); ``` -------------------------------- ### Implement Default for Http3Settings - Rust Source: https://docs.quic.tech/tokio_quiche/http3/settings/struct.Http3Settings Provides a default configuration for Http3Settings, useful for initializing settings without specifying every parameter. ```rust impl Default for Http3Settings { fn default() -> Http3Settings; } ``` -------------------------------- ### Start QUIC Listeners with tokio_quiche Source: https://docs.quic.tech/tokio_quiche/fn.listen This function starts listening for inbound QUIC connections on the provided sockets. Each socket is converted into a QuicListener with default parameters and then passed to listen_with_capabilities. It requires an iterator of sockets, connection parameters, a connection ID generator, and metrics. ```rust pub fn listen( sockets: impl IntoIterator, params: ConnectionParams<'_>, cid_generator: impl ConnectionIdGenerator<'static> + Clone, metrics: M, ) -> Result>> where S: TryInto, M: Metrics, { ``` -------------------------------- ### Type Conversion and Cloning Utilities Source: https://docs.quic.tech/tokio_quiche/buf_factory/struct.BufFactory_search=u32+-%3E+bool Documentation for utility functions related to type conversion (TryFrom, TryInto) and cloning into a target. ```APIDOC ## UTILITY FUNCTIONS ### `clone_into` #### Description Uses borrowed data to replace owned data, usually by cloning. #### Method N/A (Function signature) #### Endpoint N/A (Function signature) ### `TryFrom` for `T` #### Description Provides a way to perform fallible conversions from one type to another. #### Type `Error` - **Error** (Infallible) - The type returned in the event of a conversion error. #### Method `try_from` - **value** (U) - The value to convert. - **Returns**: Result ### `TryInto` for `T` #### Description Provides a way to attempt a conversion into another type. #### Type `Error` - **Error** (*>::Error*) - The type returned in the event of a conversion error. #### Method `try_into` - **self** (T) - The value to convert. - **Returns**: Result ``` -------------------------------- ### Box: into_non_null and Memory Management Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=std%3A%3Avec Illustrates converting a `Box` to `NonNull` and back, emphasizing manual memory management. It requires the `box_vec_non_null` nightly feature. The first example shows automatic cleanup, and the second and third examples demonstrate manual cleanup of the memory. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` ```rust #![feature(box_vec_non_null)] use std::alloc::{dealloc, Layout}; let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { non_null.drop_in_place(); dealloc(non_null.as_ptr().cast::(), Layout::new::()); } ``` ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### POST /api/allocator_api/new_uninit_in Source: https://docs.quic.tech/tokio_quiche/type.BoxError_search=u32+-%3E+bool Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API. ```APIDOC ## POST /api/allocator_api/new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator. This is a nightly-only experimental API. ### Method POST ### Endpoint /api/allocator_api/new_uninit_in ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **alloc** (A) - The allocator to use. ### Request Example ```json { "alloc": "System" } ``` ### Response #### Success Response (200) - **Box, A>** - A Box with uninitialized contents allocated using the provided allocator. #### Response Example ```json { "uninitialized_memory": "..." } ``` ``` -------------------------------- ### Module: raw Source: https://docs.quic.tech/tokio_quiche/quic/index_search=u32+-%3E+bool Provides helpers for wrapping existing `quiche::Connection` objects. ```APIDOC ## Module: raw Provides helper functions and types for wrapping existing `quiche::Connection` objects, allowing them to be used within the tokio-quiche framework. ``` -------------------------------- ### starts_with Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue Checks if a slice starts with a given prefix. ```APIDOC ## starts_with ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Method `starts_with` ### Endpoint N/A (Method on a slice) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(!v.starts_with(&[50])); ``` ### Response #### Success Response (200) `bool` - Returns `true` if the slice starts with the given needle, `false` otherwise. #### Response Example ```json { "starts_with": true } ``` ``` -------------------------------- ### Remove Prefix from Slice (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a new slice with the specified prefix removed if the original slice starts with it. If the prefix is empty, the original slice is returned. If the prefix matches the entire slice, an empty slice is returned. Returns `None` if the slice does not start with the prefix. ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` -------------------------------- ### InitialQuicConnection Methods Source: https://docs.quic.tech/tokio_quiche/struct.InitialQuicConnection_search= Methods for interacting with an initial QUIC connection, including accessing addresses, stats, and managing the handshake process. ```APIDOC ## InitialQuicConnection `InitialQuicConnection` represents a QUIC connection that has not yet performed a handshake. This type is primarily used for server-side connections. ### Methods #### `local_addr(&self) -> SocketAddr` **Description**: Returns the local network address the connection is listening on. **Method**: GET **Endpoint**: N/A (Instance method) #### `peer_addr(&self) -> SocketAddr` **Description**: Returns the remote network address of the connected peer. **Method**: GET **Endpoint**: N/A (Instance method) #### `audit_log_stats(&self) -> Arc` **Description**: Provides a handle to the `QuicAuditStats` for this connection, which are updated throughout the connection's lifetime. **Note**: This getter allows retrieving a handle early to read stats after the connection closes. **Method**: GET **Endpoint**: N/A (Instance method) #### `stats(&self) -> &Arc>` **Description**: Returns a handle to the `QuicConnectionStats` for this connection. **Note**: Initially reflects the state at creation; updated upon connection closure. **Method**: GET **Endpoint**: N/A (Instance method) #### `handshake_fut(self, app: A) -> (QuicConnection, BoxFuture<'static, Result, M, A>>>)` **Description**: Creates a future that drives the connection's handshake process. This offers more control than the `handshake` function, suitable for advanced usage. **Method**: POST **Endpoint**: N/A (Instance method) **Request Body**: - **app** (A: `ApplicationOverQuic`) - The application trait object to handle application-level data. #### `handshake(self, app: A) -> Result<(QuicConnection, Running, M, A>)>` **Description**: Performs the QUIC handshake in a separate Tokio task and waits for its completion. Returns connection metadata and a `Running` struct to resume the paused connection. **Method**: POST **Endpoint**: N/A (Instance method) **Request Body**: - **app** (A: `ApplicationOverQuic`) - The application trait object to handle application-level data. **Response**: #### Success Response (200) - **QuicConnection**: Metadata about the established connection. - **Running**: An opaque struct to resume the paused connection. #### `resume(pre_running: Running, M, A>)` **Description**: Resumes a QUIC connection that was paused after a successful handshake. **Method**: POST **Endpoint**: N/A (Instance method) **Request Body**: - **pre_running** (Running, M, A>) - The opaque struct returned by a prior handshake operation. #### `start(self, app: A) -> QuicConnection` **Description**: Drives the QUIC connection through its entire lifecycle, from handshake to closure, using separate Tokio tasks. This method combines the functionality of `handshake` and `resume`. **Method**: POST **Endpoint**: N/A (Instance method) **Request Body**: - **app** (A: `ApplicationOverQuic`) - The application trait object to handle application-level data. **Response**: #### Success Response (200) - **QuicConnection**: Metadata about the established connection. ``` -------------------------------- ### Implement Default for Http3Settings in Rust Source: https://docs.quic.tech/tokio_quiche/http3/settings/struct.Http3Settings_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides the default() method for the Http3Settings struct, returning a default configuration. This simplifies initialization by providing sensible default values for all settings. ```rust impl Default for Http3Settings { fn default() -> Http3Settings { // ... implementation details ... } } ``` -------------------------------- ### listen_with_capabilities Source: https://docs.quic.tech/tokio_quiche/fn.listen_with_capabilities Starts listening for inbound QUIC connections on the given QuicListener's. Each socket starts a separate tokio task to process and route inbound packets. This task emits connections on the respective QuicConnectionStream after receiving the client's QUIC initial and (optionally) validating its IP address. ```APIDOC ## listen_with_capabilities ### Description Starts listening for inbound QUIC connections on the given `QuicListener`s. Each socket starts a separate tokio task to process and route inbound packets. This task emits connections on the respective `QuicConnectionStream` after receiving the client’s QUIC initial and (optionally) validating its IP address. The task shuts down when the returned stream is closed (or dropped) and all previously-yielded connections are closed. ### Method PUBLISHED FUNCTION ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (Result>>) - **sockets** (impl IntoIterator) - An iterator of QuicListener instances to listen on. - **params** (ConnectionParams<'_>) - Connection parameters for establishing QUIC connections. - **cid_generator** (impl ConnectionIdGenerator<'static> + Clone) - A generator for connection IDs. - **metrics** (M where M: Metrics) - A metrics collector. #### Response Example N/A ``` -------------------------------- ### Get Underlying Array Reference from Slice (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue_search=std%3A%3Avec Shows how to attempt to get a reference to the underlying array from a slice using `as_array`. This method returns `Some` only if the specified array size `N` exactly matches the slice's length, otherwise it returns `None`. ```rust let data = [1, 2, 3]; let slice = &data[..]; // This will succeed because N matches the slice length let array_ref: Option<&[i32; 3]> = slice.as_array::<3>(); assert!(array_ref.is_some()); // This will fail because N does not match let wrong_size_ref: Option<&[i32; 2]> = slice.as_array::<2>(); assert!(wrong_size_ref.is_none()); ``` -------------------------------- ### Implement InitialQuicConnection Methods in Rust Source: https://docs.quic.tech/tokio_quiche/struct.InitialQuicConnection Provides implementations for key methods of the `InitialQuicConnection` struct in Rust. These methods facilitate retrieving connection addresses, auditing and accessing connection statistics, and managing the QUIC handshake process through various strategies like spawning tasks or returning futures. ```rust impl InitialQuicConnection where Tx: DatagramSocketSend + Send + 'static + ?Sized, M: Metrics, { pub fn local_addr(&self) -> SocketAddr pub fn peer_addr(&self) -> SocketAddr pub fn audit_log_stats(&self) -> Arc pub fn stats(&self) -> &Arc> pub fn handshake_fut( self, app: A, ) -> (QuicConnection, BoxFuture<'static, Result, M, A>>>) pub async fn handshake( self, app: A, ) -> Result<(QuicConnection, Running, M, A>)> pub fn resume( pre_running: Running, M, A>) pub fn start(self, app: A) -> QuicConnection } ``` -------------------------------- ### Implement Clone for Http3Settings - Rust Source: https://docs.quic.tech/tokio_quiche/http3/settings/struct.Http3Settings Provides the ability to clone Http3Settings instances, allowing for duplication of configuration. This is essential for scenarios where configurations need to be copied or shared. ```rust impl Clone for Http3Settings { fn clone(&self) -> Http3Settings; fn clone_from(&mut self, source: &Self); } ``` -------------------------------- ### Get Underlying Array Reference if Length Matches (Rust) Source: https://docs.quic.tech/tokio_quiche/http3/driver/struct.RawPriorityValue Explains how to get a reference to the underlying array if the slice's length exactly matches the requested array size N. Returns None if the lengths do not match. This can be useful for converting slices back to arrays when the size is known. ```rust let slice = [1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array::<3>(); assert!(array_ref.is_some()); let wrong_size_ref: Option<&[i32; 2]> = slice.as_array::<2>(); assert!(wrong_size_ref.is_none()); ```