### Rust Slice split_at Example Source: https://docs.rs/renet/latest/renet/struct.Bytes Demonstrates `split_at` for dividing a slice into two parts at a specified index. The function returns two slices: one from the start up to the index, and another from the index to the end. It panics if the index is out of bounds. ```rust let v = ['a', 'b', 'c']; { let (left, right) = v.split_at(0); assert_eq!(left, []); assert_eq!(right, ['a', 'b', 'c']); } { let (left, right) = v.split_at(2); assert_eq!(left, ['a', 'b']); assert_eq!(right, ['c']); } { let (left, right) = v.split_at(3); assert_eq!(left, ['a', 'b', 'c']); assert_eq!(right, []); } ``` -------------------------------- ### Bytes Slicing and Splitting Example Source: https://docs.rs/renet/latest/renet/struct.Bytes Demonstrates how to use the `slice` and `split_to` methods on a `Bytes` object to create new views into the underlying memory without copying. ```rust use bytes::Bytes; let mut mem = Bytes::from("Hello world"); let a = mem.slice(0..5); assert_eq!(a, "Hello"); let b = mem.split_to(6); assert_eq!(mem, "world"); assert_eq!(b, "Hello "); ``` -------------------------------- ### DefaultChannel Enum Source: https://docs.rs/renet/latest/renet/enum.DefaultChannel The DefaultChannel enum represents the standard channel configurations available in Renet. It simplifies the setup of network channels by providing predefined options. ```APIDOC ## Enum DefaultChannel ### Description Utility enumerator when using the default channels configuration. The default configuration has 3 channels: unreliable, reliable ordered, and reliable unordered. ### Variants * **Unreliable**: Represents an unreliable channel. * **ReliableOrdered**: Represents a reliable and ordered channel. * **ReliableUnordered**: Represents a reliable but unordered channel. ### Methods #### `config() -> Vec` Returns the `ChannelConfig` for each variant of `DefaultChannel`. ### Implementations * **`From for u8`**: Converts a `DefaultChannel` variant into its corresponding `u8` representation. * **`Freeze`**, **`RefUnwindSafe`**, **`Send`**, **`Sync`**, **`Unpin`**, **`UnwindSafe`**: Auto implemented traits. * **`Any`**: Provides type information. * **`Borrow`**, **`BorrowMut`**: Allows borrowing the enum. * **`From for T`**, **`Into for T`**, **`TryFrom for T`**, **`TryInto for T`**: General conversion traits. ``` -------------------------------- ### Get Packet Loss for a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns the packet loss percentage for a given client. If the client is not found, it returns `0.0`. ```rust pub fn packet_loss(&self, client_id: ClientId) -> f64> ``` -------------------------------- ### Rust Slice rchunks_exact Example Source: https://docs.rs/renet/latest/renet/struct.Bytes Demonstrates the use of `rchunks_exact` to create non-overlapping exact chunks from the end of a slice. It shows how to retrieve chunks and the remaining elements. ```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()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### Try Get Single Byte Integers Source: https://docs.rs/renet/latest/renet/struct.Bytes Safely attempts to read single-byte unsigned and signed integers. ```APIDOC ## GET /data/try_get_byte_int ### Description Safely attempts to read a single-byte integer (unsigned or signed) from the data source. ### Method GET ### Endpoint /data/try_get_byte_int ### Parameters #### Query Parameters - **signed** (boolean) - Required - True to read a signed integer, false for unsigned. ### Response #### Success Response (200) - **value** (number) - The integer read from the source. #### Error Response (400) - **error** (string) - Description of the error (e.g., 'Not enough data'). #### Response Example ```json { "value": 100 } ``` ``` -------------------------------- ### Get Network Information for a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Retrieves comprehensive network information for a given client, including RTT, packet loss, and bandwidth usage. Returns a `Result` with `NetworkInfo` on success or `ClientNotFound` error. ```rust pub fn network_info( &self, client_id: ClientId, ) -> Result> ``` -------------------------------- ### Array Conversion: as_array Source: https://docs.rs/renet/latest/renet/struct.Bytes Attempts to get a reference to the underlying array if its length matches the specified size N. This is an experimental nightly-only API. ```APIDOC ## GET /slice/as_array/{N} ### Description Gets a reference to the underlying array. If `N` is not exactly equal to the length of the slice, then this method returns `None`. This is a nightly-only experimental API. ### Method GET ### Endpoint `/slice/as_array/{N}` ### Parameters #### Path Parameters - **N** (usize) - Required - The expected length of the underlying array. ### Request Example ```json { "slice_data": [10, 20, 30] } ``` ### Response #### Success Response (200) - **array_reference** (Option<&[T; N]>) - A reference to the underlying array if its length matches N, otherwise None. #### Response Example ```json { "array_reference": [10, 20, 30] } ``` ``` -------------------------------- ### Get Available Channel Memory for a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns the amount of available memory in bytes for a specific channel associated with a client. Returns 0 if the client is not found. ```rust pub fn channel_available_memory>( &self, client_id: ClientId, channel_id: I, ) -> usize> ``` -------------------------------- ### Get Bytes Received Per Second for a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns the rate of bytes received per second from a specific client. If the client is not found, it returns `0.0`. ```rust pub fn bytes_received_per_sec(&self, client_id: ClientId) -> f64> ``` -------------------------------- ### Rust Slice chunk_by Example Source: https://docs.rs/renet/latest/renet/struct.Bytes Illustrates `chunk_by` to partition a slice into sub-slices based on a predicate. The predicate determines when a new chunk begins by comparing adjacent elements. It can be used to group equal or sorted elements. ```rust let slice = &[1, 1, 1, 3, 3, 2, 2, 2]; let mut iter = slice.chunk_by(|a, b| a == b); assert_eq!(iter.next(), Some(&[1, 1, 1][..])); assert_eq!(iter.next(), Some(&[3, 3][..])); assert_eq!(iter.next(), Some(&[2, 2, 2][..])); assert_eq!(iter.next(), None); ``` ```rust let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4]; let mut iter = slice.chunk_by(|a, b| a <= b); assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3][..])); assert_eq!(iter.next(), Some(&[2, 3, 4][..])); assert_eq!(iter.next(), None); ``` -------------------------------- ### Rust Slice split_at_checked Example Source: https://docs.rs/renet/latest/renet/struct.Bytes Demonstrates `split_at_checked` for safely splitting a slice. It returns an `Option` containing the two resulting slices if the index is valid, or `None` if the index is out of bounds, preventing panics. ```rust let v = [1, -2, 3, -4, 5, -6]; { let (left, right) = v.split_at_checked(0).unwrap(); assert_eq!(left, []); assert_eq!(right, [1, -2, 3, -4, 5, -6]); } { let (left, right) = v.split_at_checked(2).unwrap(); assert_eq!(left, [1, -2]); assert_eq!(right, [3, -4, 5, -6]); } { let (left, right) = v.split_at_checked(6).unwrap(); assert_eq!(left, [1, -2, 3, -4, 5, -6]); assert_eq!(right, []); } assert_eq!(None, v.split_at_checked(7)); ``` -------------------------------- ### Get Packets to Send to a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Retrieves a list of raw byte packets that are ready to be sent to a specific client. This method is intended for the transport layer to serialize and send data. Returns a `Result` with a vector of packets or a `ClientNotFound` error. ```rust pub fn get_packets_to_send( &mut self, client_id: ClientId, ) -> Result>, ClientNotFound>> ``` -------------------------------- ### Get Server Events from RenetServer Source: https://docs.rs/renet/latest/renet/struct.RenetServer Retrieves the next available server event, such as a client connecting or disconnecting. Returns `None` if no events are pending. This method is crucial for processing real-time server state changes. ```rust pub fn get_event(&mut self) -> Option ``` -------------------------------- ### Initialize RenetServer Source: https://docs.rs/renet/latest/renet/struct.RenetServer Creates a new instance of RenetServer with the specified connection configuration. This is the entry point for setting up the server. ```rust pub fn new(connection_config: ConnectionConfig) -> Self> ``` -------------------------------- ### Get Element Offset in Slice (Experimental) Source: https://docs.rs/renet/latest/renet/struct.Bytes Returns the byte index of an element reference within a slice. This is an experimental API that relies on pointer arithmetic and does not compare element values. It returns `None` if the element reference is not aligned to the start of an element in the slice. Panics if the element type `T` has zero size. ```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 ``` -------------------------------- ### RenetServer - Initialization and Basic Operations Source: https://docs.rs/renet/latest/renet/struct.RenetServer Covers the initialization of RenetServer and basic operations like adding/removing connections, checking connection status, and updating the server. ```APIDOC ## RenetServer - Initialization and Basic Operations ### Description This section details the initialization of the RenetServer and fundamental operations for managing client connections and server state. ### Methods #### `new(connection_config: ConnectionConfig) -> Self` - **Description**: Creates a new instance of `RenetServer` with the specified connection configuration. - **Method**: `new` - **Endpoint**: N/A (Constructor) #### `add_connection(&mut self, client_id: ClientId)` - **Description**: Adds a new client connection to the server. If a connection for the given `client_id` already exists, this method does nothing. This method is intended for internal use by the transport layer. - **Method**: `add_connection` - **Endpoint**: N/A #### `remove_connection(&mut self, client_id: ClientId)` - **Description**: Removes a client connection from the server and emits a `ClientDisconnected` event. If the client does not exist, this method does nothing. This method is intended for internal use by the transport layer. - **Method**: `remove_connection` - **Endpoint**: N/A #### `has_connections(&self) -> bool` - **Description**: Returns `true` if the server currently has any active client connections, `false` otherwise. - **Method**: `has_connections` - **Endpoint**: N/A #### `connected_clients(&self) -> usize` - **Description**: Returns the number of currently connected clients. - **Method**: `connected_clients` - **Endpoint**: N/A #### `is_connected(&self, client_id: ClientId) -> bool` - **Description**: Checks if a client with the given `client_id` is currently connected. - **Method**: `is_connected` - **Endpoint**: N/A #### `update(&mut self, duration: Duration)` - **Description**: Advances the server's internal state by the specified `duration`. This method should be called regularly, typically once per game tick or frame. - **Method**: `update` - **Endpoint**: N/A ``` -------------------------------- ### Split Slice into Fixed-Size Chunks from Start (Rust) Source: https://docs.rs/renet/latest/renet/struct.Bytes Splits a slice into a slice of `N`-element arrays starting from the beginning and a remainder slice. Panics if `N` is zero. The remainder's length is the slice length modulo `N`. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks::<2>(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); let slice = ['R', 'u', 's', 't']; let (chunks, []) = slice.as_chunks::<2>() else { panic!("slice didn't have even length") }; assert_eq!(chunks, &[['R', 'u'], ['s', 't']]); ``` -------------------------------- ### RenetClient Initialization and Status Source: https://docs.rs/renet/latest/renet/struct.RenetClient Demonstrates how to initialize a RenetClient and check its connection status. Requires a ConnectionConfig. Returns boolean values for connection states. ```rust pub struct RenetClient { /* private fields */ } // Initialization (example, actual `new` might differ) // pub fn new(config: ConnectionConfig) -> Self // Status checks pub fn is_connected(&self) -> bool pub fn is_connecting(&self) -> bool pub fn is_disconnected(&self) -> bool ``` -------------------------------- ### Create Local RenetClient for Testing Source: https://docs.rs/renet/latest/renet/struct.RenetServer Creates a new local RenetClient instance. This function is intended for testing scenarios. Use `Self::process_local_client` to manage the connection updates for the created client. ```rust pub fn new_local_client(&mut self, client_id: ClientId) -> RenetClient ``` -------------------------------- ### Iterator: iter Source: https://docs.rs/renet/latest/renet/struct.Bytes Returns an iterator that yields references to all items in the slice from start to end. ```APIDOC ## GET /slice/iter ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method GET ### Endpoint `/slice/iter` ### Parameters None ### Request Example ```json { "slice_data": [1, 2, 4] } ``` ### Response #### Success Response (200) - **iterator** (Iter<'_, T>) - An iterator yielding references to slice elements. #### Response Example ```json { "iterator_items": [1, 2, 4] } ``` ``` -------------------------------- ### Local RenetClient Management Source: https://docs.rs/renet/latest/renet/struct.RenetServer Manage local RenetClient instances for testing. This includes creating a new client, processing its packets, and disconnecting it. ```APIDOC ## POST /client/local/new ### Description Creates a new local RenetClient instance for testing purposes. ### Method POST ### Endpoint `/client/local/new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **client_id** (ClientId) - Required - The unique identifier for the client. ### Request Example ```json { "client_id": "some_client_id" } ``` ### Response #### Success Response (200) - **RenetClient** (RenetClient) - The newly created local RenetClient instance. #### Response Example ```json { "client": "" } ``` ## POST /client/local/process ### Description Processes incoming and outgoing packets for a local RenetClient. This method should be used to update the connection state and handle network traffic for clients created with `new_local_client`. ### Method POST ### Endpoint `/client/local/process` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **client_id** (ClientId) - Required - The unique identifier for the client. - **client** (RenetClient) - Required - The RenetClient instance to process. ### Request Example ```json { "client_id": "some_client_id", "client": "" } ``` ### Response #### Success Response (200) - **Result** (Result<(), ClientNotFound>) - Indicates success or a `ClientNotFound` error if the client ID is invalid. #### Response Example ```json { "status": "success" } ``` ## DELETE /client/local/{client_id} ### Description Disconnects a local RenetClient instance that was previously created using `new_local_client`. ### Method DELETE ### Endpoint `/client/local/{client_id}` ### Parameters #### Path Parameters - **client_id** (ClientId) - Required - The unique identifier for the client to disconnect. #### Query Parameters None #### Request Body None ### Request Example ```http DELETE /client/local/some_client_id HTTP/1.1 ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful disconnection. #### Response Example ```json { "status": "disconnected" } ``` ``` -------------------------------- ### Get Current Number of Connected Clients Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns the total count of clients currently connected to the server. ```rust pub fn connected_clients(&self) -> usize> ``` -------------------------------- ### rsplit Source: https://docs.rs/renet/latest/renet/struct.Bytes Splits a slice into subslices starting from the end and working backwards. The matched elements are not included in the subslices. ```APIDOC ## rsplit ### Description Returns an iterator over subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices. ### Method `rsplit`(&self, pred: F) -> RSplit<'_, T, F> ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Iterator over subslices. #### Response Example ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` ``` -------------------------------- ### Bytes Slicing and Splitting Source: https://docs.rs/renet/latest/renet/struct.Bytes Demonstrates how to slice and split `Bytes` objects to create views into the underlying memory. ```APIDOC ## Bytes Slicing and Splitting ### Description `Bytes` objects can be efficiently sliced and split to create new `Bytes` instances that refer to subsets of the original memory without copying. ### Method - `slice(range)`: Creates a new `Bytes` object that refers to a specified range within the original `Bytes`. - `split_to(at)`: Splits the `Bytes` object into two at a given index. The original `Bytes` object will contain data up to the index, and the returned `Bytes` object will contain the data from the index onwards. ### Endpoint N/A (Methods on Bytes instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use bytes::Bytes; let mut mem = Bytes::from("Hello world"); // Slicing let a = mem.slice(0..5); assert_eq!(a, "Hello"); // Splitting let b = mem.split_to(6); assert_eq!(mem, "world"); // Original 'mem' is modified assert_eq!(b, "Hello "); ``` ### Response #### Success Response (N/A) - **Bytes** (Bytes) - The new `Bytes` object resulting from slicing or splitting. #### Response Example ```rust // Example showing the results of slicing and splitting let mut mem = Bytes::from("Hello world"); let a = mem.slice(0..5); let b = mem.split_to(6); // a = "Hello", b = "Hello ", mem = "world" ``` ``` -------------------------------- ### RenetServer - Message Handling Source: https://docs.rs/renet/latest/renet/struct.RenetServer APIs for sending and receiving messages to/from clients over specified channels, including broadcast functionality. ```APIDOC ## RenetServer - Message Handling ### Description This section outlines the methods for sending and receiving messages between the server and clients, including broadcast capabilities and channel management. ### Methods #### `broadcast_message, B: Into>(&mut self, channel_id: I, message: B)` - **Description**: Sends a message to all connected clients over the specified channel. - **Method**: `broadcast_message` - **Endpoint**: N/A #### `broadcast_message_except, B: Into>(&mut self, except_id: ClientId, channel_id: I, message: B)` - **Description**: Sends a message to all connected clients except for the one specified by `except_id`, over the given channel. - **Method**: `broadcast_message_except` - **Endpoint**: N/A #### `channel_available_memory>(&self, client_id: ClientId, channel_id: I) -> usize` - **Description**: Returns the available memory in bytes for a specific channel for a given client. Returns `0` if the client is not found. - **Method**: `channel_available_memory` - **Endpoint**: N/A #### `can_send_message>(&self, client_id: ClientId, channel_id: I, size_bytes: usize) -> bool` - **Description**: Checks if a message of a given `size_bytes` can be sent over the specified channel for the given client. Returns `false` if the client is not found. - **Method**: `can_send_message` - **Endpoint**: N/A #### `send_message, B: Into>(&mut self, client_id: ClientId, channel_id: I, message: B)` - **Description**: Sends a message to a specific client over the specified channel. - **Method**: `send_message` - **Endpoint**: N/A #### `receive_message>(&mut self, client_id: ClientId, channel_id: I) -> Option` - **Description**: Attempts to receive a message from a specific client over the specified channel. Returns `Some(Bytes)` if a message is available, otherwise `None`. - **Method**: `receive_message` - **Endpoint**: N/A ``` -------------------------------- ### Try Get Multi-Byte Floats Source: https://docs.rs/renet/latest/renet/struct.Bytes Safely attempts to read 32-bit and 64-bit floating-point numbers with support for endianness. ```APIDOC ## GET /data/try_get_float ### Description Safely attempts to read a floating-point number (32-bit or 64-bit) from the data source with specified endianness. ### Method GET ### Endpoint /data/try_get_float ### Parameters #### Query Parameters - **bits** (integer) - Required - The number of bits for the float (32 or 64). - **endianness** (string) - Optional - The byte order (e.g., 'big', 'little', 'native'). Defaults to 'big'. ### Response #### Success Response (200) - **value** (number) - The floating-point number read from the source. #### Error Response (400) - **error** (string) - Description of the error (e.g., 'Not enough data'). #### Response Example ```json { "value": 2.71828 } ``` ``` -------------------------------- ### Try Get Multi-Byte Integers Source: https://docs.rs/renet/latest/renet/struct.Bytes Safely attempts to read multi-byte unsigned and signed integers with support for endianness. ```APIDOC ## GET /data/try_get_int ### Description Safely attempts to read a multi-byte integer (unsigned or signed) from the data source with specified endianness. ### Method GET ### Endpoint /data/try_get_int ### Parameters #### Query Parameters - **nbytes** (usize) - Required - The number of bytes for the integer. - **signed** (boolean) - Required - True to read a signed integer, false for unsigned. - **endianness** (string) - Optional - The byte order (e.g., 'big', 'little', 'native'). Defaults to 'big'. ### Response #### Success Response (200) - **value** (number) - The integer read from the source. #### Error Response (400) - **error** (string) - Description of the error (e.g., 'Not enough data'). #### Response Example ```json { "value": 65535 } ``` ``` -------------------------------- ### NetworkInfo Struct Source: https://docs.rs/renet/latest/renet/struct.NetworkInfo Provides details about the NetworkInfo struct, including its fields and their descriptions. ```APIDOC ## Struct NetworkInfo ### Description Describes the stats of a connection. ### Fields - **rtt** (f64) - Round-trip Time - **packet_loss** (f64) - Packet loss percentage - **bytes_sent_per_second** (f64) - Bytes sent per second - **bytes_received_per_second** (f64) - Bytes received per second ### Request Example ```json { "rtt": 0.123, "packet_loss": 0.01, "bytes_sent_per_second": 1024.5, "bytes_received_per_second": 2048.0 } ``` ### Response Example ```json { "rtt": 0.123, "packet_loss": 0.01, "bytes_sent_per_second": 1024.5, "bytes_received_per_second": 2048.0 } ``` ``` -------------------------------- ### Clone Implementation for ChannelConfig in Rust Source: https://docs.rs/renet/latest/renet/struct.ChannelConfig Demonstrates the implementation of the Clone trait for the ChannelConfig struct. This allows for the creation of duplicate ChannelConfig instances, which is useful for scenarios where configuration needs to be copied or shared. The `clone` method returns a new ChannelConfig, while `clone_from` performs in-place assignment. ```rust impl Clone for ChannelConfig { fn clone(&self) -> ChannelConfig; fn clone_from(&mut self, source: &Self); } ``` -------------------------------- ### Bytes Length Check Source: https://docs.rs/renet/latest/renet/struct.Bytes Shows how to get the number of bytes contained in a `Bytes` object using the `len()` method. This is a constant-time operation. ```rust use bytes::Bytes; let b = Bytes::from(&b"hello"[..]); assert_eq!(b.len(), 5); ``` -------------------------------- ### Buffer Adaptors and Conversions Source: https://docs.rs/renet/latest/renet/struct.Bytes Provides adaptors for limiting read bytes, chaining buffers, and implementing the `Read` trait. Also includes methods for cloning `Bytes` and converting between different byte representations and collections. ```APIDOC ## Buffer Adaptors and Conversions ### Description This section covers utility functions for adapting and converting byte buffers. ### Methods #### `take(self, limit: usize) -> Take` Creates an adaptor which will read at most `limit` bytes from `self`. #### `chain(self, next: U) -> Chain` Creates an adaptor which will chain this buffer with another. #### `reader(self) -> Reader` Creates an adaptor which implements the `Read` trait for `self`. ### Clone Implementation #### `clone(&self) -> Bytes` Returns a duplicate of the `Bytes` value. #### `clone_from(&mut self, source: &Self)` Performs copy-assignment from `source` to `self`. ### Conversion Implementations #### `From<&'static [u8]> for Bytes` Converts a static byte slice into `Bytes`. #### `From<&'static str> for Bytes` Converts a static string slice into `Bytes`. #### `From> for Bytes` Converts a boxed byte slice into `Bytes`. #### `From for Vec` Converts `Bytes` into a `Vec`. #### `From for Bytes` Converts `BytesMut` into `Bytes`. #### `From for Bytes` Converts a `String` into `Bytes`. ### Response #### Success Response (200) - `Take | Chain | Reader | Bytes | Vec` - The result of the operation. ``` -------------------------------- ### RenetClient Connection Management Source: https://docs.rs/renet/latest/renet/struct.RenetClient Functions for actively managing the client's connection state. Includes setting status, disconnecting, and handling disconnect reasons. Note that some methods are intended for internal transport layer use. ```rust // Returns the disconnect reason if the client is disconnected. pub fn disconnect_reason(&self) -> Option // Set the client connection status to connected. Does nothing if disconnected. pub fn set_connected(&mut self) // Set the client connection status to connecting. Does nothing if disconnected. pub fn set_connecting(&mut self) // Disconnect the client. Does nothing if already disconnected. pub fn disconnect(&mut self) // Disconnect the client due to a transport layer error. Does nothing if already disconnected. pub fn disconnect_due_to_transport(&mut self) ``` -------------------------------- ### Get List of Disconnected Client IDs Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns a `Vec` containing the IDs of all disconnected clients. This collects all disconnected client IDs into a vector. ```rust pub fn disconnections_id(&self) -> Vec ``` -------------------------------- ### Get List of Connected Client IDs Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns a `Vec` containing the IDs of all currently connected clients. This collects all client IDs into a vector. ```rust pub fn clients_id(&self) -> Vec ``` -------------------------------- ### Bytes Methods Source: https://docs.rs/renet/latest/renet/struct.Bytes This section details the methods available for the Bytes type, including ASCII case conversion and buffer manipulation. ```APIDOC ## Bytes Methods ### `to_ascii_lowercase()` **Description**: Returns a vector containing a copy of this slice where each byte is mapped to its ASCII lower case equivalent. ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged. **Method**: N/A (Method on Bytes type) **Endpoint**: N/A ### `make_ascii_lowercase()` **Description**: To lowercase the value in-place, use `make_ascii_lowercase`. **Method**: N/A (Method on Bytes type) **Endpoint**: N/A ``` -------------------------------- ### Bytes Manipulation and Utility Methods Source: https://docs.rs/renet/latest/renet/struct.Bytes This section covers core Bytes methods for checking uniqueness, copying, slicing, splitting, truncating, clearing, and attempting mutable conversion. ```APIDOC ## Bytes Methods ### `is_unique()` Returns `true` if this is the only reference to the data and `Into` would avoid cloning the underlying buffer. **Note:** Always returns `false` if the data is backed by a static slice or an owner. The result may be invalidated if another thread clones this value concurrently. #### Examples ```rust use bytes::Bytes; let a = Bytes::from(vec![1, 2, 3]); assert!(a.is_unique()); let b = a.clone(); assert!(!a.is_unique()); ``` ### `copy_from_slice(data: &[u8]) -> Bytes` Creates a `Bytes` instance from a slice by copying its contents. ### `slice(&self, range: impl RangeBounds) -> Bytes` Returns a new `Bytes` handle representing a slice of the original `Bytes` data. This operation increments the reference count and is O(1). #### Examples ```rust use bytes::Bytes; let a = Bytes::from(&b"hello world"[..]); let b = a.slice(2..5); assert_eq!(&b[..], b"llo"); ``` #### Panics Panics if `begin > end` or `end > self.len()`. ### `slice_ref(&self, subset: &[u8]) -> Bytes` Returns a new `Bytes` handle that is equivalent to the given `subset` slice. This is useful when you have a `&[u8]` that is known to be a sub-slice of the original `Bytes` buffer. This operation is O(1). #### Examples ```rust use bytes::Bytes; let bytes = Bytes::from(&b"012345678"[..]); let as_slice = bytes.as_ref(); let subset = &as_slice[2..6]; let subslice = bytes.slice_ref(&subset); assert_eq!(&subslice[..], b"2345"); ``` #### Panics Panics if the `subset` is not contained within the `Bytes` buffer. ### `split_off(&mut self, at: usize) -> Bytes` Splits the `Bytes` into two at the given index. `self` will contain elements `[0, at)`, and the returned `Bytes` will contain elements `[at, len)`. This is an O(1) operation. #### Examples ```rust use bytes::Bytes; let mut a = Bytes::from(&b"hello world"[..]); let b = a.split_off(5); assert_eq!(&a[..], b"hello"); assert_eq!(&b[..], b" world"); ``` #### Panics Panics if `at > len`. ### `split_to(&mut self, at: usize) -> Bytes` Splits the `Bytes` into two at the given index. `self` will contain elements `[at, len)`, and the returned `Bytes` will contain elements `[0, at)`. This is an O(1) operation. #### Examples ```rust use bytes::Bytes; let mut a = Bytes::from(&b"hello world"[..]); let b = a.split_to(5); assert_eq!(&a[..], b" world"); assert_eq!(&b[..], b"hello"); ``` #### Panics Panics if `at > len`. ### `truncate(&mut self, len: usize)` Shortens the buffer, keeping the first `len` bytes and dropping the rest. If `len` is greater than the buffer's current length, this has no effect. #### Examples ```rust use bytes::Bytes; let mut buf = Bytes::from(&b"hello world"[..]); buf.truncate(5); assert_eq!(buf, b"hello"[..]); ``` ### `clear(&mut self)` Clears the buffer, removing all data. #### Examples ```rust use bytes::Bytes; let mut buf = Bytes::from(&b"hello world"[..]); buf.clear(); assert!(buf.is_empty()); ``` ### `try_into_mut(self) -> Result` Attempts to convert `self` into `BytesMut`. Succeeds without copying if `self` is the unique owner of the underlying buffer. Fails if `self` is not unique or if the buffer was created via `from_owner` or `from_static`. #### Examples ```rust use bytes::{Bytes, BytesMut}; let bytes = Bytes::from(b"hello".to_vec()); assert_eq!(bytes.try_into_mut(), Ok(BytesMut::from(&b"hello"[..]))); ``` ``` -------------------------------- ### as_rchunks Source: https://docs.rs/renet/latest/renet/struct.Bytes Splits a slice into a remainder slice and a slice of `N`-element arrays, starting from the end of the slice. Useful for processing data from the end. ```APIDOC ## `as_rchunks` ### Description Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`. ### Method `as_rchunks()` ### Endpoint N/A (Method on slice) ### Parameters #### Path Parameters - **N** (usize) - Required - The size of each chunk array. #### Query Parameters None #### Request Body None ### Request Example ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks::<2>(); // remainder will be ['l'] // chunks will be [['o', 'r'], ['e', 'm']] ``` ### Response #### Success Response (200) - **remainder** (slice) - The remaining elements at the beginning of the slice. - **chunks** (array of arrays) - A slice containing arrays of size N, starting from the end. #### Response Example ```json { "remainder": [ "l" ], "chunks": [[ "o", "r" ], [ "e", "m" ]] } ``` ##### §Panics Panics if `N` is zero. ``` -------------------------------- ### RenetServer - Client Management and Information Source: https://docs.rs/renet/latest/renet/struct.RenetServer Methods for disconnecting clients, retrieving disconnection reasons, and accessing network statistics for individual clients. ```APIDOC ## RenetServer - Client Management and Information ### Description This section details functionalities for managing specific client connections, retrieving their status, and accessing detailed network information. ### Methods #### `disconnect(&mut self, client_id: ClientId)` - **Description**: Disconnects a specific client from the server. If the client does not exist, this method has no effect. - **Method**: `disconnect` - **Endpoint**: N/A #### `disconnect_all(&mut self)` - **Description**: Disconnects all currently connected clients from the server. - **Method**: `disconnect_all` - **Endpoint**: N/A #### `disconnect_reason(&self, client_id: ClientId) -> Option` - **Description**: Retrieves the reason for a client's disconnection, if the client is currently disconnected. Returns `Some(DisconnectReason)` if the client is disconnected, otherwise `None`. - **Method**: `disconnect_reason` - **Endpoint**: N/A #### `rtt(&self, client_id: ClientId) -> f64` - **Description**: Returns the Round-Trip Time (RTT) in seconds for a given client. Returns `0.0` if the client is not found. - **Method**: `rtt` - **Endpoint**: N/A #### `packet_loss(&self, client_id: ClientId) -> f64` - **Description**: Returns the packet loss percentage for a given client. Returns `0.0` if the client is not found. - **Method**: `packet_loss` - **Endpoint**: N/A #### `bytes_sent_per_sec(&self, client_id: ClientId) -> f64` - **Description**: Returns the average bytes sent per second for a given client. Returns `0.0` if the client is not found. - **Method**: `bytes_sent_per_sec` - **Endpoint**: N/A #### `bytes_received_per_sec(&self, client_id: ClientId) -> f64` - **Description**: Returns the average bytes received per second for a given client. Returns `0.0` if the client is not found. - **Method**: `bytes_received_per_sec` - **Endpoint**: N/A #### `network_info(&self, client_id: ClientId) -> Result` - **Description**: Retrieves comprehensive network information for a specific client. Returns a `Result` containing `NetworkInfo` on success or a `ClientNotFound` error if the client does not exist. - **Method**: `network_info` - **Endpoint**: N/A ``` -------------------------------- ### Slice Access: get Source: https://docs.rs/renet/latest/renet/struct.Bytes Safely retrieves a reference to an element or sub-slice using various index types. Returns None if the index is out of bounds. ```APIDOC ## GET /slice/get ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Method GET ### Endpoint `/slice/get` ### Parameters #### Query Parameters - **index** (usize or Range) - Required - The index or range to access. ### Request Example ```json { "slice_data": [10, 40, 30], "index": 1 } ``` ### Response #### Success Response (200) - **element_or_subslice** (Option<&T> or Option<&[T]>) - A reference to the element or subslice, or None if out of bounds. #### Response Example ```json { "element_or_subslice": 40 } ``` ``` -------------------------------- ### ClientNotFound Trait Implementations Source: https://docs.rs/renet/latest/renet/struct.ClientNotFound Details the implementations of standard Rust traits for the ClientNotFound struct, including Debug, Display, and Error. ```APIDOC ## Trait Implementations for ClientNotFound ### Debug Implementation Allows the `ClientNotFound` struct to be formatted using the `{:?}` format specifier. - **`fn fmt(&self, f: &mut Formatter<'_>) -> Result`**: Formats the value using the given formatter. ### Display Implementation Allows the `ClientNotFound` struct to be formatted using the `{}` format specifier and converted to a string using `to_string()`. - **`fn fmt(&self, fmt: &mut Formatter<'_>) -> Result`**: Formats the value using the given formatter. ### Error Implementation Provides methods for accessing the underlying error source and a description. - **`fn source(&self) -> Option<&(dyn Error + 'static)>`**: Returns the lower-level source of this error, if any. - **`fn description(&self) -> &str`**: Returns a string description of the error. (Deprecated, use Display impl or to_string()) - **`fn cause(&self) -> Option<&dyn Error>`**: Returns the underlying cause of the error. (Deprecated, replaced by Error::source) - **`fn provide<'a>(&'a self, request: &mut Request<'a>)`**: Provides type-based access to context intended for error reports. (Nightly-only experimental API) ``` -------------------------------- ### Debug and Display Trait Implementations for ClientNotFound (Rust) Source: https://docs.rs/renet/latest/renet/struct.ClientNotFound This snippet illustrates the implementations of the `Debug` and `Display` traits for the `ClientNotFound` struct. These implementations allow the struct to be formatted for debugging output and user-facing messages, respectively. The `fmt` method is used in both cases to define the formatting logic. ```rust impl Debug for ClientNotFound { fn fmt(&self, f: &mut Formatter<'_>) -> Result { // Implementation details for Debug formatting } } impl Display for ClientNotFound { fn fmt(&self, fmt: &mut Formatter<'_>) -> Result { // Implementation details for Display formatting } } ``` -------------------------------- ### Get Round-Trip Time (RTT) for a Client Source: https://docs.rs/renet/latest/renet/struct.RenetServer Returns the current round-trip time (RTT) in seconds for a given client. If the client is not found, it returns `0.0`. ```rust pub fn rtt(&self, client_id: ClientId) -> f64> ``` -------------------------------- ### trim_prefix Source: https://docs.rs/renet/latest/renet/struct.Bytes Removes a prefix from a slice. If the slice starts with the given prefix, a new slice without the prefix is returned. Otherwise, the original slice is returned. ```APIDOC ## trim_prefix ### Description Removes a prefix from a slice. If the slice starts with the given prefix, a new slice without the prefix is returned. Otherwise, the original slice is returned. ### Method `trim_prefix` (method on slices) ### Endpoint N/A (This is a method on Rust slices, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let v = &[10, 40, 30]; let prefix = &[10]; let result = v.trim_prefix(prefix); // result will be &[40, 30] ``` ### Response #### Success Response Returns a slice of the same type as the original slice. #### Response Example ```rust // For input: v = &[10, 40, 30], prefix = &[10] // Output: &[40, 30] // For input: v = &[10, 40, 30], prefix = &[50] // Output: &[10, 40, 30] ``` ```