### Get Default Gateway Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.get_default_gateway.html This example demonstrates how to call the get_default_gateway function and assert that the operation was successful. Ensure the natpmp crate is added as a dependency. ```rust use natpmp::* let r = get_default_gateway(); assert_eq!(r.is_ok(), true); ``` -------------------------------- ### Read Response or Retry Example Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.NatpmpAsync.html Illustrates reading a NAT-PMP response or retrying the operation. This method is useful after sending a request to get the result. ```rust use natpmp::* let mut n = new_tokio_natpmp().await?; n.send_public_address_request().await?; let response = n.read_response_or_retry().await?; ``` -------------------------------- ### Example Usage of NAT-PMP Error Source: https://docs.rs/natpmp/0.5.0/src/natpmp/error.rs.html Demonstrates how to use an instance of the `Error` enum and print its display representation. This example shows a common scenario of encountering a NAT-PMP error. ```rust let err = Error::NATPMP_ERR_CANNOTGETGATEWAY; println!("{}", err); ``` -------------------------------- ### Send Port Mapping Request Example Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.NatpmpAsync.html Shows how to send a port mapping request. Specify the protocol, private port, public port, and lifetime for the mapping. ```rust use natpmp::* let mut n = new_tokio_natpmp().await?; n.send_port_mapping_request(Protocol::UDP, 4020, 4020, 30).await?; ``` -------------------------------- ### NAT-PMP Library Usage Example Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html This snippet demonstrates a basic usage pattern within the natpmp library, likely involving error handling and successful completion. ```rust Err(_) => {} } Ok(()) } } ``` -------------------------------- ### NAT-PMP Port Mapping Example Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Demonstrates sending a UDP port mapping request and verifying the response. Ensure to allow sufficient time for the response after sending the request. ```rust use std::thread; use std::time::Duration; use natpmp::*; let mut n = Natpmp::new()?; n.send_port_mapping_request(Protocol::UDP, 4020, 4020, 30)?; thread::sleep(Duration::from_millis(100)); let response = n.read_response_or_retry()?; match response { Response::UDP(ur) => { assert_eq!(ur.private_port(), 4020); assert_eq!(ur.public_port(), 4020); } _ => panic!("Not a udp mapping response"), } ``` -------------------------------- ### Initialize NAT-PMP Client with Default Gateway Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Creates a new NAT-PMP client instance, automatically discovering the default gateway. This is a convenient way to start using the library. ```rust assert!(get_default_gateway().is_ok()); ``` -------------------------------- ### Send Public Address Request Example Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.NatpmpAsync.html Demonstrates how to send a public address request using NatpmpAsync. Ensure you have initialized the client with a new_tokio_natpmp(). ```rust use natpmp::* let mut n = new_tokio_natpmp().await?; n.send_public_address_request().await?; ``` -------------------------------- ### Create Natpmp with Default Gateway Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Initializes a new Natpmp object using the system's default gateway. This is a common starting point for NAT-PMP operations. ```rust use natpmp::*; let n = Natpmp::new(); assert_eq!(n.is_ok(), true); ``` -------------------------------- ### Example Usage of natpmp Error Enum Source: https://docs.rs/natpmp/0.5.0/natpmp/enum.Error.html Demonstrates how to create and print a NAT-PMP error variant. This is useful for debugging and error handling. ```rust use natpmp::* let err = Error::NATPMP_ERR_CANNOTGETGATEWAY; println!("{}", err); ``` -------------------------------- ### Create Tokio NAT-PMP Client Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.new_tokio_natpmp.html Use this function to create a new NAT-PMP client with Tokio. It handles the necessary setup for asynchronous UDP socket communication with the default gateway. Errors related to socket operations or connection failures may occur. ```rust use natpmp::* let n = new_tokio_natpmp().await?; ``` -------------------------------- ### Get a reference to the Ok value Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `as_ref()` to obtain a `Result<&T, &E>` from a `&Result`. This allows inspecting the contents of a Result without consuming it. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Collect Results with Checked Subtraction and Underflow Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Demonstrates using `collect()` with an iterator that may produce errors. This example checks for underflow during subtraction. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### Handling File Metadata with `and_then` Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Demonstrates chaining fallible operations like getting file metadata and then its modification time. If any step fails (e.g., file not found), the `Err` is propagated. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Get Epoch from MappingResponse Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Retrieves the seconds since the epoch for a NAT-PMP mapping. Note that this value may not be accurate. ```rust pub fn epoch(&self) -> u32 ``` -------------------------------- ### Unwrapping with `expect` and custom messages Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `expect` to get the contained Ok value, panicking with a custom message if the Result is Err. This is discouraged in favor of explicit error handling but useful for unrecoverable errors. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Create Tokio NAT-PMP Client Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.new_tokio_natpmp_with.html Initializes a NAT-PMP client using Tokio with a specified gateway IP address. Ensure the `natpmp` crate is added as a dependency and necessary imports are included. ```rust use natpmp::* let gateway = get_default_gateway().unwrap(); let n = new_tokio_natpmp_with(gateway).await?; ``` -------------------------------- ### Get TypeId for Any Trait Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Gets the `TypeId` of the current type. This is a blanket implementation for the Any trait. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Getting Value or Default with `unwrap_or` Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `unwrap_or` to get the `Ok` value or a provided default if `self` is `Err`. The `default` value is eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Basic Result Usage Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Demonstrates the basic usage of Result, showing how to create an Ok variant and unwrap its value. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Natpmp::get_natpmp_request_timeout Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Gets the timeout duration for the currently pending NAT-PMP request. ```APIDOC ## Natpmp::get_natpmp_request_timeout ### Description Get timeout duration of the currently pending NAT-PMP request. ### Errors: * `Error::NATPMP_ERR_NOPENDINGREQ` ### Examples ```rust use std::time::Duration; use natpmp::* let mut n = Natpmp::new()?; n.send_public_address_request()?; // do something let duration = n.get_natpmp_request_timeout()?; if duration <= Duration::from_millis(10) { // read response ... } ``` ``` -------------------------------- ### Natpmp::get_natpmp_request_timeout Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Gets the remaining timeout duration for the currently pending NAT-PMP request. ```APIDOC ## get_natpmp_request_timeout ### Description Gets the remaining timeout duration for the currently pending NAT-PMP request. Returns a duration of 0 if the timeout has already passed. ### Returns * `Result` - The remaining timeout duration, or an `Error` if no request is pending. ### Errors * `Error::NATPMP_ERR_NOPENDINGREQ` - If there is no pending NAT-PMP request. ### Examples ```rust use std::time::Duration; use natpmp::Natpmp; let mut n = Natpmp::new()?; n.send_public_address_request()?; let duration = n.get_natpmp_request_timeout()?; if duration <= Duration::from_millis(10) { // Handle timeout or read response } ``` ``` -------------------------------- ### Create Natpmp Client - natpmp Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Initializes a new NAT-PMP client instance using the default gateway. This is the primary way to interact with the NAT-PMP service. ```rust use natpmp::* let n = Natpmp::new(); assert_eq!(n.is_ok(), true); ``` -------------------------------- ### Get Lifetime from MappingResponse Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Retrieves the mapping lifetime as a Duration object for the NAT-PMP mapping. ```rust pub fn lifetime(&self) -> &Duration ``` -------------------------------- ### Natpmp::new_with Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Initializes a new Natpmp instance with a specified gateway IP address. It binds to a UDP socket, sets it to non-blocking mode, and connects to the gateway. ```APIDOC ## new_with ### Description Initializes a new Natpmp instance with a specified gateway IP address. It binds to a UDP socket, sets it to non-blocking mode, and connects to the gateway. ### Arguments * `gateway` - The IPv4 address of the NAT-PMP gateway. ### Returns * `Result` - An initialized `Natpmp` instance on success, or an `Error` on failure. ### Errors * `Error::NATPMP_ERR_SOCKETERROR` - If binding to the UDP socket fails. * `Error::NATPMP_ERR_FCNTLERROR` - If setting the socket to non-blocking mode fails. * `Error::NATPMP_ERR_CONNECTERR` - If connecting to the gateway fails. ### Examples ```rust use std::net::Ipv4Addr; use natpmp::Natpmp; let gateway = Ipv4Addr::new(192, 168, 0, 1); let n = Natpmp::new_with(gateway).unwrap(); ``` ``` -------------------------------- ### Get Public Port from MappingResponse Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Retrieves the public or external port number associated with the NAT-PMP mapping. ```rust pub fn public_port(&self) -> u16 ``` -------------------------------- ### new_tokio_natpmp_with Source: https://docs.rs/natpmp/0.5.0/natpmp/index.html Creates a new Tokio-based NAT-PMP client instance with a specified gateway. ```APIDOC ## new_tokio_natpmp_with ### Description Create a tokio NAT-PMP object with specified gateway. ### Function Signature `pub fn new_tokio_natpmp_with(gateway: Ipv4Addr) -> Result>` ### Parameters * `gateway`: The IPv4 address of the gateway. ``` -------------------------------- ### Get Private Port from MappingResponse Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Retrieves the private or internal port number associated with the NAT-PMP mapping. ```rust pub fn private_port(&self) -> u16 ``` -------------------------------- ### new_tokio_natpmp_with Source: https://docs.rs/natpmp/0.5.0/index.html Creates a new Tokio-based NAT-PMP client instance with a specified gateway. ```APIDOC ## new_tokio_natpmp_with ### Description Create a tokio NAT-PMP object with specified gateway. ### Function Signature `pub fn new_tokio_natpmp_with(gateway: Ipv4Addr) -> Result>` ``` -------------------------------- ### Get Gateway Public Address Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.GatewayResponse.html Retrieves the public/external IPv4 address of the gateway. This method is part of the GatewayResponse implementation. ```rust pub fn public_address(&self) -> &Ipv4Addr ``` -------------------------------- ### Initialize NAT-PMP Client with Specific Gateway Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Creates a NAT-PMP client instance configured to use a specific gateway IP address. Useful when the default gateway cannot be automatically determined. ```rust let addr = "192.168.0.1".parse().unwrap(); let n = Natpmp::new_with(addr)?; assert_eq!(*n.gateway(), addr); ``` -------------------------------- ### fn report(self) -> ExitCode Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Is called to get the representation of the value as status code. This status code is returned to the operating system. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Response - **ExitCode** - The exit code representation of the Result. ``` -------------------------------- ### Natpmp::new Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Creates a NAT-PMP object, attempting to automatically discover the default gateway. ```APIDOC ## Natpmp::new ### Description Create a NAT-PMP object with default gateway. ### Errors See `get_default_gateway` and `Natpmp::new_with`. ### Examples ```rust use natpmp::* let n = Natpmp::new(); assert_eq!(n.is_ok(), true); ``` ``` -------------------------------- ### Collect Results into a Vec with Checked Addition Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `collect()` to gather results from an iterator. This example demonstrates checking for overflow during addition. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### Initialize NAT-PMP Client with Gateway Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Creates a new NAT-PMP client instance, binding to a UDP socket and connecting to the specified gateway. Ensure the gateway IP address is valid. ```rust use std::str::FromStr; use std::net::Ipv4Addr; use natpmp::* let n = Natpmp::new_with("192.168.0.1".parse().unwrap()).unwrap(); ``` -------------------------------- ### Get NAT-PMP Gateway Address Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Retrieves the configured NAT-PMP gateway address from an existing Natpmp object. This can be used to confirm the gateway being used. ```rust use std::net::Ipv4Addr; use natpmp::*; let gateway = Ipv4Addr::from([192, 168, 0, 1]); let n = Natpmp::new_with(gateway)?; assert_eq!(n.gateway(), &gateway); ``` -------------------------------- ### new_natpmp_async_with Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.new_natpmp_async_with.html Creates a NAT-PMP object with an async UDP socket and the gateway IP address. ```APIDOC ## new_natpmp_async_with ### Description Create a NAT-PMP object with async udpsocket and gateway. ### Signature ```rust pub fn new_natpmp_async_with(s: S, gateway: Ipv4Addr) -> NatpmpAsync where S: AsyncUdpSocket, ``` ### Parameters * `s`: An asynchronous UDP socket implementing the `AsyncUdpSocket` trait. * `gateway`: The IPv4 address of the gateway. ``` -------------------------------- ### Natpmp::new_with Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Creates a NAT-PMP object with a specified gateway IP address. ```APIDOC ## Natpmp::new_with ### Description Create a NAT-PMP object with a specified gateway. ### Errors * `Error::NATPMP_ERR_SOCKETERROR` * `Error::NATPMP_ERR_FCNTLERROR` * `Error::NATPMP_ERR_CONNECTERR` ### Examples ```rust use std::str::FromStr; use std::net::Ipv4Addr; use natpmp::* let n = Natpmp::new_with("192.168.0.1".parse().unwrap()).unwrap(); ``` ``` -------------------------------- ### Get NAT-PMP Request Timeout Duration Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Calculates the remaining time until the next retry for a pending NAT-PMP request. Returns an error if no request is pending. ```rust use std::time::Duration; use natpmp::* # fn main() -> Result<()> { let mut n = Natpmp::new()?; n.send_public_address_request()?; // do something let duration = n.get_natpmp_request_timeout()?; if duration <= Duration::from_millis(10) { // read response ... } # Ok(()) # } ``` -------------------------------- ### Create Natpmp with Specified Gateway Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Initializes a new Natpmp object with a specific IPv4 address as the gateway. This is useful when the default gateway is not known or needs to be overridden. ```rust use std::str::FromStr; use std::net::Ipv4Addr; use natpmp::*; let n = Natpmp::new_with("192.168.0.1".parse().unwrap()).unwrap(); ``` -------------------------------- ### Get NAT-PMP Gateway Address Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Retrieves the NAT-PMP gateway's IP address from an existing client instance. This is useful for verifying the configured gateway. ```rust use std::net::Ipv4Addr; use natpmp::* # fn main() -> Result<()> { let gateway = Ipv4Addr::from([192, 168, 0, 1]); let n = Natpmp::new_with(gateway)?; assert_eq!(n.gateway(), &gateway); # Ok(()) # } ``` -------------------------------- ### Get NAT-PMP Request Timeout Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Retrieves the timeout duration for the currently pending NAT-PMP request. This is useful for implementing custom retry logic or timeouts. ```rust use std::time::Duration; use natpmp::*; let mut n = Natpmp::new()?; n.send_public_address_request()?; // do something let duration = n.get_natpmp_request_timeout()?; if duration <= Duration::from_millis(10) { // read response ... } ``` -------------------------------- ### Create Tokio NAT-PMP Object with Default Gateway Source: https://docs.rs/natpmp/0.5.0/src/natpmp/a_tokio.rs.html Creates a new NAT-PMP client instance using Tokio's `UdpSocket` and the system's default gateway. This function requires the `tokio` feature to be enabled. ```rust pub async fn new_tokio_natpmp() -> Result> { let gateway = get_default_gateway()?; new_tokio_natpmp_with(gateway).await } ``` -------------------------------- ### new_tokio_natpmp Source: https://docs.rs/natpmp/0.5.0/index.html Creates a new Tokio-based NAT-PMP client instance using the default gateway. ```APIDOC ## new_tokio_natpmp ### Description Create a tokio NAT-PMP object with default gateway. ### Function Signature `pub fn new_tokio_natpmp() -> Result>` ``` -------------------------------- ### Create Tokio NAT-PMP Object with Specified Gateway Source: https://docs.rs/natpmp/0.5.0/src/natpmp/a_tokio.rs.html Creates a new NAT-PMP client instance using Tokio's `UdpSocket` and a user-specified gateway IP address. This function requires the `tokio` feature to be enabled. ```rust pub async fn new_tokio_natpmp_with(gateway: Ipv4Addr) -> Result> { let s = UdpSocket::bind("0.0.0.0:0") .await .map_err(|_| Error::NATPMP_ERR_SOCKETERROR)?; let gateway_sockaddr = SocketAddrV4::new(gateway, NATPMP_PORT); if s.connect(gateway_sockaddr).await.is_err() { return Err(Error::NATPMP_ERR_CONNECTERR); } let n = new_natpmp_async_with(s, gateway); Ok(n) } ``` -------------------------------- ### Unchecked Unwrap of Err Value Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `unwrap_err_unchecked` to get the `Err` value without checking if it's an `Ok`. This is unsafe and results in undefined behavior if called on an `Ok`. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### into_ok Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained Ok value, never panics. This is an experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for, making it a maintainability safeguard. ### Method Signature `pub const fn into_ok(self) -> T where E: Into` ### Stability This is a nightly-only experimental API. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Unchecked Unwrap of Ok Value Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `unwrap_unchecked` to get the `Ok` value without checking if it's an `Err`. This is unsafe and results in undefined behavior if called on an `Err`. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` -------------------------------- ### Get a mutable reference to the value Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `as_mut()` to obtain a `Result<&mut T, &mut E>` from a `&mut Result`. This enables in-place modification of the contained value. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### new_tokio_natpmp_with Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.new_tokio_natpmp_with.html Creates a tokio NAT-PMP object with the specified gateway. This function returns a `Result` which can be `Error::NATPMP_ERR_SOCKETERROR` or `Error::NATPMP_ERR_CONNECTERR` on failure. ```APIDOC ## Function new_tokio_natpmp_with ```rust pub async fn new_tokio_natpmp_with( gateway: Ipv4Addr, ) -> Result> ``` ### Description Create a tokio NAT-PMP object with specified gateway. ### Errors * `Error::NATPMP_ERR_SOCKETERROR` * `Error::NATPMP_ERR_CONNECTERR` ### Examples ```rust use natpmp::*; let gateway = get_default_gateway().unwrap(); let n = new_tokio_natpmp_with(gateway).await?; ``` ``` -------------------------------- ### Implement AsyncUdpSocket for Tokio UdpSocket Source: https://docs.rs/natpmp/0.5.0/src/natpmp/a_tokio.rs.html This implementation allows the `natpmp` crate to use Tokio's `UdpSocket` for asynchronous operations. Ensure Tokio is enabled via feature flags. ```rust use std::io; use std::net::{Ipv4Addr, SocketAddrV4}; use async_trait::async_trait; use tokio::net::UdpSocket; use crate::asynchronous::{new_natpmp_async_with, AsyncUdpSocket, NatpmpAsync}; use crate::{get_default_gateway, Error, Result, NATPMP_PORT}; #[async_trait] impl AsyncUdpSocket for UdpSocket { async fn connect(&self, addr: &str) -> io::Result<()> { self.connect(addr).await } async fn send(&self, buf: &[u8]) -> io::Result { self.send(buf).await } async fn recv(&self, buf: &mut [u8]) -> io::Result { self.recv(buf).await } } ``` -------------------------------- ### fn from_output(output: as Try>::Output) -> Result Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Constructs the type from its `Output` type. ```APIDOC ## fn from_output(output: as Try>::Output) -> Result ### Description Constructs the type from its `Output` type. ### Parameters #### Path Parameters - **output** ( as Try>::Output) - Required - The output value to construct the Result from. ### Response - **Result** - The constructed Result type. ``` -------------------------------- ### Prepare NAT-PMP Request Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Prepares a NAT-PMP request by populating a buffer with protocol, port, and lifetime information. This function is used internally before sending a request to the NAT-PMP gateway. ```rust ) -> Result<()> { self.pending_request[0] = 0; self.pending_request[1] = match protocol { Protocol::UDP => 1, _ => 2, }; self.pending_request[2] = 0; // reserved self.pending_request[3] = 0; // reserved // private port self.pending_request[4] = (private_port >> 8 & 0xff) as u8; self.pending_request[5] = (private_port & 0xff) as u8; // public port self.pending_request[6] = (public_port >> 8 & 0xff) as u8; self.pending_request[7] = (public_port & 0xff) as u8; // lifetime self.pending_request[8] = ((lifetime >> 24) & 0xff) as u8; self.pending_request[9] = ((lifetime >> 16) & 0xff) as u8; self.pending_request[10] = ((lifetime >> 8) & 0xff) as u8; self.pending_request[11] = (lifetime & 0xff) as u8; self.pending_request_len = 12; self.send_natpmp_request() } ``` -------------------------------- ### Lazy Default Value with `unwrap_or_else` Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `unwrap_or_else` to get the `Ok` value or compute a default value using a closure `op` if `self` is `Err`. This is efficient for expensive default computations. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### new_tokio_natpmp Source: https://docs.rs/natpmp/0.5.0/natpmp/fn.new_tokio_natpmp.html Creates a tokio NAT-PMP object with the default gateway. This function is asynchronous and returns a Result containing the NatpmpAsync object or an error. ```APIDOC ## new_tokio_natpmp ### Description Creates a tokio NAT-PMP object with default gateway. ### Signature ```rust pub async fn new_tokio_natpmp() -> Result> ``` ### Errors - `Error::NATPMP_ERR_SOCKETERROR` - `Error::NATPMP_ERR_CONNECTERR` ### Example ```rust use natpmp::new_tokio_natpmp; let n = new_tokio_natpmp().await?; ``` ``` -------------------------------- ### ok() Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Converts `Result` to `Option`, consuming the Result and discarding the error if any. ```APIDOC ## pub fn ok(self) -> Option ### Description Converts `self` into an `Option`, consuming `self`, and discarding the error, if any. ### Method `ok()` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ### Response #### Success Response - `Option`: Contains the `T` value if the Result was `Ok`, otherwise `None`. ``` -------------------------------- ### fn product(iter: I) -> Result Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Takes each element in the Iterator. If it is an Err, no further elements are taken, and the Err is returned. Should no Err occur, the product of all elements is returned. ```APIDOC ## fn product(iter: I) -> Result ### Description Takes each element in the `Iterator`: if it is an `Err`, no further elements are taken, and the `Err` is returned. Should no `Err` occur, the product of all elements is returned. ### Parameters #### Path Parameters - **iter** (Iterator>) - Required - The iterator to process. ### Response - **Result** - The product of the elements if successful, or the first encountered error. ### Examples ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` ``` -------------------------------- ### AsyncUdpSocket connect method Source: https://docs.rs/natpmp/0.5.0/natpmp/trait.AsyncUdpSocket.html Asynchronously connects the UDP socket to a specified address. This is a required method for the AsyncUdpSocket trait. ```rust fn connect<'life0, 'life1, 'async_trait>( &'life0 self, addr: &'life1 str, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, ``` -------------------------------- ### Clone to Uninit (Nightly) Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.MappingResponse.html Performs copy-assignment from self to a mutable pointer to uninitialized memory. This is an experimental, nightly-only API. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Handle Port Mapping Errors Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Demonstrates sending a port mapping request and then attempting to send another with conflicting parameters, expecting an error response. ```rust let mut n: Natpmp = Natpmp::new()?; n.send_port_mapping_request(Protocol::UDP, 14020, 14020, 30)?; thread::sleep(Duration::from_millis(250)); n.read_response_or_retry()?; n.send_port_mapping_request(Protocol::UDP, 14021, 14020, 10)?; thread::sleep(Duration::from_millis(250)); match n.read_response_or_retry() { Ok(Response::UDP(ur)) => { assert_ne!(ur.public_port(), 14020); } Ok(_) => panic!("Not a udp mapping response!"), ``` -------------------------------- ### Result Methods for References Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Provides methods for `Result<&T, E>` and `Result<&mut T, E>` to copy or clone the contained value if it's a success. ```APIDOC ## Result Methods for References ### `impl Result<&T, E>` #### `pub const fn copied(self) -> Result` where T: Copy Maps a `Result<&T, E>` to a `Result` by copying the contents of the `Ok` part. ##### Examples ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `pub fn cloned(self) -> Result` where T: Clone Maps a `Result<&T, E>` to a `Result` by cloning the contents of the `Ok` part. ##### Examples ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ### `impl Result<&mut T, E>` #### `pub const fn copied(self) -> Result` where T: Copy Maps a `Result<&mut T, E>` to a `Result` by copying the contents of the `Ok` part. ##### Examples ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` #### `pub fn cloned(self) -> Result` where T: Clone Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the `Ok` part. ##### Examples ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ``` -------------------------------- ### Send Port Mapping Request Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Submits a NAT-PMP request to create a port mapping. Specify the protocol, private port, desired public port, and lease duration. Errors are returned if the request cannot be sent. ```rust use natpmp::* # fn main() -> Result<()> { let mut n = Natpmp::new()?; n.send_port_mapping_request(Protocol::UDP, 4020, 4020, 30)?; // do something then read response # Ok(()) # } ``` -------------------------------- ### Convert Result to Iterator (Ok Case) Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Shows how `into_iter()` on an `Ok` variant yields a single-element iterator containing the value. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); ``` -------------------------------- ### Basic Result Predicate Methods Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Methods to check if a `Result` is `Ok` or `Err`, and to check if it's `Ok` and satisfies a predicate. ```APIDOC ## Basic Result Predicate Methods ### `impl Result` #### `pub const fn is_ok(&self) -> bool` Returns `true` if the result is `Ok`. ##### Examples ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` #### `pub fn is_ok_and(self, f: F) -> bool` where F: FnOnce(T) -> bool Returns `true` if the result is `Ok` and the value inside of it matches a predicate. ##### Examples ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` #### `pub const fn is_err(&self) -> bool` Returns `true` if the result is `Err`. ##### Examples ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` #### `pub fn is_err_and(self, f: F) -> bool` where F: FnOnce(E) -> bool Returns `true` if the result is `Err` and the value inside of it matches a predicate. ``` -------------------------------- ### as_ref() Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Converts `&Result` to `Result<&T, &E>`, producing a new Result with references. ```APIDOC ## pub const fn as_ref(&self) -> Result<&T, &E> ### Description Produces a new `Result`, containing a reference into the original, leaving the original in place. ### Method `as_ref()` ### Parameters None ### Request Example ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` ### Response #### Success Response - `Result<&T, &E>`: A new Result containing references to the original `T` or `E` value. ``` -------------------------------- ### unwrap_or_default Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained Ok value or a default value if the Result is Err. ```APIDOC ## unwrap_or_default ### Description Consumes the `self` argument then, if `Ok`, returns the contained value, otherwise if `Err`, returns the default value for that type. ### Method Signature `pub fn unwrap_or_default(self) -> T where T: Default` ### Examples ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` ``` -------------------------------- ### unwrap Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`. ```APIDOC ## unwrap ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. Panics are meant for unrecoverable errors, and may abort the entire program. Instead, prefer to use the `?` (try) operator, or pattern matching to handle the `Err` case explicitly, or call `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default`. ### Method `unwrap(self) -> T` where `E: Debug` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### pub fn unwrap_or_else(self, op: F) -> T Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained `Ok` value or computes it from a closure. ```APIDOC ## pub fn unwrap_or_else(self, op: F) -> T where F: FnOnce(E) -> T, Returns the contained `Ok` value or computes it from a closure. ### Example ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` ``` -------------------------------- ### Convert Result Ok value to Option Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html The `ok()` method converts a `Result` into an `Option`, consuming the original Result. If the Result was `Ok`, it returns `Some(T)`; otherwise, it returns `None`. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### pub fn unwrap_or(self, default: T) -> T Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained `Ok` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated. ```APIDOC ## pub fn unwrap_or(self, default: T) -> T Returns the contained `Ok` value or a provided default. Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing the result of a function call, it is recommended to use `unwrap_or_else`, which is lazily evaluated. ### Example ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` ``` -------------------------------- ### Send Public Address Request Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Initiates a NAT-PMP request to obtain the public IP address. This function prepares the request and sends it, returning an error if the send operation fails. ```rust use natpmp::* # fn main() -> Result<()> { let mut n = Natpmp::new()?; n.send_public_address_request()?; // do something then read response # Ok(()) # } ``` -------------------------------- ### expect Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`. ```APIDOC ## expect ### Description Returns the contained `Ok` value, consuming the `self` value. Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the `Err` case explicitly, or call `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default`. ### Method `expect(self, msg: &str) -> T` where `E: Debug` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Providing a Default Value with `or` Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Use `or` to return the `Ok` value of `self` if it's `Ok`, otherwise return the `Ok` value from the provided `res`ult. Note that `res` is eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### GatewayResponse Methods Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.GatewayResponse.html Methods available on the GatewayResponse struct. ```APIDOC ## GatewayResponse Gateway response. ### Methods #### `public_address(&self) -> &Ipv4Addr` Gateway public/external address. #### `epoch(&self) -> u32` Seconds since epoch. **Note: May be not accurate.** ``` -------------------------------- ### Chaining Fallible Operations Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Demonstrates how `Result` can be used to chain operations that might fail, propagating errors. ```APIDOC ## Chaining Fallible Operations This example shows how to chain operations that return a `Result`. If any operation in the chain returns an `Err`, that error is propagated. ### Example ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } assert_eq!(Ok(2).and_then(sq_then_to_string), Ok("4".to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` Often used to chain fallible operations that may return `Err`. ### Example with File Metadata ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` ``` -------------------------------- ### Send Public Address Request and Read Response Source: https://docs.rs/natpmp/0.5.0/src/natpmp/lib.rs.html Initiates a request for the public IP address and then reads the response, retrying if necessary. Includes a delay to allow the network device to respond. ```rust use std::thread; use std::time::Duration; use natpmp::* # fn main() -> Result<()> { let mut n = Natpmp::new()?; n.send_public_address_request()?; thread::sleep(Duration::from_millis(250)); let response = n.read_response_or_retry()?; # Ok(()) # } ``` -------------------------------- ### Read NAT-PMP Response or Retry Source: https://docs.rs/natpmp/0.5.0/natpmp/struct.Natpmp.html Attempts to read a NAT-PMP response. If no response is immediately available, it may return `Error::NATPMP_TRYAGAIN`, indicating that the operation should be retried later. ```rust use std::thread; use std::time::Duration; use natpmp::*; let mut n = Natpmp::new()?; n.send_public_address_request()?; thread::sleep(Duration::from_millis(250)); let response = n.read_response_or_retry()?; ``` -------------------------------- ### Expect Err with Custom Message Source: https://docs.rs/natpmp/0.5.0/natpmp/type.Result.html Demonstrates using expect_err, which panics with a custom message if the Result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ```