### Initialize and run a DHCP server Source: https://docs.rs/dhcplease/0.2.1/dhcplease/index.html Demonstrates the basic setup for a DHCP server using a configuration file and the Tokio runtime. ```rust use dhcplease::{Config, DhcpServer}; #[tokio::main] async fn main() -> dhcplease::Result<()> { let config = Config::load_or_create("config.json").await?; let server = DhcpServer::new(config).await?; server.run().await } ``` -------------------------------- ### DhcpServer::run Source: https://docs.rs/dhcplease/0.2.1/dhcplease/index.html Starts the DHCP server to listen for incoming requests on UDP port 67. ```APIDOC ## DhcpServer::run() ### Description Starts the main server loop, listening for DHCP packets on UDP port 67. ### Signature `pub async fn run(self) -> Result<()>` ``` -------------------------------- ### Initialize and run a DHCP server Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/struct.DhcpServer.html Demonstrates creating a new server instance, setting up a graceful shutdown trigger using ctrl+c, and starting the server loop. ```rust use dhcplease::{Config, DhcpServer}; #[tokio::main] async fn main() -> dhcplease::Result<()> { let config = Config::load_or_create("config.json").await?; let server = DhcpServer::new(config).await?; // Shutdown on ctrl+c let shutdown_handle = server.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.ok(); shutdown_handle.shutdown().await; }); server.run().await } ``` ```rust use dhcplease::{Config, DhcpServer}; #[tokio::main] async fn main() -> dhcplease::Result<()> { let config = Config::load_or_create("config.json").await?; let server = DhcpServer::new(config).await?; // Shutdown after ctrl+c let server_handle = server.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.ok(); server_handle.shutdown().await; }); server.run().await } ``` -------------------------------- ### Cloning Result Contents Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Examples of cloning the contents of a Result containing a reference. ```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)); ``` ```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)); ``` -------------------------------- ### DhcpServer::run Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/struct.DhcpServer.html Starts the DHCP server loop to process incoming packets until a shutdown is requested. ```APIDOC ## pub async fn run(&self) -> Result<()> ### Description Runs the DHCP server, processing packets until shutdown is requested. This method spawns a new async task for each received packet. ``` -------------------------------- ### Define DHCP Server Configuration Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/index.html Example JSON structure for configuring server IP, subnet, address pools, and lease settings. ```json { "server_ip": "192.168.1.1", "subnet_mask": "255.255.255.0", "pool_start": "192.168.1.100", "pool_end": "192.168.1.200", "gateway": "192.168.1.1", "dns_servers": ["8.8.8.8"], "lease_duration_seconds": 86400, "leases_file": "leases.json" } ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Examples of copying the contents of a Result containing a reference. ```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)); ``` ```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)); ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Examples of flattening nested Result types. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Transposing Result and Option Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Example of transposing a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Examples of checking if a Result is Ok or Err. ```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); ``` ```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); ``` -------------------------------- ### Validating Result with Predicate Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Example of using is_ok_and to validate the value inside a Result. ```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); ``` -------------------------------- ### Get Remaining Lease Time Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Lease.html Calculates the remaining seconds until the lease expires, returning 0 if it has already expired. ```rust pub fn remaining_seconds(&self) -> i64 ``` -------------------------------- ### Initialize and Allocate IP with Leases Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Leases.html Demonstrates creating a new Leases instance from a configuration and allocating an IP address for a specific client ID. ```rust use std::sync::Arc; use dhcplease::{Config, Leases}; let config = Arc::new(Config::default()); let leases = Leases::new(config).await?; let client_id = vec![1, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]; let ip = leases.allocate_ip(&client_id).await?; ``` -------------------------------- ### DhcpServer::new Source: https://docs.rs/dhcplease/0.2.1/dhcplease/index.html Initializes a new DHCP server instance using the provided configuration. ```APIDOC ## DhcpServer::new(config: Config) ### Description Creates a new instance of the DHCP server using the provided configuration object. ### Signature `pub async fn new(config: Config) -> Result` ### Parameters - **config** (Config) - Required - The server configuration including IP pool, lease duration, and DNS settings. ``` -------------------------------- ### load_or_create Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Loads configuration from a file, or creates a default config if it doesn't exist. ```APIDOC ## pub async fn load_or_create>(path: P) -> Result ### Description Loads configuration from a file, or creates a default config if it doesn't exist. ### Arguments - **path** (P) - Path to the JSON configuration file ### Errors Returns an error if the file exists but cannot be read or parsed, the configuration fails validation, or a new default config cannot be written. ``` -------------------------------- ### save Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Saves the configuration to a JSON file with pretty-printing. ```APIDOC ## pub async fn save>(&self, path: P) -> Result<()> ### Description Saves the configuration to a JSON file. The file is written with pretty-printing for human readability. ``` -------------------------------- ### Lease Constructor Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Lease.html Creates a new lease instance, initializing timestamps based on the current time and the provided duration. ```rust pub fn new( ip_address: Ipv4Addr, client_id: String, duration_seconds: u32, ) -> Self ``` -------------------------------- ### Define DHCP server configuration Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html The Config struct contains fields for network parameters, IP allocation ranges, and lease management settings. ```rust pub struct Config {Show 15 fields pub server_ip: Ipv4Addr, pub subnet_mask: Ipv4Addr, pub pool_start: Ipv4Addr, pub pool_end: Ipv4Addr, pub gateway: Option, pub dns_servers: Vec, pub domain_name: Option, pub lease_duration_seconds: u32, pub renewal_time_seconds: Option, pub rebinding_time_seconds: Option, pub broadcast_address: Option, pub mtu: Option, pub static_bindings: Vec, pub leases_file: String, pub interface_index: Option, } ``` -------------------------------- ### Define BOOTREPLY constant Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/constant.BOOTREPLY.html Represents the BOOTP/DHCP operation code for server replies. ```rust pub const BOOTREPLY: u8 = 2; ``` -------------------------------- ### DhcpPacket Factory Methods Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/struct.DhcpPacket.html Methods for creating reply packets based on existing requests. ```APIDOC ## pub fn create_reply(request: &DhcpPacket, message_type: MessageType, your_ip: Ipv4Addr, server_ip: Ipv4Addr, options: Vec) -> Self Creates a DHCP reply packet (OFFER, ACK, or NAK) from a request, automatically copying transaction fields and adding the message type option. ## pub fn create_bootp_reply(request: &DhcpPacket, your_ip: Ipv4Addr, server_ip: Ipv4Addr, options: Vec) -> Self Creates a legacy BOOTP reply packet without the DHCP message type option. ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Demonstrates using the product method on an iterator of Results, which short-circuits on the first Err encountered. ```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()); ``` -------------------------------- ### StaticBinding Struct Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.StaticBinding.html The structure definition for a static MAC-to-IP binding. ```rust pub struct StaticBinding { pub mac_address: String, pub ip_address: Ipv4Addr, pub hostname: Option, } ``` -------------------------------- ### Fallback to alternative Result with or Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the current Result if it is Ok, otherwise returns the provided alternative Result. ```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)); ``` -------------------------------- ### validate Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Validates the configuration for correctness. ```APIDOC ## pub fn validate(&self) -> Result<()> ### Description Validates the configuration for correctness, checking pool ranges, IP conflicts, subnet masks, and static bindings. ### Errors Returns Error::InvalidConfig with a description of the first validation failure encountered. ``` -------------------------------- ### DhcpServer::save_leases Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/struct.DhcpServer.html Persists the current lease state to disk. ```APIDOC ## pub async fn save_leases(&self) -> Result<()> ### Description Saves all leases to disk immediately. Call this before shutting down to ensure lease state is persisted. ``` -------------------------------- ### Convert Result to References Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Creates a new Result containing references to the original values. ```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")); ``` ```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); ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the contained Ok value or a provided default value if the result is Err. ```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); ``` -------------------------------- ### encode() Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.DhcpOption.html Encodes the DHCP option into its wire format. ```APIDOC ## pub fn encode(&self) -> Vec ### Description Encodes the option to its wire format (code + length + data). The returned bytes can be directly appended to a DHCP packet’s options section. ### Returns - **Vec** - The encoded byte representation of the option. ``` -------------------------------- ### pub fn normalize_mac(mac: &str) -> String Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/fn.normalize_mac.html Normalizes a given MAC address string to a lowercase colon-separated format (e.g., 'aa:bb:cc:dd:ee:ff'). ```APIDOC ## Function: normalize_mac ### Description Normalizes a MAC address string to lowercase colon-separated format. It converts formats like "AA-BB-CC-DD-EE-FF" to "aa:bb:cc:dd:ee:ff". ### Signature `pub fn normalize_mac(mac: &str) -> String` ### Parameters - **mac** (&str) - The input MAC address string to be normalized. ### Returns - **String** - The normalized MAC address in lowercase colon-separated format. ``` -------------------------------- ### Into Ok Value Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Extracts the Ok value without risk of panicking, useful for infallible Result types. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### pub fn sanitize_hostname(hostname: &str) -> String Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/fn.sanitize_hostname.html Sanitizes a hostname string by retaining only ASCII alphanumeric characters, hyphens, and dots, and truncating the result to a maximum of 255 characters. ```APIDOC ## sanitize_hostname ### Description Sanitizes a hostname by removing invalid characters. Keeps only ASCII alphanumeric characters, hyphens, and dots. Truncates to 255 characters maximum per RFC 1035. ### Signature `pub fn sanitize_hostname(hostname: &str) -> String` ### Parameters - **hostname** (&str) - The input hostname string to be sanitized. ### Returns - **String** - The sanitized hostname. ``` -------------------------------- ### LeaseStore Struct Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.LeaseStore.html The primary structure for storing DHCP lease data, containing maps for leases, IP assignments, and declined IPs. ```rust pub struct LeaseStore { pub leases: HashMap, pub ip_to_client: HashMap, pub declined_ips: HashMap>, } ``` -------------------------------- ### Inspect Result Ok Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Executes a closure with a reference to the Ok value without modifying the result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("failed to parse number"); ``` -------------------------------- ### Expect Result Value Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the Ok value or panics with a provided message if the result is Err. ```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`"); ``` -------------------------------- ### parse(code, data) Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.DhcpOption.html Parses a DHCP option from its code and raw data bytes. ```APIDOC ## pub fn parse(code: u8, data: &[u8]) -> Result ### Description Parses a DHCP option from its code and raw data. ### Parameters - **code** (u8) - The option code (first byte of TLV). - **data** (&[u8]) - The option data (after code and length bytes). ### Errors Returns `Error::InvalidPacket` if the data length is invalid for the option type. ``` -------------------------------- ### option_code() Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.DhcpOption.html Returns the RFC 2132 option code for the current DHCP option. ```APIDOC ## pub fn option_code(&self) -> u8 ### Description Returns the RFC 2132 option code for this option. ### Returns - **u8** - The option code. ``` -------------------------------- ### Collect Result from Iterator Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Demonstrates how collecting an iterator of Results short-circuits on the first Err encountered. ```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])); ``` ```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!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Leases Struct Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Leases.html The internal structure definition for the Leases manager. ```rust pub struct Leases { /* private fields */ } ``` -------------------------------- ### Lease Struct Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Lease.html The primary data structure representing an active DHCP lease with fields for IP, client ID, hostname, and timing metadata. ```rust pub struct Lease { pub ip_address: Ipv4Addr, pub client_id: String, pub hostname: Option, pub expires_at: DateTime, pub created_at: DateTime, pub last_seen: DateTime, } ``` -------------------------------- ### Map Result to Default or Function Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Provides fallback mechanisms when mapping Result values. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### normalize_mac function signature Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/fn.normalize_mac.html The function signature for normalizing MAC address strings. ```rust pub fn normalize_mac(mac: &str) -> String ``` -------------------------------- ### And Operation on Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the provided result if the current result is Ok, otherwise returns the Err value. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### DhcpServer::shutdown Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/struct.DhcpServer.html Signals the server to perform a graceful shutdown. ```APIDOC ## pub async fn shutdown(&self) ### Description Signals the server to shut down gracefully. The server will finish processing the current packet, save leases to disk, and then the run method will return. ``` -------------------------------- ### Unwrap Result with Default Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the Ok value or the default value for the type if the result is an Err. ```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); ``` -------------------------------- ### And Then Operation on Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Calls a function if the result is Ok, allowing for chained control flow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### Map Result Values Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Applies a function to the Ok value of a Result. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### DhcpPacket Methods Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/struct.DhcpPacket.html Methods for parsing, encoding, and inspecting DHCP packet data. ```APIDOC ## pub fn parse(data: &[u8]) -> Result Parses a DHCP packet from raw bytes. Returns an error if the packet is malformed, has an invalid magic cookie, or violates relay loop protection. ## pub fn encode(&self) -> Vec Encodes the packet into a byte buffer for network transmission, including padding and TLV-formatted options. ## pub fn message_type(&self) -> Option Returns the DHCP message type (Option 53) if present. ## pub fn requested_ip(&self) -> Option Returns the requested IP address (Option 50) if present. ## pub fn server_identifier(&self) -> Option Returns the server identifier (Option 54) if present. ## pub fn client_identifier(&self) -> Option<&[u8]> Returns the client identifier (Option 61) if present. ## pub fn relay_agent_info(&self) -> Option<&[u8]> Returns the relay agent information (Option 82) if present. ## pub fn hostname(&self) -> Option<&str> Returns the client hostname (Option 12) if present. ## pub fn parameter_request_list(&self) -> Option<&[u8]> Returns the parameter request list (Option 55) if present. ## pub fn requested_lease_time(&self) -> Option Returns the requested lease time (Option 51) if present. ## pub fn chaddr_bytes(&self) -> &[u8] Returns the client hardware address bytes. ## pub fn format_mac(&self) -> String Formats the client hardware address as a colon-separated string. ## pub fn client_id(&self) -> Vec Returns a unique client identifier for lease tracking, using Option 61 or constructing one from hardware details. ## pub fn is_broadcast(&self) -> bool Returns true if the broadcast flag is set. ``` -------------------------------- ### sanitize_hostname function signature Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/fn.sanitize_hostname.html The function signature for sanitizing a hostname string. ```rust pub fn sanitize_hostname(hostname: &str) -> String ``` -------------------------------- ### Define HLEN_ETHERNET constant Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/constant.HLEN_ETHERNET.html Represents the hardware address length for Ethernet, which is 6 bytes. ```rust pub const HLEN_ETHERNET: u8 = 6; ``` -------------------------------- ### is_valid_mac Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Validates a MAC address string format. ```APIDOC ## pub fn is_valid_mac(mac: &str) -> bool ### Description Validates a MAC address string format. Accepts colon-separated (aa:bb:cc:dd:ee:ff) or hyphen-separated (aa-bb-cc-dd-ee-ff) formats, case-insensitive. ``` -------------------------------- ### Compute default value with unwrap_or_else Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the contained Ok value or computes a default value using a closure if the result is Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### BOOTREQUEST Constant Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/constant.BOOTREQUEST.html Defines the BOOTREQUEST constant as a u8 with a value of 1. ```rust pub const BOOTREQUEST: u8 = 1; ``` -------------------------------- ### sanitize_domain_name function signature Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/fn.sanitize_domain_name.html The function signature for sanitizing domain names in Rust. ```rust pub fn sanitize_domain_name(domain: &str) -> String ``` -------------------------------- ### DHCP_CLIENT_PORT Constant Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/constant.DHCP_CLIENT_PORT.html Represents the standard DHCP client port value of 68. ```rust pub const DHCP_CLIENT_PORT: u16 = 68; ``` -------------------------------- ### Define HTYPE_ETHERNET constant Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/constant.HTYPE_ETHERNET.html Represents the hardware type for Ethernet as a u8 value. ```rust pub const HTYPE_ETHERNET: u8 = 1; ``` -------------------------------- ### Unwrap Error from Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the Err value or panics if the result is an Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Calculate Sum of Result Iterator Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Demonstrates using the sum method on an iterator of Results, which returns an Err if any element is an Err. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### DhcpOption Enum Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.DhcpOption.html The structure of the DhcpOption enum, containing variants for various DHCP configuration options. ```rust pub enum DhcpOption { Show 18 variants SubnetMask(Ipv4Addr), Router(Vec), DnsServer(Vec), Hostname(String), DomainName(String), BroadcastAddress(Ipv4Addr), RequestedIpAddress(Ipv4Addr), LeaseTime(u32), OptionOverload(OverloadFlag), MessageType(MessageType), ServerIdentifier(Ipv4Addr), ParameterRequestList(Vec), RenewalTime(u32), RebindingTime(u32), ClientIdentifier(Vec), RelayAgentInfo(Vec), InterfaceMtu(u16), Unknown(u8, Vec), } ``` -------------------------------- ### calculate_broadcast Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Returns the broadcast address for the configured network. ```APIDOC ## pub fn calculate_broadcast(&self) -> Ipv4Addr ### Description Returns the broadcast address for the configured network. If broadcast_address is explicitly configured, returns that value; otherwise, calculates it from server_ip and subnet_mask. ``` -------------------------------- ### Convert Result to Option Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Converts a Result into an Option, discarding the error or success value respectively. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Expect Error from Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns the Err value or panics with a custom message if the result is an Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Lease Expiration Check Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Lease.html Checks if the current lease has passed its expiration time. ```rust pub fn is_expired(&self) -> bool ``` -------------------------------- ### Result Type Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html The core definition of the Result type alias. ```rust pub type Result = Result; ``` ```rust pub enum Result { Ok(T), Err(Error), } ``` -------------------------------- ### pool_size Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Returns the total number of addresses in the pool. ```APIDOC ## pub fn pool_size(&self) -> u32 ### Description Returns the total number of addresses in the pool. ``` -------------------------------- ### DHCP_SERVER_PORT Constant Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/server/constant.DHCP_SERVER_PORT.html Represents the standard DHCP server port value of 67. ```rust pub const DHCP_SERVER_PORT: u16 = 67; ``` -------------------------------- ### DhcpPacket Struct Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/packet/struct.DhcpPacket.html The structure definition for a parsed DHCP packet, containing header fields and a vector of DHCP options. ```rust pub struct DhcpPacket {Show 15 fields pub op: u8, pub htype: u8, pub hlen: u8, pub hops: u8, pub xid: u32, pub secs: u16, pub flags: u16, pub ciaddr: Ipv4Addr, pub yiaddr: Ipv4Addr, pub siaddr: Ipv4Addr, pub giaddr: Ipv4Addr, pub chaddr: [u8; 16], pub sname: [u8; 64], pub file: [u8; 128], pub options: Vec, } ``` -------------------------------- ### OptionCode Enum Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.OptionCode.html The OptionCode enum uses a u8 representation for DHCP option codes. It includes common options like SubnetMask, Router, and LeaseTime. ```rust #[repr(u8)] pub enum OptionCode { Show 19 variants Pad = 0, SubnetMask = 1, Router = 3, DnsServer = 6, Hostname = 12, DomainName = 15, InterfaceMtu = 26, BroadcastAddress = 28, RequestedIpAddress = 50, LeaseTime = 51, OptionOverload = 52, MessageType = 53, ServerIdentifier = 54, ParameterRequestList = 55, RenewalTime = 58, RebindingTime = 59, ClientIdentifier = 61, RelayAgentInfo = 82, End = 255, } ``` -------------------------------- ### Unwrap Result Value Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Extracts the Ok value or panics if the result is an Err. Discouraged in favor of pattern matching or the ? operator. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Check Result Error with Predicate Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Uses is_err_and to verify if a Result is an Err and satisfies a specific condition. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Chain fallible operations with and_then Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Chains operations that return a Result, propagating errors if they occur. ```rust 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")); ``` ```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); ``` -------------------------------- ### Convert Result to Iterator Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Converts a Result into an iterator that yields the contained value if Ok, or nothing if Err. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Iterate Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns an iterator over the contained value if the result is Ok. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Renew Lease Source: https://docs.rs/dhcplease/0.2.1/dhcplease/lease/struct.Lease.html Extends the lease duration, updating the expiration and last seen timestamps to the current time. ```rust pub fn renew(&mut self, duration_seconds: u32) ``` -------------------------------- ### Fallback to closure result with or_else Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Calls a closure to produce an alternative Result if the current one is Err. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### ip_in_pool Source: https://docs.rs/dhcplease/0.2.1/dhcplease/config/struct.Config.html Checks if an IP address is within the configured pool range. ```APIDOC ## pub fn ip_in_pool(&self, ip: Ipv4Addr) -> bool ### Description Checks if an IP address is within the configured pool range. Returns true if pool_start <= ip <= pool_end. ``` -------------------------------- ### Unwrap Result Unchecked Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Accesses the Ok value without checking for Err. Calling this on an Err variant results in undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Into Error Value Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Extracts the Err value without risk of panicking, useful for infallible Result types. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Error Enum Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/enum.Error.html The Error enum variants cover network, configuration, and protocol-level errors encountered by the DHCP server. ```rust pub enum Error { Io(Error), Json(Error), InvalidPacket(String), PoolExhausted, InvalidConfig(String), Socket(String), AddressOutOfRange(Ipv4Addr), LeaseNotFound(String), } ``` -------------------------------- ### Map Result Error Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Transforms the error variant of a Result while keeping the Ok variant unchanged. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Inspect Result Err Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Executes a closure with a reference to the Err value without modifying the result. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### Unwrap Err Unchecked Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Accesses the Err value without checking for Ok. Calling this on an Ok variant results in undefined behavior. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Iterate Mut Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Returns a mutable iterator over the contained value if the result is Ok. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### OverloadFlag Enum Definition Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.OverloadFlag.html The definition of the OverloadFlag enum, which uses a u8 representation to map specific fields to option-carrying roles. ```rust #[repr(u8)] pub enum OverloadFlag { File = 1, Sname = 2, Both = 3, } ``` -------------------------------- ### Deref Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Converts a Result containing a dereferenceable type into a Result containing a reference to the target. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### Define MessageType Enum Source: https://docs.rs/dhcplease/0.2.1/dhcplease/options/enum.MessageType.html The MessageType enum uses a u8 representation to map DHCP message types to their corresponding protocol values. ```rust #[repr(u8)] pub enum MessageType { Discover = 1, Offer = 2, Request = 3, Decline = 4, Ack = 5, Nak = 6, Release = 7, Inform = 8, } ``` -------------------------------- ### Deref Mut Result Source: https://docs.rs/dhcplease/0.2.1/dhcplease/error/type.Result.html Converts a Result containing a mutable dereferenceable type into a Result containing a mutable reference to the target. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.