### Running Client Example Output Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/crypto/struct.CryptoProvider.html Demonstrates the initial output from running the client example, showing the selected ciphersuite and the start of an HTTP response. ```bash $ cargo run --example client | head -3 Current ciphersuite: TLS13_CHACHA20_POLY1305_SHA256 HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 19899 ``` -------------------------------- ### Example: Triggering a Start Event Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/input/bei/struct.Start.html Demonstrates how to set up an observer to react to the Start event for a 'Throw' action, typically used for single-press actions. ```rust app.add_observer(throw); app.world_mut().spawn(( Player, actions!(Player[Action::::new(), bindings![KeyCode::KeyF]]), )); /// Triggered only once on the first press, similar to `just_pressed` in `bevy_input`. /// /// It will not trigger again until the key is released and pressed again. fn throw(throw: On>, players: Query<(&Transform, &mut Health)>) { // ... } ``` -------------------------------- ### Example: Throwing an item on button press Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.Start.html Demonstrates how to use the Start event to trigger a one-time action, like throwing an item when a button is pressed. This is similar to `just_pressed` in `bevy_input`. ```rust app.add_observer(throw); app.world_mut().spawn(( Player, actions!(Player[Action::::new(), bindings![KeyCode::KeyF]]), )); /// Triggered only once on the first press, similar to `just_pressed` in `bevy_input`. /// /// It will not trigger again until the key is released and pressed again. fn throw(throw: On>, players: Query<(&Transform, &mut Health)>) { // ... } ``` -------------------------------- ### File Seek Example Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/trait.Seek.html Demonstrates how to open a file and move its cursor to a specific byte offset from the start using the `seek` method. ```rust use std::io; use std::io::prelude::*; use std::fs::File; use std::io::SeekFrom; fn main() -> io::Result<()> { let mut f = File::open("foo.txt")?; // move the cursor 42 bytes from the start of the file f.seek(SeekFrom::Start(42)?); Ok(()) } ``` -------------------------------- ### Finish Plugin Setup Source: https://docs.rs/lightyear/0.26.4/lightyear/link/struct.LinkPlugin.html Completes the LinkPlugin's setup after all registered plugins are ready, useful for plugins dependent on asynchronous setup. ```rust fn finish(&self, _app: &mut App) Finish adding this plugin to the `App`, once all plugins registered are ready. This can be useful for plugins that depends on another plugin asynchronous setup, like the renderer. ``` -------------------------------- ### Start ServerConfig Creation Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/server/struct.ServerConfig.html Initiates the creation of a ServerConfig using the builder pattern. This is the recommended way to start configuring a WebSocketServer. ```rust pub const fn builder() -> ServerConfigBuilder ``` -------------------------------- ### Combo Example Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/input/bei/struct.Combo.html Example demonstrating how to use the Combo struct to create a double-click action. ```APIDOC ## §Examples Double click: ```rust use bevy::prelude::*; use bevy_enhanced_input::prelude::*; world.spawn(( Menu, Actions::::spawn(SpawnWith(|context: &mut ActionSpawner<_>| { let click = context .spawn((Action::::new(), bindings![MouseButton::Left])) .id(); context.spawn(( Action::::new(), Combo::default().with_step(click).with_step(click), )); })), )); #[derive(InputAction)] #[action_output(bool)] struct Click; #[derive(InputAction)] #[action_output(bool)] struct DoubleClick; #[derive(Component)] struct Menu; ``` ``` -------------------------------- ### Create GET Request Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/handshake/client/type.Request.html Shows how to create a GET request for a given URI using the `get()` constructor. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Client Creation Example Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/client/struct.Client.html Demonstrates how to create a new client instance and initiate a connection. ```rust let mut client = Client::new(&token_bytes).unwrap(); client.connect(); ``` -------------------------------- ### Get Item Install Info Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/steamworks/struct.UGC.html Retrieves installation information for a workshop item. ```rust pub fn item_install_info(&self, item: PublishedFileId) -> Option ``` -------------------------------- ### app_install_dir Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/steamworks/struct.Apps.html Gets the installation directory for a given application ID, even if it's not installed. ```APIDOC ## app_install_dir ### Description Returns the installation folder of the app with the given ID. This works even if the app isn’t installed, returning where it would be installed in the default location. ### Method `app_install_dir` ### Parameters #### Path Parameters - **app_id** (AppId) - Required - The ID of the application. ### Response #### Success Response - **String** - The installation directory path. ``` -------------------------------- ### Get App Installation Directory Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/steamworks/struct.Apps.html Returns the installation directory for a given application ID. This function works even if the app is not installed, indicating its default installation path. ```rust pub fn app_install_dir(&self, app_id: AppId) -> String ``` -------------------------------- ### Creating and Configuring a Client Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/client/struct.ClientConfig.html Example of creating a ClientConfig with custom settings and initializing a client connection. ```rust let cfg = ClientConfig::with_context(MyContext {}) .num_disconnect_packets(10) .packet_send_rate(0.1) .on_state_change(|from, to, _ctx| { if let (ClientState::SendingChallengeResponse, ClientState::Connected) = (from, to) { println!("client connected to server"); } }); let mut client = Client::with_config(&token_bytes, cfg).unwrap(); client.connect(); ``` -------------------------------- ### Example Client Output Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/crypto/struct.CryptoProvider.html This example shows the initial output from a client application that uses a custom crypto provider. It displays the negotiated ciphersuite and the first few lines of an HTTP response. ```bash $ cargo run --example client | head -3 Current ciphersuite: TLS13_CHACHA20_POLY1305_SHA256 HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 ``` -------------------------------- ### Get Oldest Value (Start) from ConfirmedHistory Source: https://docs.rs/lightyear/0.26.4/lightyear/interpolation/interpolation_history/struct.ConfirmedHistory.html Retrieves the oldest value in the history buffer, used as the starting point for interpolation. ```rust pub fn start(&self) -> Option<(Tick, &C)> ``` -------------------------------- ### Plugin::finish Implementation Source: https://docs.rs/lightyear/0.26.4/lightyear/input/client/struct.ClientInputPlugin.html Completes the plugin's setup after all other plugins are ready. Useful for plugins dependent on asynchronous setup. ```rust fn finish(&self, _app: &mut App) ``` -------------------------------- ### Request::get() Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/http/struct.Request.html Creates a new Builder initialized with a GET method and the specified URI. This is a convenient shortcut for starting a GET request. ```APIDOC ## Request::get() ### Description Creates a new `Builder` initialized with a GET method and the given URI. This method returns an instance of `Builder` which can be used to create a `Request`. ### Method Associated function ### Parameters - **uri** (T): The URI for the request. Must be convertible into `http::Uri`. ### Request Example ```rust use http::Request; let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` ``` -------------------------------- ### Initialize and Open WebSocket Server Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/server/struct.WebSocketServer.html Demonstrates how to create and configure a WebSocket server using ServerConfig and then spawn it as an EntityCommand. This snippet shows both using Bevy's Commands and direct mutable World access. ```rust use { aeronet_websocket::server::{Identity, ServerConfig, WebSocketServer}, bevy_ecs::prelude::*, }; // set up a self-signed certificate to identify this server let identity = Identity::self_signed(["localhost", "127.0.0.1", "::1"]).unwrap(); let config = ServerConfig::builder() .with_bind_default(12345) // server port .with_identity(identity); // using `Commands` commands.spawn_empty().queue(WebSocketServer::open(config)); // using mutable `World` access let server = world.spawn_empty().id(); WebSocketServer::open(config).apply(world.entity_mut(server)); ``` -------------------------------- ### Get Stream Position Example Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/trait.Seek.html Illustrates how to get the current cursor position within a buffered file stream before and after reading a line. ```rust use std::{ io::{self, BufRead, BufReader, Seek}, fs::File, }; fn main() -> io::Result<()> { let mut f = BufReader::new(File::open("foo.txt")?); let before = f.stream_position()?; f.read_line(&mut String::new())?; let after = f.stream_position()?; println!("The first line was {} bytes long", after - before); Ok(()) } ``` -------------------------------- ### Server::new Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/struct.Server.html Creates a new server instance with a default configuration. Requires a protocol ID and a private key. ```APIDOC ## Server::new ### Description Create a new server with a default configuration. For a custom configuration, use `Server::with_config` instead. ### Method `pub fn new(protocol_id: u64, private_key: [u8; 32]) -> Result` ### Parameters * `protocol_id` (u64) - The protocol identifier for the server. * `private_key` ([u8; 32]) - The private key used for cryptographic operations. ### Returns * `Result` - A `Result` containing the new `Server` instance or an `Error` if creation failed. ``` -------------------------------- ### Server with Custom Configuration Example Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/struct.Server.html Creates a new server instance with a custom configuration, including context and a connection callback. This is useful for applications requiring specific server behaviors and state management. ```rust let private_key = generate_key(); let protocol_id = 0x123456789ABCDEF0; let cfg = ServerConfig::with_context(42).on_connect(|idx, _, _user_data, ctx| { assert_eq!(ctx, &42); }); let server = Server::with_config(protocol_id, private_key, cfg).unwrap(); ``` -------------------------------- ### Get Port as String Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/http/uri/struct.Port.html Retrieves the port number as a string slice. This example shows how to get the port component as a string after parsing an authority. ```rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_str(), "80"); ``` -------------------------------- ### Example Usage of WebSocketConfig Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/protocol/struct.WebSocketConfig.html Demonstrates how to create and configure a WebSocketConfig instance using builder-style methods to set buffer sizes. ```rust let conf = WebSocketConfig::default() .read_buffer_size(256 * 1024) .write_buffer_size(256 * 1024); ``` -------------------------------- ### Slice Length Example Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.Bindings.html Demonstrates how to get the number of elements in a slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### new Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/struct.KeyLogFile.html Constructs a new KeyLogFile instance. This involves inspecting the SSLKEYLOGFILE environment variable and attempting to open the specified file for writing. ```APIDOC ### impl KeyLogFile #### pub fn new() -> KeyLogFile Makes a new `KeyLogFile`. The environment variable is inspected and the named file is opened during this call. ``` -------------------------------- ### Vector Length Example Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.Bindings.html Illustrates how to get the number of elements currently in a vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Get Stream Length Example (Nightly) Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/trait.Seek.html Demonstrates how to get the current length of a file stream in bytes using the experimental `stream_len` method. Note: This API is nightly-only. ```rust #![feature(seek_stream_len)] use std::{ io::{self, Seek}, fs::File, }; fn main() -> io::Result<()> { let mut f = File::open("foo.txt")?; let len = f.stream_len()?; println!("The file is currently {len} bytes long"); Ok(()) } ``` -------------------------------- ### ServerConfig Certificate Configuration Example Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/struct.ConfigBuilder.html Illustrates the configuration process for a ServerConfig, including setting up client authentication requirements and providing a server certificate. ```APIDOC ## ServerConfig Certificate Configuration ### Description This section details how to configure certificate verification and certificate sending for a server. ### Certificate Verification (Client Authentication Requirement) Configure certificate verification by calling one of: * `ConfigBuilder::with_no_client_auth` - To not require client authentication (most common). * `ConfigBuilder::with_client_cert_verifier` - To use a custom verifier. ### Certificate Sending Configure certificate sending by calling one of: * `ConfigBuilder::with_single_cert` - To send a specific certificate. * `ConfigBuilder::with_single_cert_with_ocsp` - To send a specific certificate, plus stapled OCSP. * `ConfigBuilder::with_cert_resolver` - To send a certificate chosen dynamically. ### Example ```rust use rustls::{ServerConfig, Certificate, PrivateKey}; // Assume certs is a Vec and private_key is a rustls::PrivateKey let certs: Vec = vec![]; let private_key: PrivateKey = PrivateKey(vec![]); let server_config = ServerConfig::builder() .with_no_client_auth() .with_single_cert(certs, private_key) .expect("bad certificate/key"); ``` ``` -------------------------------- ### Example Usage of config_and_key_from_iter Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/pki_types/struct.EchConfigListBytes.html Demonstrates how to use `config_and_key_from_iter` with a PEM file iterator to obtain ECH configuration and private key. ```rust let (config, key) = EchConfigListBytes::config_and_key_from_iter( PemObject::pem_file_iter("tests/data/ech.pem").unwrap() ).unwrap(); ``` -------------------------------- ### Get Rollback Start Tick Source: https://docs.rs/lightyear/0.26.4/lightyear/prediction/manager/struct.PredictionManager.html Retrieves the tick at which the current rollback state began. ```rust pub fn get_rollback_start_tick(&self) -> Option ``` -------------------------------- ### Client::new Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/client/struct.Client.html Creates a new client instance with default configuration. Requires a connection token obtained from a web backend. ```APIDOC ## Client::new ### Description Creates a new client with a default configuration. ### Signature `pub fn new(token_bytes: &[u8]) -> Result` ### Parameters * `token_bytes` (`&[u8]`) - A byte slice representing the connection token. ### Returns * `Result` - Ok containing the new Client on success, or an Error on failure. ### Example ```rust // Generate a connection token for the client let private_key = generate_key(); let token_bytes = ConnectToken::build("127.0.0.1:0", 0, 0, private_key) .generate() .unwrap() .try_into_bytes() .unwrap(); let mut client = Client::new(&token_bytes).unwrap(); ``` ``` -------------------------------- ### Get Iterator Over Slice Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/pki_types/struct.Der.html Returns an iterator that yields references to all items in the slice from start to end. ```rust let slice = &[1, 2, 3]; let mut iter = slice.iter(); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), None); ``` -------------------------------- ### Create an Instant Source: https://docs.rs/lightyear/0.26.4/lightyear/core/time/struct.Instant.html Get the current time as an Instant. This is the starting point for measuring elapsed time. ```rust use std::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Basic ClientConfig Builder Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/struct.ConfigBuilder.html Demonstrates the basic usage of ClientConfig::builder() to start building a client configuration. ```rust use rustls::{ClientConfig, ServerConfig}; ClientConfig::builder() // ... ``` -------------------------------- ### Getting Relationship Accessor Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Provides a `ComponentRelationshipAccessor` for working with relationships in dynamic contexts, if applicable to the `Starting` component. ```rust fn relationship_accessor() -> Option>; ``` -------------------------------- ### Plugin::ready Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/struct.MetricsPlugin.html Checks if the plugin has finished its setup. ```APIDOC ## Plugin::ready ### Description Has the plugin finished its setup? This can be useful for plugins that need something asynchronous to happen before they can finish their setup, like the initialization of a renderer. Once the plugin is ready, `finish` should be called. ### Method `fn ready(&self, _app: &App) -> bool` ### Parameters * `_app` (&App) - A reference to the App. ### Returns `bool` - True if the plugin is ready, false otherwise. ``` -------------------------------- ### ServerConfig with Context and on_connect Callback Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/struct.ServerConfig.html This example demonstrates how to create a ServerConfig with a custom context (a thread-safe counter) and attach an on_connect callback that modifies this context. The callback is executed when a client connects. ```rust use std::sync::{Arc, Mutex}; use lightyear_netcode::{Server, ServerConfig}; let thread_safe_counter = Arc::new(Mutex::new(0)); let cfg = ServerConfig::with_context(thread_safe_counter).on_connect(|idx, _, _, ctx| { let mut counter = ctx.lock().unwrap(); *counter += 1; println!("client {} connected, counter: {idx}", counter); }); let server = Server::with_config(protocol_id, private_key, cfg).unwrap(); ``` -------------------------------- ### match_indices Examples Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/protocol/frame/struct.Utf8Bytes.html Demonstrates `match_indices` for finding all disjoint matches of a pattern and their starting indices within a string slice. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Basic ServerConfig Builder Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/struct.ConfigBuilder.html Demonstrates the basic usage of ServerConfig::builder() to start building a server configuration. ```rust use rustls::{ClientConfig, ServerConfig}; ServerConfig::builder() // ... ``` -------------------------------- ### Get Uri Query String Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/http/struct.Uri.html Extracts the query string from a Uri, starting after the '?'. Returns None if no query string is present. ```rust let uri: Uri = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&key2=value2")); ``` -------------------------------- ### Get Port as u16 Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/http/uri/struct.Port.html Retrieves the port number as a u16. This example demonstrates parsing an authority string and extracting the port. ```rust let authority: Authority = "example.org:80".parse().unwrap(); let port = authority.port().unwrap(); assert_eq!(port.as_u16(), 80); ``` -------------------------------- ### New Client with Default Configuration Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/client/struct.Client.html Creates a new client with default settings. Requires a connection token generated from a private key. ```rust // Generate a connection token for the client let private_key = generate_key(); let token_bytes = ConnectToken::build("127.0.0.1:0", 0, 0, private_key) .generate() .unwrap() .try_into_bytes() .unwrap(); let mut client = Client::new(&token_bytes).unwrap(); ``` -------------------------------- ### Getting on_remove Component Hook Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Retrieves the `on_remove` hook for the `Starting` component if defined. This hook is executed when the component is removed from an entity. ```rust fn on_remove() -> Option fn(DeferredWorld<'w>, HookContext)>; ``` -------------------------------- ### Getting on_insert Component Hook Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Retrieves the `on_insert` hook for the `Starting` component if defined. This hook is executed when a value is inserted for the component. ```rust fn on_insert() -> Option fn(DeferredWorld<'w>, HookContext)>; ``` -------------------------------- ### connect_async Usage Example Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/fn.connect_async.html Connect to a WebSocket server with custom headers. This example demonstrates how to create a request, add headers, and then establish an asynchronous connection using `connect_async`. Requires the `websocket` feature flag. ```rust use tungstenite::http::{Method, Request}; use tokio_tungstenite::connect_async; let mut request = "wss://api.example.com".into_client_request().unwrap(); request.headers_mut().insert("api-key", "42".parse().unwrap()); let (stream, response) = connect_async(request).await.unwrap(); ``` -------------------------------- ### Getting on_add Component Hook Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Retrieves the `on_add` hook for the `Starting` component if defined. This hook is executed when the component is added to an entity. ```rust fn on_add() -> Option fn(DeferredWorld<'w>, HookContext)>; ``` -------------------------------- ### Rust Slice as_array Example Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/pki_types/struct.Der.html Attempts to get a reference to the underlying array if the requested size N matches the slice length. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); assert!(array_ref.is_some()); let array_ref_wrong_size: Option<&[i32; 2]> = slice.as_array(); assert!(array_ref_wrong_size.is_none()); ``` -------------------------------- ### Box::from_raw Example - Manual Allocation Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/type.ConnectCallback.html Shows how to manually create a `Box` from scratch using the global allocator and a raw pointer. This requires careful handling of memory allocation and deallocation. ```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); } ``` -------------------------------- ### ConfigBuilder Usage Examples Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/struct.ConfigBuilder.html Illustrates how to use ConfigBuilder to create ClientConfig and ServerConfig objects with different certificate configurations. ```APIDOC ## ClientConfig Certificate Configuration ### With Root Certificates and No Client Auth This example shows how to configure a client to verify the server's certificate using provided root certificates and to not send its own client certificate. ```rust use rustls::{ClientConfig, OwnedTrustAnchor, Certificate}; use std::sync::Arc; // Assume root_certs is a Vec let root_certs: Vec = vec![]; // Placeholder let client_config = ClientConfig::builder() .with_root_certificates(rustls::OwnedTrustAnchor::from_subject_alts_for_testing(root_certs)) .with_no_client_auth(); ``` ### With Custom Certificate Verifier and Client Certificate This example demonstrates configuring a client with a custom certificate verifier and sending a specific client certificate. ```rust use rustls::{ClientConfig, Certificate, PrivateKey, OwnedTrustAnchor}; use rustls::client::danger::HandshakeSignatureValid; use std::sync::Arc; // Placeholder for custom verifier and certificate/key struct MyVerifier; impl rustls::client::danger::ServerCertVerifier for MyVerifier { fn verify_server_cert( &self, _end_entity: &rustls::Certificate, _intermediates: &[rustls::Certificate], _server_name: &rustls::ServerName, _scts: &mut dyn Iterator, _ocsp_response: &[u8], _now: std::time::SystemTime, ) -> Result { Ok(rustls::client::danger::ServerCertAdvice::Ok) } fn offer_single_client_auth( &self, _alg_hint: Option<&rustls::SignatureAlgorithm>, ) -> bool { true } fn verify_tls13_signature( &self, _message: &[u8], _cert: &rustls::Certificate, _signature: &[u8], ) -> Result { Ok(HandshakeSignatureValid::Ok) } fn verify_tls12_signature( &self, _message: &[u8], _cert: &rustls::Certificate, _signature: &[u8], ) -> Result { Ok(rustls::client::danger::HandshakeSignatureValid::Ok) } } let certs: Vec = vec![]; // Placeholder let private_key: PrivateKey = PrivateKey(vec![]); // Placeholder let client_config = ClientConfig::builder() .with_dangerous_configuration(rustls::client::ClientConfigFinalizer::new(Arc::new(MyVerifier {}))) .with_client_auth_cert(certs, private_key); ``` ## ServerConfig Certificate Configuration ### With No Client Auth and Single Certificate This example configures a server to not require client authentication and to present a single specific certificate to clients. ```rust use rustls::{ServerConfig, Certificate, PrivateKey}; // Assume certs and private_key are correctly initialized let certs: Vec = vec![]; // Placeholder let private_key: PrivateKey = PrivateKey(vec![]); // Placeholder let server_config = ServerConfig::builder() .with_no_client_auth() .with_single_cert(certs, private_key) .expect("bad certificate/key"); ``` ### With Single Certificate and OCSP Stapling This example configures a server to present a specific certificate along with stapled OCSP information. ```rust use rustls::{ServerConfig, Certificate, PrivateKey}; // Assume certs and private_key are correctly initialized let certs: Vec = vec![]; // Placeholder let private_key: PrivateKey = PrivateKey(vec![]); // Placeholder let server_config = ServerConfig::builder() .with_no_client_auth() .with_single_cert_with_ocsp(certs, private_key) .expect("bad certificate/key"); ``` ## Protocol Version Configuration ### ServerConfig with Specific Protocol Versions This example shows how to build a `ServerConfig` that only supports TLS 1.3. ```rust use rustls::ServerConfig; let server_config = ServerConfig::builder_with_protocol_versions(&[&rustls::version::TLS13]); ``` ``` -------------------------------- ### Examples for len() method Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/protocol/frame/struct.Utf8Bytes.html Demonstrates the usage of the `len()` method to get the byte length of a string, including handling of multi-byte characters. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Server::with_config Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/struct.Server.html Creates a new server instance with a custom configuration, allowing for callbacks and context. ```APIDOC ## Server::with_config ### Description Create a new server with a custom configuration. Callbacks with context can be registered with the server to be notified when the server changes states. See `ServerConfig` for more details. ### Method `pub fn with_config(protocol_id: u64, private_key: [u8; 32], cfg: ServerConfig) -> Result, Error>` ### Parameters * `protocol_id` (u64) - The protocol identifier for the server. * `private_key` ([u8; 32]) - The private key used for cryptographic operations. * `cfg` (ServerConfig) - The custom server configuration, including callbacks and context. ### Returns * `Result, Error>` - A `Result` containing the new `Server` instance or an `Error` if creation failed. ### Example ```rust let private_key = generate_key(); let protocol_id = 0x123456789ABCDEF0; let cfg = ServerConfig::with_context(42).on_connect(|idx, _, _user_data, ctx| { assert_eq!(ctx, &42); }); let server = Server::with_config(protocol_id, private_key, cfg).unwrap(); ``` ``` -------------------------------- ### Getting on_despawn Component Hook Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Retrieves the `on_despawn` hook for the `Starting` component if defined. This hook is executed when the entity associated with the component is despawned. ```rust fn on_despawn() -> Option fn(DeferredWorld<'w>, HookContext)>; ``` -------------------------------- ### Getting on_replace Component Hook Source: https://docs.rs/lightyear/0.26.4/lightyear/connection/prelude/server/struct.Starting.html Retrieves the `on_replace` hook for the `Starting` component if defined. This hook is executed when the component's value is replaced. ```rust fn on_replace() -> Option fn(DeferredWorld<'w>, HookContext)>; ``` -------------------------------- ### WebSocketServer::open Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/server/struct.WebSocketServer.html Creates an EntityCommand to set up a WebSocket server and begin listening for client connections. This method is available when the `server` and `websocket` features are enabled and the target is not `wasm`. ```APIDOC ## WebSocketServer::open ### Description Creates an `EntityCommand` to set up a server and have it start listening for connections. ### Method Associated Function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * `config`: Accepts any type that can be converted into `ServerConfig`. ### Examples ```rust use { aeronet_websocket::server::{Identity, ServerConfig, WebSocketServer}, bevy_ecs::prelude::*, }; // set up a self-signed certificate to identify this server let identity = Identity::self_signed(["localhost", "127.0.0.1", "::1"]).unwrap(); let config = ServerConfig::builder() .with_bind_default(12345) // server port .with_identity(identity); // using `Commands` commands.spawn_empty().queue(WebSocketServer::open(config)); // using mutable `World` access let server = world.spawn_empty().id(); WebSocketServer::open(config).apply(world.entity_mut(server)); ``` ### Response Returns an `EntityCommand` that can be applied to a Bevy ECS world to set up the server. ``` -------------------------------- ### HashMap With Capacity and Hasher Example Source: https://docs.rs/lightyear/0.26.4/lightyear/utils/collections/type.HashMap.html Demonstrates creating a HashMap with a specified initial capacity and a custom hasher using `with_capacity_and_hasher`. This pre-allocates memory for efficiency. ```rust use hashbrown::HashMap; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); ``` -------------------------------- ### Getting the Body of a Request Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/handshake/client/type.Request.html Illustrates how to access the body of a `Request` using the `body()` method. This example checks if the body of a `String` request is empty. ```rust let request: Request = Request::default(); assert!(request.body().is_empty()); ``` -------------------------------- ### Get Current Chunk from Buf Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/struct.Bytes.html Returns a slice representing the contiguous bytes starting from the current position. The slice length is between 0 and the remaining bytes. ```rust let mut buf = Bytes::from_static(b"hello"); assert_eq!(buf.chunk(), b"hello"); buf.advance(2); assert_eq!(buf.chunk(), b"llo"); ``` -------------------------------- ### InputPlugin::ready Method Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.InputPlugin.html Checks if the plugin has finished its setup. Useful for plugins requiring asynchronous operations before completion. ```rust fn ready(&self, _app: &App) -> bool ``` -------------------------------- ### Create OPTIONS Request Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/handshake/client/type.Request.html Demonstrates creating an OPTIONS request for a given URI using the `options()` constructor. ```rust let request = Request::options("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Example: Spawning with AccumulateBy Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/input/bei/struct.AccumulateBy.html Demonstrates how to use AccumulateBy to sum movement input when an Accelerate action is pressed. This setup is typically used during entity spawning. ```Rust use bevy::{ecs::spawn::SpawnWith, prelude::*}; use bevy_enhanced_input::prelude::*; Actions::::spawn(SpawnWith(|context: &mut ActionSpawner<_>| { let accelerate = context .spawn(( Action::::new(), bindings![KeyCode::ShiftLeft, KeyCode::ShiftRight], )) .id(); // Sums movement when `Accelerate` is pressed. context.spawn(( Action::::new(), AccumulateBy::new(accelerate), Bindings::spawn(Cardinal::wasd_keys().with(DeadZone::default())), )); })); #[derive(Component)] struct TestContext; #[derive(InputAction)] #[action_output(bool)] struct Accelerate; #[derive(InputAction)] #[action_output(f32)] struct Movement; ``` -------------------------------- ### Get Canonical Label for Unit Source: https://docs.rs/lightyear/0.26.4/lightyear/metrics/metrics/enum.Unit.html Retrieves the canonical string label for a Unit. For example, 's' for Seconds or 'ns' for Nanoseconds. Some units may not have a meaningful display label. ```rust pub fn as_canonical_label(&self) -> &'static str ``` -------------------------------- ### Suite keys() Method Source: https://docs.rs/lightyear/0.26.4/lightyear/websocket/prelude/rustls/quic/struct.Suite.html Produces a set of initial QUIC keys using the Suite's ciphersuite and algorithm, given the client's destination connection ID, side, and protocol version. ```rust pub fn keys( &self, client_dst_connection_id: &[u8], side: Side, version: Version, ) -> Keys ``` -------------------------------- ### Finding Pattern Matches with match_indices Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/steamworks/struct.LobbyKey.html Use `match_indices` to find all non-overlapping occurrences of a pattern within a string slice and get their starting indices. This method is suitable for forward iteration. ```Rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); ``` ```Rust let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); ``` ```Rust let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### WebSocketServerIo::new Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/server/struct.WebSocketServerIo.html Creates a new WebSocketServerIo instance with default settings. ```APIDOC ## WebSocketServerIo::new ### Description Creates a new WebSocketServerIo instance with default settings. ### Method Associated function (constructor) ### Parameters None ### Response - **WebSocketServerIo**: A new instance of WebSocketServerIo. ``` -------------------------------- ### Get Launch Query Parameter Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/steamworks/struct.Apps.html Retrieves a specific launch parameter value when the game is run via a Steam URL. Reserved parameter names starting with '@' or '_' are handled specially. ```rust pub fn launch_query_param(&self, key: &str) -> String ``` -------------------------------- ### Start ClientConfig Builder Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/client/struct.ClientConfig.html Initiates the creation of a ClientConfig using the builder pattern. This method returns a ClientConfigBuilder. ```rust pub const fn builder() -> ClientConfigBuilder ``` -------------------------------- ### NetcodeServer::new Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/prelude/server/struct.NetcodeServer.html Constructs a new NetcodeServer instance with the provided configuration. ```APIDOC ## NetcodeServer::new ### Description Constructs a new `NetcodeServer` with the given `NetcodeConfig`. ### Signature ```rust pub fn new(config: NetcodeConfig) -> NetcodeServer ``` ### Parameters * `config` (`NetcodeConfig`): The configuration for the NetcodeServer. ``` -------------------------------- ### Buf Trait: Get Current Chunk Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/buffer/struct.ReadBuffer.html Returns a slice of the available data starting from the current position. Note that this slice might not represent the entire remaining data if the buffer's internal representation is non-continuous. ```rust fn chunk(&self) -> &[u8] ``` -------------------------------- ### Plugin::ready Implementation Source: https://docs.rs/lightyear/0.26.4/lightyear/input/client/struct.ClientInputPlugin.html Checks if the plugin has finished its setup. Useful for plugins with asynchronous initialization. ```rust fn ready(&self, _app: &App) -> bool ``` -------------------------------- ### Get Slice Pointer Range Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.Bindings.html Returns two raw pointers representing the start and end of the slice. The end pointer is one past the last element. Useful for C interop or checking pointer containment within the slice. ```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)); ``` -------------------------------- ### AtomicU64 fetch_and Example Source: https://docs.rs/lightyear/0.26.4/lightyear/metrics/metrics/atomics/struct.AtomicU64.html Demonstrates performing a bitwise AND operation on an AtomicU64 and retrieving the previous value. Ensure `target_has_atomic=64` is enabled. ```rust use std::sync::atomic::{AtomicU64, Ordering}; let foo = AtomicU64::new(0b101101); assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b100001); ``` -------------------------------- ### Get Element Offset in a Slice Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/pki_types/struct.EchConfigListBytes.html Use `element_offset` to find the index of an element based on its memory address. This method uses pointer arithmetic and does not compare elements. It returns `None` if the element reference is not aligned with the start of an element within the slice. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust 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 ``` -------------------------------- ### Get Element Index by Reference Source: https://docs.rs/lightyear/0.26.4/lightyear/input/bei/prelude/struct.Bindings.html Use `element_offset` to find the `usize` index of a given element reference within a slice. This method relies on pointer arithmetic and does not compare element values. It returns `None` if the reference is not aligned with an element's start. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### KeyLogFile::new() Constructor Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/struct.KeyLogFile.html Creates a new KeyLogFile instance. This function inspects the SSLKEYLOGFILE environment variable and opens the specified file for logging. ```rust pub fn new() -> KeyLogFile ``` -------------------------------- ### Iterating over exact chunks from the end of a slice Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/struct.Bytes.html Use `rchunks_exact` to get an iterator over non-overlapping chunks of a specified size, starting from the end of the slice. This iterator guarantees each chunk has exactly `chunk_size` elements, omitting any trailing elements that don't form a full chunk. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); // The remainder can be accessed via iter.remainder() ``` -------------------------------- ### Rust binary_search Example Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/pki_types/struct.Der.html Shows how to perform a binary search on a sorted slice to find an element or determine its insertion point. Includes examples for found, not found, and range-based searches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let low = s.partition_point(|x| x < &1); assert_eq!(low, 1); let high = s.partition_point(|x| x <= &1); assert_eq!(high, 5); let r = s.binary_search(&1); assert!((low..high).contains(&r.unwrap())); assert!(s[..low].iter().all(|&x| x < 1)); assert!(s[low..high].iter().all(|&x| x == 1)); assert!(s[high..].iter().all(|&x| x > 1)); // For something not found, the "range" of equal items is empty assert_eq!(s.partition_point(|x| x < &11), 9); assert_eq!(s.partition_point(|x| x <= &11), 9); assert_eq!(s.binary_search(&11), Err(9)); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert` // to shift less elements. s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### Example Usage of Chord for Composite Actions Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/input/bei/struct.Chord.html Demonstrates spawning a Player entity with a composite action ('Heal') that requires a 'Modifier' action to be active, alongside a default 'Attack' action. This setup uses Bevy's ECS and Bevy Enhanced Input's action system. ```rust use bevy::prelude::*; use bevy_enhanced_input::prelude::*; world.spawn(( Player, Actions::::spawn(SpawnWith(|context: &mut ActionSpawner<_>| { let modifier = context .spawn((Action::::new(), bindings![GamepadButton::LeftTrigger])) .id(); // Use `Heal` if `Modifier` is active. context.spawn(( Action::::new(), Chord::single(modifier), bindings![GamepadButton::West], )); // Otherwise use `Attack`. context.spawn((Action::::new(), bindings![GamepadButton::West])); })), )); #[derive(Component)] struct Player; #[derive(InputAction)] #[action_output(bool)] struct Attack; #[derive(InputAction)] #[action_output(bool)] struct Modifier; #[derive(InputAction)] #[action_output(bool)] struct Heal; ``` -------------------------------- ### Client Certificate Verification and Authentication Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/struct.ConfigBuilder.html Illustrates the configuration of a ClientConfig for certificate handling. It shows how to set up root certificates for verification and how to manage client authentication, including disabling it or providing a certificate. ```rust ClientConfig::builder() .with_root_certificates(root_certs) .with_no_client_auth(); ``` -------------------------------- ### Get Mutable Reference to First Element Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/rustls/crypto/cipher/struct.BorrowedPayload.html Returns a mutable reference to the first element of the slice, or `None` if it is empty. Example: `let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); let y: &mut [i32] = &mut []; assert_eq!(None, y.first_mut());` ```rust pub fn first_mut(&mut self) -> Option<&mut T> ``` -------------------------------- ### Client::with_config Source: https://docs.rs/lightyear/0.26.4/lightyear/netcode/client/struct.Client.html Creates a new client instance with a custom configuration, allowing for state change callbacks. ```APIDOC ## Client::with_config ### Description Creates a new client with a custom configuration. Callbacks with context can be registered with the client to be notified when the client changes states. ### Signature `pub fn with_config(token_bytes: &[u8], cfg: ClientConfig) -> Result, Error>` ### Parameters * `token_bytes` (`&[u8]`) - A byte slice representing the connection token. * `cfg` (`ClientConfig`) - The custom client configuration, including callbacks. ### Returns * `Result, Error>` - Ok containing the new Client on success, or an Error on failure. ### Example ```rust struct MyContext {} let cfg = ClientConfig::with_context(MyContext {}).on_state_change(|from, to, _ctx| { assert_eq!(from, ClientState::Disconnected); assert_eq!(to, ClientState::SendingConnectionRequest); }); let mut client = NetcodeClient::with_config(&token_bytes, cfg).unwrap(); ``` ``` -------------------------------- ### init Source: https://docs.rs/lightyear/0.26.4/lightyear/link/struct.LinkStats.html Initializes a with the given initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize Initializes a with the given initializer. ``` -------------------------------- ### Set the path and query for a Uri Builder Source: https://docs.rs/lightyear/0.26.4/lightyear/prelude/tokio_tungstenite/tungstenite/http/uri/struct.Builder.html Demonstrates setting the path and query component of a `Uri` using the `path_and_query` method on the `Builder`. ```rust let uri = uri::Builder::new() .path_and_query("/hello?foo=bar") .build() .unwrap(); ``` -------------------------------- ### Install RecoverableRecorder Globally Source: https://docs.rs/lightyear/0.26.4/lightyear/metrics/metrics_util/struct.RecoverableRecorder.html Installs the wrapped recorder globally, returning a handle for recovery. A weakly-referenced version is installed, and the original recorder is held by the RecoverableRecorder. Errors occur if a recorder is already installed. ```rust pub fn install(self) -> Result, SetRecorderError> ``` -------------------------------- ### Install DebuggingRecorder as Global Recorder Source: https://docs.rs/lightyear/0.26.4/lightyear/metrics/metrics_util/debugging/struct.DebuggingRecorder.html Installs the DebuggingRecorder as the global metrics recorder. This operation can fail if another recorder is already installed. ```rust pub fn install(self) -> Result<(), SetRecorderError> ```