### Rust Example: Using get for Safe Element and Subslice Access Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/alonzo/struct.Bytes This example demonstrates the `get` method for safely accessing individual elements or sub-slices of a Rust slice using an index or a range. It highlights how `get` returns an `Option` to handle out-of-bounds access gracefully, preventing panics. ```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)); ``` -------------------------------- ### Rust Slice starts_with Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/codec/minicbor/bytes/struct.ByteVec Shows how to use the `starts_with` method to determine if a slice begins with a specified prefix. Examples cover various prefix lengths, including the entire slice and empty prefixes. ```Rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```Rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Rust Slice: `get` Method Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/alonzo/struct.BoundedBytes Provides examples for the `get` method on Rust slices, showing how to safely retrieve a single element or a subslice using an index or a range. It highlights how `get` returns `None` for out-of-bounds access, preventing panics. ```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)); ``` -------------------------------- ### BlockFetch Server Methods API Reference Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/blockfetch/struct.Server Comprehensive API documentation for the methods implemented by the `Server` struct, covering initialization, state management, and message exchange within the BlockFetch mini-protocol. These methods allow interaction with the underlying multiplexer agent channel. ```APIDOC impl Server pub fn new(channel: AgentChannel) -> Server - Description: Create a new BlockFetch server from a multiplexer agent channel. - Parameters: - channel: AgentChannel - A multiplexer agent channel used for communication with the server. - Returns: Server - A new instance of the BlockFetch server. pub fn state(&self) -> &State - Description: Get the current state of the server. - Returns: &State - The current state of the server (e.g., `Idle`, `Busy`, `Done`). pub fn is_done(&self) -> bool - Description: Check if the server is in the `Done` state. - Returns: bool - true if the server has completed its operation and is in the `Done` state, false otherwise. pub async fn send_message(&mut self, msg: &Message) -> Result<(), ServerError> - Description: Sends a generic message over the channel to the connected client. - Parameters: - msg: &Message - The message to send, typically an enum variant representing a BlockFetch protocol message. - Returns: Result<(), ServerError> - An empty Result on successful message transmission, or a `ServerError` if an error occurs during sending. pub async fn recv_message(&mut self) -> Result - Description: Receives a generic message from the connected client over the channel. - Returns: Result - The received `Message` on success, or a `ServerError` if an error occurs during reception. pub async fn send_start_batch(&mut self) -> Result<(), ServerError> - Description: Sends a signal to the client indicating the start of a new batch of blocks. - Returns: Result<(), ServerError> - An empty Result on success, or a `ServerError` on failure. pub async fn send_no_blocks(&mut self) -> Result<(), ServerError> - Description: Sends a signal to the client indicating that no blocks are currently available to be sent. - Returns: Result<(), ServerError> - An empty Result on success, or a `ServerError` on failure. pub async fn send_block(&mut self, body: Vec) -> Result<(), ServerError> - Description: Sends a block with the given raw byte body to the client. - Parameters: - body: Vec - The raw bytes representing the block content. - Returns: Result<(), ServerError> - An empty Result on successful block transmission, or a `ServerError` on failure. ``` -------------------------------- ### Getting a Mutable Fixed-Size Chunk from the Start of a Rust Slice Source: https://docs.rs/pallas/0.32.1/pallas/codec/minicbor/bytes/struct.ByteVec This example illustrates how to use `first_chunk_mut` to obtain a mutable array reference of a specified size `N` from the beginning of a Rust slice. It demonstrates modifying the elements within the chunk and handling cases where the slice is shorter than `N`. ```Rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### Rust Slice starts_with Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/enum.KeyValuePairs Examples demonstrating the usage of the `starts_with` method on Rust slices to check if a slice begins with a specified prefix. ```Rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```Rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Getting an Immutable Fixed-Size Chunk from the Start of a Rust Slice Source: https://docs.rs/pallas/0.32.1/pallas/codec/minicbor/bytes/struct.ByteVec This example demonstrates how to use `first_chunk` to extract an immutable array reference of a specified size `N` from the beginning of a Rust slice. It shows successful extraction, cases where the slice is too short (returning `None`), and extracting an empty chunk. ```Rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### Rust Slice starts_with Method and Examples Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/localstate/queries_v16/primitives/struct.Bytes Documents the `starts_with` method for Rust slices, which determines if a slice begins with a specified prefix. It includes the method signature, parameters, return value, and examples demonstrating checks with various prefixes, including empty slices. ```APIDOC pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq - Returns `true` if `needle` is a prefix of the slice or equal to the slice. - Parameters: - self: The slice to check. - needle: The slice to check for as a prefix. - Returns: bool - `true` if the slice starts with `needle`, `false` otherwise. - Notes: Always returns `true` if `needle` is an empty slice. ``` ```Rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```Rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Mutably Reverse Split Rust Slice and Modify (`rsplitn_mut`) Source: https://docs.rs/pallas/0.32.1/pallas/codec/utils/struct.Bytes Illustrates how to use `rsplitn_mut` to get mutable sub-slices from a Rust array, starting the split from the end. The example splits the array by numbers divisible by 3, limits to two groups, and then modifies the first element of each resulting group. ```Rust let mut s = [10, 40, 30, 20, 60, 50]; for group in s.rsplitn_mut(2, |num| *num % 3 == 0) { group[0] = 1; } assert_eq!(s, [1, 40, 30, 20, 60, 1]); ``` -------------------------------- ### Rust Slice starts_with Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/codec/utils/enum.NonEmptyKeyValuePairs Practical examples demonstrating the `starts_with` method for Rust slices. This method checks if a slice begins with a specified `needle` slice. The examples cover various scenarios, including checking for non-empty prefixes and the special case of an empty `needle`. ```Rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```Rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Rust Slice get() Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/enum.MaybeIndefArray Examples demonstrating the usage of the `get()` method on Rust slices. This method safely retrieves an immutable reference to an element or subslice, returning `Some(value)` if the index is within bounds, and `None` otherwise. It supports both single-element indexing and range-based subslice retrieval. ```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)); ``` -------------------------------- ### Rust Slice starts_with Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/chainsync/struct.BlockContent Examples demonstrating the `starts_with` method for checking if a Rust slice begins with a given prefix. Includes cases with non-empty and empty prefix slices. ```Rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```Rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### PeerServer Implementation Methods Source: https://docs.rs/pallas/0.32.1/pallas/network/facades/struct.PeerServer Documents the methods implemented for the `PeerServer` struct, including its constructor (`new`), an asynchronous method for accepting incoming connections (`accept`), and accessor methods for its internal miniprotocol servers. These methods provide the primary interface for interacting with a `PeerServer` instance. ```APIDOC pub fn new(bearer: Bearer) -> PeerServer - Description: Creates a new instance of the PeerServer. - Parameters: - bearer: An enum representing the network bearer (e.g., TCP connection). - Returns: A new PeerServer instance. pub async fn accept(listener: &TcpListener, magic: u64) -> Result - Description: Asynchronously accepts an incoming network connection and initializes a PeerServer from it. - Parameters: - listener: A reference to a Tokio TcpListener for incoming connections. - magic: A u64 value representing the network magic, used for protocol versioning. - Returns: A Result containing a PeerServer instance on success or an Error on failure. pub fn handshake(&mut self) -> &mut Server - Description: Provides mutable access to the internal handshake server. - Returns: A mutable reference to the handshake server. pub fn chainsync(&mut self) -> &mut Server - Description: Provides mutable access to the internal chainsync server. - Returns: A mutable reference to the chainsync server. pub fn blockfetch(&mut self) -> &mut Server - Description: Provides mutable access to the internal blockfetch server. - Returns: A mutable reference to the blockfetch server. ``` -------------------------------- ### Rust Slice first() Method Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/struct.Set Example of using `first()` on a Rust slice to get an optional reference to its first element. ```Rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Rust Slice `as_rchunks` Example Source: https://docs.rs/pallas/0.32.1/pallas/codec/utils/struct.Set Presents an example of `slice::as_rchunks`, which is similar to `as_chunks` but performs the chunking starting from the end of the slice. This results in the remainder appearing at the beginning of the returned tuple. The example demonstrates how the remainder and chunks are formed when processing from the right. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### GenericClient API Reference for Local State Protocol Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/localstate/struct.GenericClient Comprehensive API documentation for the `GenericClient` struct, providing methods for initializing the client, checking its state, sending and receiving protocol messages, and managing state acquisition and release within the Pallas network's local state miniprotocol. ```APIDOC GenericClient Struct Methods: pub fn new(channel: AgentChannel) -> GenericClient - Description: Creates a new instance of the GenericClient. - Parameters: - channel: AgentChannel - The communication channel for the client. - Returns: GenericClient - A new client instance. pub fn state(&self) -> &State - Description: Retrieves the current state of the client. - Parameters: - &self: Immutable reference to the client. - Returns: &State - A reference to the current state enum. pub fn is_done(&self) -> bool - Description: Checks if the client has completed its operation. - Parameters: - &self: Immutable reference to the client. - Returns: bool - True if the client is done, false otherwise. pub async fn send_message(&mut self, msg: &Message) -> Result<(), ClientError> - Description: Asynchronously sends a message to the remote peer. - Parameters: - &mut self: Mutable reference to the client. - msg: &Message - The message to be sent. - Returns: Result<(), ClientError> - Ok(()) on success, or ClientError on failure. pub async fn recv_message(&mut self) -> Result - Description: Asynchronously receives a message from the remote peer. - Parameters: - &mut self: Mutable reference to the client. - Returns: Result - Ok(Message) with the received message, or ClientError on failure. pub async fn send_acquire( &mut self, point: Option, ) -> Result<(), ClientError> - Description: Sends an acquire request to obtain a specific state point. - Parameters: - &mut self: Mutable reference to the client. - point: Option - The optional point to acquire. If None, acquires the current tip. - Returns: Result<(), ClientError> - Ok(()) on success, or ClientError on failure. pub async fn send_reacquire( &mut self, point: Option, ) -> Result<(), ClientError> - Description: Sends a reacquire request to update the acquired state point. - Parameters: - &mut self: Mutable reference to the client. - point: Option - The optional point to reacquire. - Returns: Result<(), ClientError> - Ok(()) on success, or ClientError on failure. pub async fn send_release(&mut self) -> Result<(), ClientError> - Description: Sends a release request, indicating the client no longer needs the acquired state. - Parameters: - &mut self: Mutable reference to the client. - Returns: Result<(), ClientError> - Ok(()) on success, or ClientError on failure. ``` -------------------------------- ### GenericServer Struct Methods (pallas-network) Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/localstate/struct.GenericServer API documentation for the `GenericServer` struct, detailing its constructor, state accessors, and asynchronous methods for sending and receiving messages, handling acquisition failures, and confirming acquisition or sending results within the local state miniprotocol. ```APIDOC impl GenericServer: pub fn new(channel: AgentChannel) -> GenericServer - Description: Creates a new instance of GenericServer. - Parameters: - channel: AgentChannel - The communication channel for the server. - Returns: GenericServer - A new GenericServer instance. pub fn state(&self) -> &State - Description: Returns the current state of the GenericServer. - Parameters: None - Returns: &State - A reference to the current state. pub fn is_done(&self) -> bool - Description: Checks if the server has completed its operation. - Parameters: None - Returns: bool - True if the server is done, false otherwise. pub async fn send_message(&mut self, msg: &Message) -> Result<(), Error> - Description: Asynchronously sends a message through the server's channel. - Parameters: - msg: &Message - The message to send. - Returns: Result<(), Error> - Ok(()) on success, or an Error. pub async fn recv_message(&mut self) -> Result - Description: Asynchronously receives a message from the server's channel. - Parameters: None - Returns: Result - The received Message on success, or an Error. pub async fn send_failure(&mut self, reason: AcquireFailure) -> Result<(), Error> - Description: Asynchronously sends an acquisition failure message. - Parameters: - reason: AcquireFailure - The reason for the acquisition failure. - Returns: Result<(), Error> - Ok(()) on success, or an Error. pub async fn send_acquired(&mut self) -> Result<(), Error> - Description: Asynchronously sends a message indicating successful acquisition. - Parameters: None - Returns: Result<(), Error> - Ok(()) on success, or an Error. pub async fn send_result(&mut self, response: AnyCbor) -> Result<(), Error> - Description: Asynchronously sends a result message, typically after an operation. - Parameters: - response: AnyCbor - The CBOR-encoded response to send. - Returns: Result<(), Error> - Ok(()) on success, or an Error. ``` -------------------------------- ### Rust split_last_chunk_mut Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/enum.MaybeIndefArray Shows how to use `split_last_chunk_mut` to get a mutable reference to the last `N` elements of a slice and the preceding elements. The example modifies both parts of the split slice. ```Rust let x = &mut [0, 1, 2]; if let Some((elements, last)) = x.split_last_chunk_mut::<2>() { last[0] = 3; last[1] = 4; elements[0] = 5; } assert_eq!(x, &[5, 3, 4]); assert_eq!(None, x.split_last_chunk_mut::<4>()); ``` -------------------------------- ### Example of Rust Slice `iter_mut` Method Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/struct.NonEmptySet Illustrates the use of `iter_mut` to get a mutable iterator over a slice, allowing in-place modification of elements. The example adds 2 to each element in the slice. ```Rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### FollowTipRequest Trait Implementations API Documentation Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/sync/struct.FollowTipRequest API documentation for the standard Rust trait implementations for the `FollowTipRequest` struct. This includes methods from the `Clone`, `Debug`, and `Default` traits, providing functionality for duplication, formatting for debugging, and obtaining a default instance. ```APIDOC Trait Implementations for FollowTipRequest: impl Clone: fn clone(&self) -> FollowTipRequest Description: Returns a duplicate of the value. const fn clone_from(&mut self, source: &Self) Description: Performs copy-assignment from `source`. impl Debug: fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> Description: Formats the value using the given formatter. impl Default: fn default() -> FollowTipRequest Description: Returns the “default value” for a type. ``` -------------------------------- ### WatchServiceServer Methods (Rust APIDOC) Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/watch/watch_service_server/struct.WatchServiceServer API documentation for the methods available on the `WatchServiceServer` struct. These methods facilitate the creation, configuration, and management of the watch service, including constructors, interceptor integration, and compression settings. ```APIDOC impl WatchServiceServer where T: WatchService pub fn new(inner: T) -> WatchServiceServer - Description: Creates a new `WatchServiceServer` instance. - Parameters: - inner: An instance of a type `T` that implements `WatchService`. - Returns: A new `WatchServiceServer` instance. pub fn from_arc(inner: Arc) -> WatchServiceServer - Description: Creates a new `WatchServiceServer` instance from an `Arc` (atomically reference counted pointer). - Parameters: - inner: An `Arc` containing an instance of a type `T` that implements `WatchService`. - Returns: A new `WatchServiceServer` instance. pub fn with_interceptor(inner: T, interceptor: F) -> InterceptedService, F> - Description: Creates an `InterceptedService` that wraps the `WatchServiceServer` with a custom interceptor. - Parameters: - inner: An instance of a type `T` that implements `WatchService`. - interceptor: A function `F` that implements the `Interceptor` trait. - Returns: An `InterceptedService` instance. pub fn accept_compressed(self, encoding: CompressionEncoding) -> WatchServiceServer - Description: Configures the `WatchServiceServer` to enable decompressing incoming requests with the specified encoding. - Parameters: - self: The `WatchServiceServer` instance. - encoding: The `CompressionEncoding` to accept (e.g., Gzip, Deflate). - Returns: The modified `WatchServiceServer` instance. pub fn send_compressed(self, encoding: CompressionEncoding) -> WatchServiceServer - Description: Configures the `WatchServiceServer` to compress outgoing responses with the given encoding, if the client supports it. - Parameters: - self: The `WatchServiceServer` instance. - encoding: The `CompressionEncoding` to use for responses. - Returns: The modified `WatchServiceServer` instance. ``` -------------------------------- ### Rust Slice len() Method Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/struct.Bytes Illustrates how to use the `len()` method to get the number of elements in a Rust slice. This example confirms the expected length of a fixed-size array. ```Rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Example usage of Rust slice `get` method Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/struct.NonEmptySet Demonstrates how to use the `get` method to safely retrieve elements or subslices from a Rust array, returning `Some` if the index is valid and `None` otherwise. ```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)); ``` -------------------------------- ### SubmitServiceClient API Methods Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/submit/submit_service_client/struct.SubmitServiceClient API documentation for the `SubmitServiceClient` in the `utxorpc-spec` crate, providing methods for client initialization and setting the origin URI. ```APIDOC SubmitServiceClient: pub fn new(inner: T) -> SubmitServiceClient - Description: Creates a new instance of the SubmitServiceClient. - Parameters: - inner: T - The inner service implementation. - Returns: SubmitServiceClient - A new client instance. pub fn with_origin(inner: T, origin: Uri) -> SubmitServiceClient - Description: Creates a new instance of the SubmitServiceClient with a specified origin URI. - Parameters: - inner: T - The inner service implementation. - origin: Uri - The URI to set as the client's origin. - Returns: SubmitServiceClient - A new client instance with the specified origin. ``` -------------------------------- ### Example of Rust slice get method Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/struct.NonEmptySet Demonstrates how to use the `get` method to safely access elements or subslices of a Rust slice, handling both valid and out-of-bounds indices by returning `Some` or `None`. ```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)); ``` -------------------------------- ### WatchServiceClient Constructor and Configuration Methods (Rust) Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/watch/watch_service_client/struct.WatchServiceClient This section documents the primary methods for initializing and configuring the `WatchServiceClient` in Rust. It includes the basic constructor and a method to specify an origin URI for the client's requests. ```Rust pub fn new(inner: T) -> WatchServiceClient - Description: Creates a new instance of the `WatchServiceClient`. - Parameters: - inner: `T` - The underlying transport or service implementation that the client will use to communicate. - Returns: `WatchServiceClient` - A new client instance ready for use. pub fn with_origin(inner: T, origin: Uri) -> WatchServiceClient - Description: Creates a new `WatchServiceClient` instance, explicitly setting an origin URI for its requests. - Parameters: - inner: `T` - The underlying transport or service implementation. - origin: `Uri` - The URI to be used as the origin for outgoing requests from this client. - Returns: `WatchServiceClient` - A new client instance configured with the specified origin. ``` -------------------------------- ### Rust last_chunk_mut Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/enum.MaybeIndefArray Illustrates the use of `last_chunk_mut` to get a mutable reference to the last `N` elements of a slice. The example modifies the elements within the retrieved chunk and checks for cases where the chunk cannot be formed. ```Rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); assert_eq!(None, x.last_chunk_mut::<4>()); ``` -------------------------------- ### Rust Vec Type Core Methods API Documentation Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/localstate/queries_v16/primitives/struct.Bytes Comprehensive API documentation for essential methods of the Rust `Vec` type, including `capacity`, `as_slice`, `as_ptr`, `allocator`, and `len`. Each entry details the method signature, purpose, parameters, return values, and provides illustrative code examples where available. ```APIDOC pub fn capacity(&self) -> usize - Returns the total number of elements the vector can hold without reallocating. - Examples: let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); #[derive(Clone)] struct ZeroSized; fn main() { assert_eq!(std::mem::size_of::(), 0); let v = vec![ZeroSized; 0]; assert_eq!(v.capacity(), usize::MAX); } pub fn as_slice(&self) -> &[T] - Extracts a slice containing the entire vector. - Equivalent to `&s[..]`. - Examples: use std::io::{self, Write}; let buffer = vec![1, 2, 3, 5, 8]; io::sink().write(buffer.as_slice()).unwrap(); pub fn as_ptr(&self) -> *const T - Returns a raw pointer to the vector’s buffer, or a dangling raw pointer valid for zero sized reads if the vector didn’t allocate. - The caller must ensure that the vector outlives the pointer this function returns, or else it will end up dangling. - Modifying the vector may cause its buffer to be reallocated, which would also make any pointers to it invalid. - The caller must also ensure that the memory the pointer (non-transitively) points to is never written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If you need to mutate the contents of the slice, use `as_mut_ptr`. - This method guarantees that for the purpose of the aliasing model, this method does not materialize a reference to the underlying slice, and thus the returned pointer will remain valid when mixed with other calls to `as_ptr`, `as_mut_ptr`, and `as_non_null`. - Note that calling other methods that materialize mutable references to the slice, or mutable references to specific elements you are planning on accessing through this pointer, as well as writing to those elements, may still invalidate this pointer. - See the second example below for how this guarantee can be used. - Examples: let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } pub fn allocator(&self) -> &A - 🔬This is a nightly-only experimental API. (`allocator_api`) - Returns a reference to the underlying allocator. pub fn len(&self) -> usize - Returns the number of elements in the vector, also referred to as its ‘length’. ``` -------------------------------- ### Example Usage of Rust Slice get Method Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/enum.MaybeIndefArray Demonstrates how to use the `get` method on a Rust slice to safely retrieve elements or subslices, handling cases where the index is within or 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)); ``` -------------------------------- ### PeerServer Struct API Reference Source: https://docs.rs/pallas/0.32.1/pallas/network/facades/struct.PeerServer Comprehensive API documentation for the `PeerServer` struct within the `pallas::network::facades` module, detailing its fields, methods, and implemented traits for network communication. ```APIDOC PeerServer Struct: Fields: - blockfetch: Related to block fetching. - chainsync: Related to chain synchronization. - handshake: Related to network handshake. - keepalive: Related to keep-alive mechanisms. - plexer: Related to network multiplexing. - txsubmission: Related to transaction submission. Methods: - abort(): Aborts the PeerServer operation. - accept(): Accepts an incoming connection. - accepted_address(): Returns the accepted network address. - accepted_version(): Returns the accepted protocol version. - blockfetch(): Accesses blockfetch related functionality. - chainsync(): Accesses chainsync related functionality. - handshake(): Accesses handshake related functionality. - keepalive(): Accesses keepalive related functionality. - new(): Constructor for PeerServer. - txsubmission(): Accesses txsubmission related functionality. Auto Trait Implementations: - Freeze - RefUnwindSafe - Send - Sync - Unpin - UnwindSafe Blanket Implementations: - Any - Borrow - BorrowMut - From - Instrument - Into - IntoEither - IntoRequest - TryFrom - TryInto - VZip - WithSubscriber ``` -------------------------------- ### Rust Slice as_mut_ptr Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/struct.Bytes Illustrates the use of `as_mut_ptr` to get a mutable raw pointer to a slice. The example shows how to modify slice elements directly via pointer arithmetic in an `unsafe` context. ```Rust let x = &mut [1, 2, 4]; let x_ptr = x.as_mut_ptr(); unsafe { for i in 0..x.len() { *x_ptr.add(i) += 2; } } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Pallas Network BlockFetch Client API Reference Source: https://docs.rs/pallas/0.32.1/pallas/network/miniprotocols/blockfetch/struct.Client Comprehensive API documentation for the `Client` struct in the Pallas network library's BlockFetch mini-protocol. This includes methods for creating a new client, checking its state, sending and receiving messages, and initiating block range requests for fetching data from the Cardano network. ```APIDOC impl Client pub fn new(channel: AgentChannel) -> Client - Description: Create a new BlockFetch client from a multiplexer agent channel. - Parameters: - channel: A multiplexer agent channel used for communication with the remote node. pub fn state(&self) -> &State - Description: Get the current state of the client. - Returns: The current state of the client. pub fn is_done(&self) -> bool - Description: Check if the client is done. - Returns: true if the client is in the `Done` state, false otherwise. pub async fn send_message(&mut self, msg: &Message) -> Result<(), ClientError> - Description: Sends a message to the remote node using the BlockFetch mini-protocol. - Parameters: - msg: The message to send. - Returns: A `Result` indicating success or a `ClientError`. pub async fn recv_message(&mut self) -> Result - Description: Receives a message from the remote node using the BlockFetch mini-protocol. - Returns: A `Result` containing the received `Message` or a `ClientError`. pub async fn send_request_range(&mut self, range: (Point, Point)) -> Result<(), ClientError> - Description: Sends a request to the remote node to fetch a range of blocks. - Parameters: - range: A tuple representing the start and end points of the block range. - Returns: A `Result` indicating success or a `ClientError`. pub async fn recv_while_busy(&mut self) -> Result, ClientError> - Description: Continuously receives messages while the client is in a busy state, processing incoming data. - Returns: A `Result` indicating completion or a `ClientError`. ``` -------------------------------- ### Pallas minicbor Data Module API Reference Source: https://docs.rs/pallas/0.32.1/pallas/codec/minicbor/data/index API documentation for the `pallas::codec::minicbor::data` module, detailing its core data types, tokens, and tags for CBOR handling within the Pallas Rust crate. ```APIDOC Module data: CBOR data types, tokens and tags. Structs: Int: CBOR integer type that covers values of [-2^64, 2^64 - 1] Tag: CBOR data item tag. Tagged: Statically tag a value. TryFromIntError: Error when conversion of a CBOR `Int` to another type failed. UnknownTag: Error indicating that a tag value is unknown to `IanaTag`. Enums: IanaTag: IANA registered tags. Token: Representation of possible CBOR tokens. Type: CBOR data types. Constants: MAX_INT: Max. CBOR integer value (2^64 - 1). MIN_INT: Min. CBOR integer value (-2^64). ``` -------------------------------- ### Rust Vec as_ptr Method Examples Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/struct.Bytes Examples illustrating the usage of `as_ptr()` to get a raw pointer to the vector's buffer, including iterating through elements and demonstrating aliasing guarantees in unsafe blocks. ```Rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```Rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### Rust FollowTipResponse Struct API Documentation Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/sync/struct.FollowTipResponse Documents the `FollowTipResponse` struct from the `pallas` crate, outlining its fields and various trait implementations, including those for serialization, deserialization, cloning, and debugging, as well as auto and blanket implementations. ```APIDOC FollowTipResponse struct: Fields: - action Trait Implementations: - Clone - Debug - Default - Deserialize<'de> - Message - PartialEq - Serialize - StructuralPartialEq Auto Trait Implementations: - !Freeze - RefUnwindSafe - Send - Sync - Unpin - UnwindSafe Blanket Implementations: - Any - Borrow - BorrowMut - CloneToUninit - DeserializeOwned - From - Instrument - Into - IntoEither - IntoRequest - ToOwned - TryFrom - TryInto - VZip - WithSubscriber ``` -------------------------------- ### Example Usage of Rust slice::last_chunk_mut Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/alonzo/enum.KeyValuePairs Illustrates how to use the `last_chunk_mut` method to get a mutable reference to the last N elements of a Rust slice. It includes an example of modifying the elements within the retrieved mutable chunk. ```Rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); assert_eq!(None, x.last_chunk_mut::<4>()); ``` -------------------------------- ### SyncServiceServer Constructor and Configuration Methods Source: https://docs.rs/pallas/0.32.1/pallas/interop/utxorpc/spec/sync/sync_service_server/struct.SyncServiceServer Provides a comprehensive set of methods for instantiating and configuring the `SyncServiceServer`. This includes standard constructors, methods for adding custom interceptors to the service, and options to enable or disable compression for both incoming requests and outgoing responses. ```APIDOC SyncServiceServer Methods: new(inner: T) -> SyncServiceServer - Creates a new SyncServiceServer instance with the given inner service. - Parameters: - inner: The service implementation. from_arc(inner: Arc) -> SyncServiceServer - Creates a new SyncServiceServer instance from an Arc-wrapped inner service. - Parameters: - inner: An Arc-wrapped service implementation. with_interceptor(inner: T, interceptor: F) -> InterceptedService, F> - Creates a new SyncServiceServer instance with a custom interceptor. - Parameters: - inner: The service implementation. - interceptor: A function or type implementing the Interceptor trait. - Constraints: F must implement tonic::service::interceptor::Interceptor. accept_compressed(self, encoding: CompressionEncoding) -> SyncServiceServer - Enables decompressing incoming requests with the specified encoding. - Parameters: - self: The SyncServiceServer instance. - encoding: The compression encoding to accept (e.g., Gzip, Deflate). send_compressed(self, encoding: CompressionEncoding) -> SyncServiceServer - Configures the server to compress outgoing responses with the specified encoding, if the client supports it. - Parameters: - self: The SyncServiceServer instance. - encoding: The compression encoding to use for responses. ``` -------------------------------- ### Rust Slice as_ptr Example Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/conway/enum.NonEmptyKeyValuePairs Shows how to get a raw constant pointer to a slice's buffer using `as_ptr`. The example then uses this pointer with `get_unchecked` for comparison, highlighting the `unsafe` nature of raw pointer arithmetic. ```Rust let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` -------------------------------- ### Get Mutable First N Elements as Chunk from Rust Slice Source: https://docs.rs/pallas/0.32.1/pallas/ledger/primitives/alonzo/enum.MaybeIndefArray Example demonstrating the `first_chunk_mut` method to get a mutable array reference to the first N elements of a Rust slice, allowing their modification. ```Rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ```