### SrtSocketBuilder Examples Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocketBuilder.html Illustrative examples of how to use SrtSocketBuilder to create SRT sockets. ```APIDOC ### Examples: Simple: ```rust let (a, b) = futures::try_join!( SrtSocket::builder().listen_on(":3333"), SrtSocket::builder().call("127.0.0.1:3333", Some("stream ID")), )?; ``` Rendezvous example: ```rust let (a, b) = futures::try_join!( SrtSocket::builder().local_port(5555).rendezvous("127.0.0.1:4444"), SrtSocket::builder() .set(|options| { options.connect.timeout = Duration::from_secs(2); options.receiver.buffer_size = ByteCount(120000); options.sender.max_payload_size = PacketSize(1200); options.session.peer_idle_timeout = Duration::from_secs(5); }) .local_port(4444) .rendezvous("127.0.0.1:5555"), )?; ``` ``` -------------------------------- ### Simple SRT Socket Connection Example Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/builder.rs.html Demonstrates a basic setup for two SRT sockets to connect to each other. One socket listens on a port, and the other calls the listening socket's address. ```rust use srt_tokio::{SrtSocket, options::*}; use std::io; #[tokio::main] async fn main() -> Result<(), io::Error> { let (a, b) = futures::try_join!( SrtSocket::builder().listen_on(":3333"), SrtSocket::builder().call("127.0.0.1:3333", Some("stream ID")), )?; Ok(()) } ``` -------------------------------- ### Simple SrtListener Binding Example Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/builder.rs.html Demonstrates how to create and bind an SrtListener with custom socket options. This example sets connection timeout, receiver buffer size, sender max payload size, and peer idle timeout. ```rust use srt_tokio::{SrtListener, options::*}; use std::{io, time::Duration}; #[tokio::main] async fn main() -> Result<(), io::Error> { let listener = SrtListener::builder() .set(|options| { options.connect.timeout = Duration::from_secs(2); options.receiver.buffer_size = ByteCount(120000); options.sender.max_payload_size = PacketSize(1200); options.session.peer_idle_timeout = Duration::from_secs(5); }).bind("127.0.0.1:4444").await?; Ok(()) } ``` -------------------------------- ### String capacity Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Shows how to check the allocated capacity of a String. ```rust let s = String::with_capacity(10); assert!(s.capacity() >= 10); ``` -------------------------------- ### SRT Socket Quick Start: Sender and Receiver Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/lib.rs.html Demonstrates how to set up an SRT sender and receiver using srt-tokio. The sender listens on a port and sends data, while the receiver connects to the sender and verifies the received data. This example requires tokio for asynchronous operations. ```rust #![forbid(unsafe_code)] #![recursion_limit = "256"] //! Implementation of [SRT](https://www.haivision.com/products/srt-secure-reliable-transport/) in pure safe rust. //! //! Generally used for live video streaming across lossy but high bandwidth connections. //! //! # Quick start //! ```rust //! use srt_tokio::SrtSocket; //! use futures::prelude::*; //! use bytes::Bytes; //! use std::time::Instant; //! use std::io; //! //! #[tokio::main] //! async fn main() //!# // keep this to quell `needless_doctest_main` warning //!# -> () //!# { //! let sender_fut = async { //! let mut tx = SrtSocket::builder().listen_on(2223).await?; //! //! let iter = ["1", "2", "3"]; //! //! tx.send_all(&mut stream::iter(&iter) //! .map(|b| Ok((Instant::now(), Bytes::from(*b))))).await?; //! tx.close().await?; //! //! Ok::<_, io::Error>(()) //! }; //! //! let receiver_fut = async { //! let mut rx = SrtSocket::builder().call("127.0.0.1:2223", None).await?; //! //! assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"1"[..].into())); //! assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"2"[..].into())); //! assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"3"[..].into())); //! assert_eq!(rx.try_next().await?, None); //! //! Ok::<_, io::Error>(()) //! }; //! //! futures::try_join!(sender_fut, receiver_fut).unwrap(); //! } //! //! ``` ``` -------------------------------- ### str len Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates getting the byte length of a string slice, highlighting differences for 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); ``` -------------------------------- ### String is_empty Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Shows how to check if a String is empty. ```rust let mut v = String::new(); assert!(v.is_empty()); v.push('a'); assert!(!v.is_empty()); ``` -------------------------------- ### String as_bytes Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Illustrates converting a String to its byte slice representation. ```rust let s = String::from("hello"); assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes()); ``` -------------------------------- ### String len Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates getting the byte length of a String, noting it may differ from character count for multi-byte characters. ```rust let a = String::from("foo"); assert_eq!(a.len(), 3); let fancy_f = String::from("ƒoo"); assert_eq!(fancy_f.len(), 4); assert_eq!(fancy_f.chars().count(), 3); ``` -------------------------------- ### Get SrtListener Settings Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtListener.html Retrieves a reference to the connection initialization settings for the SrtListener. These settings are used during the connection setup. ```rust pub fn settings(&self) -> &ConnInitSettings ``` -------------------------------- ### ListenerOptions::new Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.ListenerOptions.html Creates a new ListenerOptions instance with the specified local address. This is a constructor for basic listener setup. ```APIDOC ## fn new ### Description Creates a new `ListenerOptions` instance with the specified local address. ### Signature ```rust pub fn new(local: impl TryInto) -> Result, OptionsError> ``` ### Parameters * `local`: An address that can be converted into a `SocketAddress`. ``` -------------------------------- ### Rust trim_start_matches Examples Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates removing matching prefixes from a string slice using `trim_start_matches` with characters, numeric checks, and character arrays. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Get Listener Settings Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/mod.rs.html Returns a reference to the connection initialization settings of the SRT listener. ```rust pub fn settings(&self) -> &ConnInitSettings { &self.settings } ``` -------------------------------- ### String as_str Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates how to extract a string slice from a String. ```rust let s = String::from("foo"); assert_eq!("foo", s.as_str()); ``` -------------------------------- ### Connect Default Implementation Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.Connect.html Provides the default configuration for the Connect struct. This is useful for creating a basic connection setup without specifying every option. ```rust fn default() -> Connect ``` -------------------------------- ### Create SRT Socket Builder Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/mod.rs.html Use `SrtSocket::builder()` to start constructing an SRT socket. This is the entry point for configuring and creating new SRT connections. ```rust pub fn builder() -> SrtSocketBuilder { SrtSocketBuilder::default() } ``` -------------------------------- ### PendingConnection Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/session.rs.html Manages the state of a connection that is pending approval or setup. ```APIDOC ## Struct PendingConnection Manages the state of a connection that is pending approval or setup. ### Methods * **`start_approval(session_id: SessionId, request: AccessControlRequest, response_sender: mpsc::Sender<(SessionId, AccessControlResponse)>)`** -> `(PendingConnection, ConnectionRequest)` Initiates the approval process for a new connection, returning the `PendingConnection` state and the `ConnectionRequest` object. * **`transition_to_open(socket: &PacketSocket, connection: Connection)`** -> `Result` Transitions a pending connection to an open state, returning an `OpenConnection` handle. This method requires the packet socket and connection details. ``` -------------------------------- ### str is_empty Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Shows how to check if a string slice is empty. ```rust let s = ""; assert!(s.is_empty()); let s = "not empty"; assert!(!s.is_empty()); ``` -------------------------------- ### SrtSocket Start Send Implementation Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocket.html Begins the process of sending an item to the SrtSocket sink. Must be preceded by a successful poll_ready call. ```rust fn start_send( self: Pin<&mut Self>, item: (Instant, Bytes), ) -> Result<(), Self::Error> ``` -------------------------------- ### SRT Socket Rendezvous Example with Custom Options Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/builder.rs.html Illustrates a rendezvous connection between two SRT sockets, showcasing custom configuration for latency, buffer size, payload size, and timeouts. ```rust use srt_tokio::{SrtSocket, options::*}; use std::{io, time::Duration}; #[tokio::main] async fn main() -> Result<(), io::Error> { let (a, b) = futures::try_join!( SrtSocket::builder().local_port(5555).rendezvous("127.0.0.1:4444"), SrtSocket::builder() .set(|options| { options.connect.timeout = Duration::from_secs(2); options.receiver.buffer_size = ByteCount(120000); options.sender.max_payload_size = PacketSize(1200); options.session.peer_idle_timeout = Duration::from_secs(5); }) .local_port(4444) .rendezvous("127.0.0.1:5555"), )?; Ok(()) } ``` -------------------------------- ### Rust strip_prefix Examples Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Illustrates using `strip_prefix` to remove a prefix exactly once if it matches, returning the remainder or None. ```rust assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar")); assert_eq!("foo:bar".strip_prefix("bar"), None); assert_eq!("foofoo".strip_prefix("foo"), Some("foo")); ``` -------------------------------- ### Default Session Configuration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.Session.html Provides the default configuration for an SRT session. This is useful when you need a basic setup without custom tuning. ```rust fn default() -> Session ``` -------------------------------- ### str as_bytes Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Converts a string slice to its byte slice representation. ```rust let bytes = "bors".as_bytes(); assert_eq!(b"bors", bytes); ``` -------------------------------- ### str is_char_boundary Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates checking if a byte index falls on a UTF-8 character boundary. ```rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` -------------------------------- ### Rendezvous SrtSocket Creation Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocketBuilder.html Illustrates how to use SrtSocketBuilder for a rendezvous connection, where both peers initiate a connection to each other on specified ports. This example also shows how to customize socket options like timeouts and buffer sizes. ```rust let (a, b) = futures::try_join!( SrtSocket::builder().local_port(5555).rendezvous("127.0.0.1:4444"), SrtSocket::builder() .set(|options| { options.connect.timeout = Duration::from_secs(2); options.receiver.buffer_size = ByteCount(120000); options.sender.max_payload_size = PacketSize(1200); options.session.peer_idle_timeout = Duration::from_secs(5); }) .local_port(4444) .rendezvous("127.0.0.1:5555"), )?; ``` -------------------------------- ### str ceil_char_boundary Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Finds the closest character boundary not below a given byte index, useful for ensuring a string slice starts at a valid character boundary. ```rust let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.ceil_char_boundary(13); assert_eq!(closest, 14); assert_eq!(&s[..closest], "❤️🧡💛"); ``` -------------------------------- ### Spawn Listener and Connect Clients Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/mod.rs.html Sets up an SRT listener and spawns multiple client tasks to connect to it. Handles both accepted and rejected connections. ```rust // connect 10 clients to it let mut join_handles = vec![]; for i in 0..10 { join_handles.push(tokio::spawn(async move { info!("Calling: {}", i); let address = "127.0.0.1:4001"; if i % 2 > 0 { let result = SrtSocket::builder().call(address, Some("reject")).await; assert!(result.is_err()); debug!("Rejected: {}", i); } else { let stream_id = format!("{i}").to_string(); let mut receiver = SrtSocket::builder() .call(address, Some(&stream_id)) .await .unwrap(); info!("Accepted: {}", i); let first = receiver.next().await; assert_eq!(first.unwrap().unwrap().1, "hello"); let second = receiver.next().await; assert!(second.is_none()); info!("Received: {}", i); } })); } // close the multiplex server when all is done join_all(join_handles).await; info!("all finished"); finished_send.send(()).unwrap(); listener.await?; Ok(()) } ``` -------------------------------- ### Handle Incoming SRT Connections Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/mod.rs.html This snippet demonstrates how to set up an SRT listener and handle incoming connections. It shows how to accept new connections and spawn a task to manage each client. ```rust async fn run_listener() -> Result<(), io::Error> { let port = 4444; let (_binding, mut incoming) = SrtListener::builder() .with(Sender { drop_delay: Duration::from_secs(20), peer_latency: Duration::from_secs(1), buffer_size: ByteCount(8192 * 100), ..Default::default() }) .bind("127.0.0.1:4444") .await .unwrap(); info!("SRT Multiplex Server is listening on port: {}", port); while let Some(request) = incoming.incoming().next().await { let mut srt_socket = request.accept(None).await.unwrap(); tokio::spawn(async move { let client_desc = format!( "(ip_port: {{}}, sockid: {{}})", srt_socket.settings().remote, srt_socket.settings().remote_sockid.0 ); info!("New client connected: {}", client_desc); let longer_than_peer_timeout = Duration::from_secs(7); let start = Instant::now(); let mut stream = stream::unfold(0, |count| async move { let res = Ok((Instant::now(), Bytes::copy_from_slice(&[0; 1316]))); sleep(Duration::from_millis(5)).await; if start.elapsed() > longer_than_peer_timeout { return None; } Some((res, count)) }) .boxed(); if let Err(e) = srt_socket.send_all(&mut stream).await { info!("Send to client: {} error: {{}}", client_desc, e); } info!("Client {} disconnected", client_desc); start.elapsed().as_secs() as i32 }); } Ok(()) } ``` -------------------------------- ### Trim Start Whitespace Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Removes leading whitespace from a string slice. The definition of 'start' depends on the text's directionality. ```rust let s = "\n Hello\tworld\t\n"; assert_eq!("Hello\tworld\t\n", s.trim_start()); ``` ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### Get Duration as f32 seconds Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_secs_f32` to get the total number of seconds from a Duration, including the fractional part, as an f32. ```rust use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.as_secs_f32(), 2.7); ``` -------------------------------- ### Get Duration as f64 seconds Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_secs_f64` to get the total number of seconds from a Duration, including the fractional part, as an f64. ```rust use std::time::Duration; let dur = Duration::new(2, 700_000_000); assert_eq!(dur.as_secs_f64(), 2.7); ``` -------------------------------- ### SRT Sender and Receiver Example Source: https://docs.rs/srt-tokio/latest/index.html This snippet demonstrates a full-duplex SRT communication. The sender listens on a port and sends data, while the receiver connects to the sender and verifies the received data. Ensure futures and bytes crates are included as dependencies. ```rust use srt_tokio::SrtSocket; use futures::prelude::*; use bytes::Bytes; use std::time::Instant; use std::io; #[tokio::main] async fn main() { let sender_fut = async { let mut tx = SrtSocket::builder().listen_on(2223).await?; let iter = ["1", "2", "3"]; tx.send_all(&mut stream::iter(&iter) .map(|b| Ok((Instant::now(), Bytes::from(*b))))).await?; tx.close().await?; Ok::<_, io::Error>(()) }; let receiver_fut = async { let mut rx = SrtSocket::builder().call("127.0.0.1:2223", None).await?; assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"1"[..].into())); assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"2"[..].into())); assert_eq!(rx.try_next().await?.map(|(_i, b)| b), Some(b"3"[..].into())); assert_eq!(rx.try_next().await?, None); Ok::<_, io::Error>(()) }; futures::try_join!(sender_fut, receiver_fut).unwrap(); } ``` -------------------------------- ### Get fractional nanoseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `subsec_nanos` to get the fractional part of a second in nanoseconds. This does not return the total duration in nanoseconds. ```rust use std::time::Duration; let duration = Duration::from_millis(5_010); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_nanos(), 10_000_000); ``` -------------------------------- ### take Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocket.html Creates a new stream of at most `n` items from the underlying stream. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates a new stream of at most `n` items of the underlying stream. ### Parameters - **n** (usize) - The maximum number of items to take from the stream. ### Returns A `Take` struct representing the stream limited to `n` items. ``` -------------------------------- ### Get fractional microseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `subsec_micros` to get the fractional part of a second in microseconds. This does not return the total duration in microseconds. ```rust use std::time::Duration; let duration = Duration::from_micros(1_234_567); assert_eq!(duration.as_secs(), 1); assert_eq!(duration.subsec_micros(), 234_567); ``` -------------------------------- ### Get fractional milliseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `subsec_millis` to get the fractional part of a second in milliseconds. This does not return the total duration in milliseconds. ```rust use std::time::Duration; let duration = Duration::from_millis(5_432); assert_eq!(duration.as_secs(), 5); assert_eq!(duration.subsec_millis(), 432); ``` -------------------------------- ### SrtListener::settings Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/mod.rs.html Retrieves the connection initialization settings for the SRT listener. ```APIDOC ## SrtListener::settings ### Description Returns a reference to the `ConnInitSettings` associated with this `SrtListener`. ### Method `settings(&self) -> &ConnInitSettings` ### Returns - `&ConnInitSettings`: An immutable reference to the listener's connection initialization settings. ``` -------------------------------- ### PendingConnection and OpenConnection Structures Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/listener/session.rs.html Introduces `PendingConnection` for managing the initial stages of a connection and `OpenConnection` for an established connection. `PendingConnection` facilitates the transition to an open state, while `OpenConnection` provides methods for sending packets and closing the connection. ```rust use std::{io::ErrorKind, net::SocketAddr}; use futures::{ channel::{mpsc, oneshot}, SinkExt, }; use srt_protocol::{ connection::Connection, listener::*, options::*, packet::*, settings::*, }; use tokio::task::JoinHandle; use crate::{ net::PacketSocket, socket::factory::{self, SrtSocketFactory, SrtSocketTaskFactory}, SrtSocket, }; #[derive(Debug)] pub struct PendingConnection { settings_sender: oneshot::Sender<(ConnectionSettings, JoinHandle<()>)>, task_factory: SrtSocketTaskFactory, } impl PendingConnection { pub fn start_approval( session_id: SessionId, request: AccessControlRequest, response_sender: mpsc::Sender<(SessionId, AccessControlResponse)>, ) -> (PendingConnection, ConnectionRequest) { let (socket_factory, task_factory) = factory::split_new(); let (settings_sender, settings_receiver) = oneshot::channel(); let response_sender = ResponseSender(session_id, response_sender); let state = PendingConnection { settings_sender, task_factory, }; let request = ConnectionRequest { request, response_sender, settings_receiver, socket_factory, }; (state, request) } pub fn transition_to_open( self, socket: &PacketSocket, connection: Connection, ) -> Result { let (packet_sender, socket) = socket.clone_channel(100); let (handle, settings) = self.task_factory.spawn_task(socket, connection); self.settings_sender .send((settings, handle)) .ok() .ok_or(()?); Ok(OpenConnection { packet_sender }) } } #[derive(Debug)] pub struct OpenConnection { packet_sender: mpsc::Sender, } impl OpenConnection { pub async fn send(&mut self, packet: (Packet, SocketAddr)) -> Result<(), ()> { match self.packet_sender.try_send(Ok(packet)) { Err(e) if e.is_full() => self.packet_sender.send(e.into_inner()).await.ok().ok_or(()), r => r.ok().ok_or(()), } } pub async fn close(&mut self) -> Result<(), ()> { self.packet_sender.close().await.ok().ok_or(()) } } #[derive(Debug)] struct ResponseSender(SessionId, mpsc::Sender<(SessionId, AccessControlResponse)>); impl ResponseSender { async fn send(mut self, response: AccessControlResponse) -> Result<(), std::io::Error> { self.1 .send((self.0, response)) .await .map_err(|e| std::io::Error::new(ErrorKind::NotConnected, e)) } } ``` -------------------------------- ### AcceptParameters::new() Source: https://docs.rs/srt-tokio/latest/srt_tokio/access/struct.AcceptParameters.html Creates a new instance of AcceptParameters with default settings. ```rust pub fn new() -> AcceptParameters ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.DataRate.html Provides experimental, nightly-only functionality for cloning data to an uninitialized memory location. ```APIDOC ## CloneToUninit ### Description Performs copy-assignment from `self` to `dest`. This is a nightly-only experimental API. ### Method `clone_to_uninit` ### Parameters - **dest** (*mut u8): A mutable pointer to the destination memory location. ### Response None ``` -------------------------------- ### compare Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.SocketAddressParseError.html Compare self to `key` and return their ordering. ```APIDOC ## fn compare(&self, key: &K) -> Ordering ### Description Compare self to `key` and return their ordering. ### Method fn ### Parameters - `key`: &K - The key to compare against. ### Returns Ordering - The ordering of self relative to key. ``` -------------------------------- ### DataRate Any Implementation Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.DataRate.html Provides the ability to get the TypeId of a DataRate instance. ```rust fn type_id(&self) -> TypeId; ``` -------------------------------- ### CloneToUninit (Nightly Experimental) Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.SocketAddress.html Performs copy-assignment from self to a mutable byte pointer. This is an experimental API and requires the nightly toolchain. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters - `dest` (*mut u8) - A mutable pointer to the destination memory location. ### Safety This function is unsafe as it involves raw pointer manipulation. The caller must ensure that `dest` is a valid, mutable pointer to enough memory to hold the cloned value. ``` -------------------------------- ### Simple String Find Patterns Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates finding simple character and substring patterns within a string. ```rust let s = "Löwe 老虎 Léopard Gepardi"; assert_eq!(s.find('L'), Some(0)); assert_eq!(s.find('é'), Some(14)); assert_eq!(s.find("pard"), Some(17)); ``` -------------------------------- ### try_from Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.SocketAddressParseError.html Performs the conversion. ```APIDOC ## fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Method fn ### Parameters - `value`: U - The value to convert. ### Returns Result>::Error> - The result of the conversion. ``` -------------------------------- ### Getting Key Size Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.ConnectionRequest.html Retrieves the key size associated with the connection request. ```rust pub fn key_size(&self) -> KeySize ``` -------------------------------- ### Getting Stream ID Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.ConnectionRequest.html Retrieves the optional stream identifier associated with the connection request. ```rust pub fn stream_id(&self) -> Option<&StreamId> ``` -------------------------------- ### KeySize Methods Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.KeySize.html Provides methods to convert KeySize variants to their raw or usize representations. ```APIDOC ## impl KeySize ### `as_raw` ```rust pub fn as_raw(self) -> u8 ``` Converts the KeySize variant to its raw `u8` representation. ### `as_usize` ```rust pub fn as_usize(self) -> usize ``` Converts the KeySize variant to its `usize` representation. ``` -------------------------------- ### AcceptParameters::take_key_settings() Source: https://docs.rs/srt-tokio/latest/srt_tokio/access/struct.AcceptParameters.html Takes ownership of the key settings from AcceptParameters, leaving None in its place. Useful for retrieving and consuming the settings. ```rust pub fn take_key_settings(&mut self) -> Option ``` -------------------------------- ### Getting Remote Socket ID Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.ConnectionRequest.html Retrieves the remote socket identifier associated with the connection request. ```rust pub fn remote_socket_id(&self) -> SocketId ``` -------------------------------- ### compare Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.Percent.html Compares the Percent value with a given key and returns their ordering. ```APIDOC ## fn compare(&self, key: &K) -> Ordering ### Description Compare self to `key` and return their ordering. ### Parameters #### Path Parameters - **key** (K) - Description: The key to compare against. ``` -------------------------------- ### Getting Local Socket ID Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.ConnectionRequest.html Retrieves the local socket identifier associated with the connection request. ```rust pub fn local_socket_id(&self) -> SocketId ``` -------------------------------- ### AcceptParameters::take_key_settings Source: https://docs.rs/srt-tokio/latest/srt_tokio/access/struct.AcceptParameters.html Takes ownership of the key settings from the AcceptParameters instance. ```APIDOC ## AcceptParameters::take_key_settings ### Description Takes ownership of the key settings from the `AcceptParameters` instance. ### Method `take_key_settings(&mut self) -> Option` ### Returns An `Option` containing the key settings if they were set, otherwise `None`. ``` -------------------------------- ### Comparing Connect Configurations for Equality Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.Connect.html Tests if two Connect configurations are equal. This is used for checking if settings are identical. ```rust fn eq(&self, other: &Connect) -> bool ``` -------------------------------- ### Get total nanoseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_nanos` to retrieve the total number of nanoseconds from a Duration. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_nanos(), 5_730_023_852); ``` -------------------------------- ### Getting Remote Socket Address Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.ConnectionRequest.html Retrieves the remote socket address (IP and port) of the connection request. ```rust pub fn remote(&self) -> SocketAddr ``` -------------------------------- ### Configure SRT Socket with Options Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/mod.rs.html Create an `SrtSocketBuilder` pre-configured with specific socket options. This allows for setting advanced parameters before building the socket. ```rust pub fn with(options: O) -> SrtSocketBuilder where SocketOptions: OptionsOf, O: Validation, { Self::builder().with(options) } ``` -------------------------------- ### Get total microseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_micros` to retrieve the total number of whole microseconds from a Duration. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_micros(), 5_730_023); ``` -------------------------------- ### Any Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Provides runtime type information for `PacketPeriod`. ```APIDOC ### impl Any for T where T: 'static + ?Sized, Source§ #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more Source ``` -------------------------------- ### Get total milliseconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_millis` to retrieve the total number of whole milliseconds from a Duration. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_millis(), 5_730); ``` -------------------------------- ### AcceptParameters::new Source: https://docs.rs/srt-tokio/latest/srt_tokio/access/struct.AcceptParameters.html Creates a new instance of AcceptParameters with default values. ```APIDOC ## AcceptParameters::new ### Description Creates a new instance of `AcceptParameters`. ### Method `new()` ### Returns A new `AcceptParameters` instance. ``` -------------------------------- ### Rust strip_suffix Examples Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Shows using `strip_suffix` to remove a suffix exactly once if it matches, returning the remainder or None. ```rust assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar")); assert_eq!("bar:foo".strip_suffix("bar"), None); assert_eq!("foofoo".strip_suffix("foo"), Some("foo")); ``` -------------------------------- ### starts_with() Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Checks if the string slice starts with a given pattern. The pattern can be a `&str`, `char`, a slice of `char`s, or a closure. ```APIDOC ## starts_with() ### Description Returns `true` if the given pattern matches a prefix of this string slice. Returns `false` if it does not. The pattern can be a `&str`, in which case this function will return true if the `&str` is a prefix of this string slice. The pattern can also be a `char`, a slice of `char`s, or a function or closure that determines if a character matches. ### Method `starts_with

(&self, pat: P) -> bool where P: Pattern` ### Examples ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` ``` -------------------------------- ### From Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.SocketAddress.html Creates an instance of the type from another type. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. ### Method `from` ### Parameters - `t` (T) - The value to convert from. ### Returns The converted value. ``` -------------------------------- ### SrtListener Builder Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtListener.html Creates a new SrtListenerBuilder to configure and create an SrtListener. This is the entry point for creating a listener. ```rust pub fn builder() -> SrtListenerBuilder ``` -------------------------------- ### SRT Tokio Socket Builder Listen Method Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/builder.rs.html Initiates an SRT socket to listen for incoming connections. It uses the `ListenerOptions` to configure the socket and binds it. ```rust pub async fn listen(self) -> Result { Self::bind( ListenerOptions { socket: self.0 }.try_validate()?.into(), self.1, ) .await } ``` -------------------------------- ### Rust trim_right Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Shows how to remove trailing whitespace from a string slice using `trim_right`. Note: This method is deprecated. ```rust let s = " Hello\tworld\t"; assert_eq!(" Hello\tworld", s.trim_right()); ``` -------------------------------- ### Create ListenerOptions with Local Address and Socket Options Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.ListenerOptions.html Creates a new ListenerOptions instance with a local socket address and custom socket options. This allows for fine-grained control over the socket's behavior. ```rust pub fn with( local: impl TryInto, socket: SocketOptions, ) -> Result, OptionsError> ``` -------------------------------- ### Rust trim_left Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates removing leading whitespace from a string slice using `trim_left`. Note: This method is deprecated. ```rust let s = " Hello\tworld\t"; assert_eq!("Hello\tworld\t", s.trim_left()); ``` -------------------------------- ### ListenerOptions::with Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.ListenerOptions.html Creates a new ListenerOptions instance with specified local address and socket options. This allows for more granular control over socket configuration. ```APIDOC ## fn with ### Description Creates a new `ListenerOptions` instance with the specified local address and socket options. ### Signature ```rust pub fn with(local: impl TryInto, socket: SocketOptions) -> Result, OptionsError> ``` ### Parameters * `local`: An address that can be converted into a `SocketAddress`. * `socket`: The `SocketOptions` to configure the listener with. ``` -------------------------------- ### unsafe str as_bytes_mut Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates converting a mutable string slice to a mutable byte slice. This operation is unsafe. ```rust pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] ⓘ Converts a mutable string slice to a mutable byte slice. ``` -------------------------------- ### SocketOptions::new() Function Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.SocketOptions.html Creates a new instance of SocketOptions with default valid settings. ```rust pub fn new() -> Valid ``` -------------------------------- ### get Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Returns a subslice of `str` if the indices are valid and within bounds, otherwise returns `None`. This is a non-panicking alternative to indexing. ```APIDOC ## get ### Description Returns a subslice of `str`. This is the non-panicking alternative to indexing the `str`. Returns `None` whenever equivalent indexing operation would panic. ### Method `get(&self, i: I) -> Option<&>::Output>` where I: SliceIndex ### Examples ``` let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` ``` -------------------------------- ### Listen on a Specific Address with SRT Socket Builder Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/builder.rs.html Initiates the listening process for an SRT socket on a given local address. This method internally calls `local()` and then `listen().await`. ```rust pub async fn listen_on( self, local: impl TryInto, ) -> Result { self.local(local).listen().await } ``` -------------------------------- ### Get SRT Socket Settings Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/mod.rs.html Retrieve a reference to the `ConnectionSettings` of the SRT socket. This provides information about the current configuration of the connection. ```rust pub fn settings(&self) -> &ConnectionSettings { &self.settings } ``` -------------------------------- ### KeySize TryFrom Implementation Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.KeySize.html Allows converting a u16 value into a KeySize variant. This is useful for parsing external data or configuration where key sizes are represented as numbers. ```rust type Error = OptionsError; fn try_from(value: u16) -> Result ``` -------------------------------- ### Get Raw Pointer to String Slice Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Converts a string slice to a raw pointer to its first byte. The pointer must not be written to. ```rust let s = "Hello"; let ptr = s.as_ptr(); ``` -------------------------------- ### Get whole seconds from Duration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketPeriod.html Use `as_secs` to retrieve the number of whole seconds from a Duration. This method excludes the fractional part. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_secs(), 5); ``` -------------------------------- ### bind_with Source: https://docs.rs/srt-tokio/latest/src/srt_tokio/socket/call.rs.html Initiates and establishes an SRT connection from the caller's side. It takes a PacketSocket and CallerOptions, then enters a loop to manage the connection handshake by handling ticks and incoming packets. The function returns the PacketSocket and the established Connection upon successful connection, or an io::Error if the connection times out, is refused, or fails. ```APIDOC ## bind_with ### Description Initiates and establishes an SRT connection from the caller's side. It takes a PacketSocket and CallerOptions, then enters a loop to manage the connection handshake by handling ticks and incoming packets. The function returns the PacketSocket and the established Connection upon successful connection, or an io::Error if the connection times out, is refused, or fails. ### Function Signature `pub async fn bind_with(mut socket: PacketSocket, options: Valid) -> Result<(PacketSocket, Connection), io::Error>` ### Parameters #### `socket` - Type: `PacketSocket` - Description: The underlying packet socket used for sending and receiving SRT packets. #### `options` - Type: `Valid` - Description: Configuration options for the caller, including connection timeout, stream ID, and network settings. ### Returns - On success: `Ok((PacketSocket, Connection))` - Returns the modified PacketSocket and the established SRT Connection. - On failure: `Err(io::Error)` - Returns an error if the connection times out, is refused, or encounters any other failure during the handshake process. ### Usage Example ```rust // Assuming 'socket' is a initialized PacketSocket and 'caller_options' are valid CallerOptions match srt_tokio::socket::bind_with(socket, caller_options).await { Ok((new_socket, connection)) => { // Connection established successfully println!("SRT connection established."); } Err(e) => { // Handle connection error eprintln!("SRT connection failed: {}", e); } } ``` ``` -------------------------------- ### SrtSocket Settings Method Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocket.html Returns a reference to the connection settings of the SrtSocket. ```rust pub fn settings(&self) -> &ConnectionSettings ``` -------------------------------- ### KeySize Trait Implementations Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.KeySize.html Details the trait implementations for the KeySize enum, including Clone, Debug, Default, PartialEq, and TryFrom. ```APIDOC ## Trait Implementations for KeySize ### `Clone` Allows creating copies of KeySize values. ### `Debug` Enables debugging output for KeySize values. ### `Default` Provides a default value for KeySize, typically `KeySize::Unspecified`. ### `PartialEq` Allows comparison of KeySize values for equality. ### `TryFrom` Enables conversion from a `u16` value to a `KeySize` variant. Returns `OptionsError` on failure. ``` -------------------------------- ### Rust trim_right Directionality Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates `trim_right` behavior with different text directions, operating on the byte string's last position. ```rust let s = "English "; assert!(Some('h') == s.trim_right().chars().rev().next()); let s = "עברית "; assert!(Some('ת') == s.trim_right().chars().rev().next()); ``` -------------------------------- ### try_into Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/enum.SocketAddressParseError.html Performs the conversion. ```APIDOC ## fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ### Method fn ### Returns Result>::Error> - The result of the conversion. ``` -------------------------------- ### str floor_char_boundary Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Finds the closest character boundary not exceeding a given byte index, useful for truncating strings to valid UTF-8. ```rust let s = "❤️🧡💛💚💙💜"; assert_eq!(s.len(), 26); assert!(!s.is_char_boundary(13)); let closest = s.floor_char_boundary(13); assert_eq!(closest, 10); assert_eq!(&s[..closest], "❤️🧡"); ``` -------------------------------- ### chain Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocket.html Adapter for chaining two streams. Combines two streams into a single stream where the second stream starts after the first one completes. ```APIDOC ## fn chain(self, other: St) -> Chain ### Description Adapter for chaining two streams. Read more ### Method N/A (Method on Stream trait) ### Endpoint N/A ### Parameters - **other** (St) - Description: Another stream that implements the Stream trait. ### Request Example N/A ### Response #### Success Response - **Chain** - A new stream that yields items from `self` first, then from `other`. ``` -------------------------------- ### impl Comparable for Q Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.PacketRate.html Provides comparison functionality for PacketRate, allowing it to be ordered relative to other keys. ```APIDOC ## fn compare(&self, key: &K) -> Ordering ### Description Compare self to `key` and return their ordering. ### Method compare ### Parameters - **key** (K) - Description: The key to compare against. ``` -------------------------------- ### Chain two streams Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtSocket.html Use `chain` to combine two streams sequentially. The second stream will only start processing after the first one is exhausted. ```rust fn chain(self, other: St) -> Chain where St: Stream, Self: Sized, ``` -------------------------------- ### Safely Get Subslice with Bounds Checking Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Retrieves a subslice of a String, returning None if the indices are out of bounds or do not align with UTF-8 character boundaries. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### Cloning Connect Configuration Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.Connect.html Creates a duplicate of the existing Connect configuration. This is useful for modifying settings without affecting the original configuration. ```rust fn clone(&self) -> Connect ``` -------------------------------- ### Get Mutable Bytes from String Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Obtain a mutable byte slice from a String. The caller must ensure the bytes remain valid UTF-8. ```rust let mut s = String::from("Hello"); let bytes = unsafe { s.as_bytes_mut() }; assert_eq!(b"Hello", bytes); ``` -------------------------------- ### Get SrtListener Statistics Stream Source: https://docs.rs/srt-tokio/latest/srt_tokio/struct.SrtListener.html Returns a mutable reference to a stream that yields ListenerStatistics. This stream can be used to monitor the listener's performance. ```rust pub fn statistics( &mut self, ) -> &mut (impl Stream + Clone) ``` -------------------------------- ### Rust trim_left Directionality Example Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Illustrates `trim_left` behavior with different text directions, showing it operates on the byte string's first position. ```rust let s = " English"; assert!(Some('E') == s.trim_left().chars().next()); let s = " עברית"; assert!(Some('ע') == s.trim_left().chars().next()); ``` -------------------------------- ### Split String by String Slice Source: https://docs.rs/srt-tokio/latest/srt_tokio/options/struct.StreamId.html Demonstrates splitting a string into substrings using a string slice as a delimiter. ```rust let v: Vec<&str> = "lion::tiger::leopard".split("::").collect(); assert_eq!(v, ["lion", "tiger", "leopard"]); ```