### Result::is_ok Implementation Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.EncodeResult.html Example of checking if a Result is Ok. ```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); ``` -------------------------------- ### Clone Result contents Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.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)); ``` -------------------------------- ### Copy Result contents Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.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)); ``` -------------------------------- ### Result::is_err Implementation Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.EncodeResult.html Example of checking if a Result is Err. ```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); ``` -------------------------------- ### Create and Insert RelayAgentInformation Source: https://docs.rs/dhcproto/latest/dhcproto/v4/relay/struct.RelayAgentInformation.html Demonstrates how to initialize a RelayAgentInformation instance, add sub-options, and insert it into a DHCP message. ```rust use dhcproto::v4::{self, relay::{RelayInfo, RelayAgentInformation}}; let mut info = RelayAgentInformation::default(); info.insert(RelayInfo::LinkSelection("1.2.3.4".parse().unwrap())); let mut msg = v4::Message::default(); msg.opts_mut() .insert(v4::DhcpOption::RelayAgentInformation(info)); ``` -------------------------------- ### Constructing DHCPv4 Messages Source: https://docs.rs/dhcproto/latest/dhcproto/v4/index.html Demonstrates how to initialize a DHCPv4 message, configure flags, set hardware addresses, and insert various DHCP options before encoding the message into a byte buffer. ```rust use dhcproto::{v4, Encodable, Encoder}; // arbitrary hardware addr let chaddr = vec![ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, ]; // construct a new Message let mut msg = v4::Message::default(); msg.set_flags(v4::Flags::default().set_broadcast()) // set broadcast to true .set_chaddr(&chaddr) // set chaddr .opts_mut() .insert(v4::DhcpOption::MessageType(v4::MessageType::Discover)); // set msg type // set some more options msg.opts_mut() .insert(v4::DhcpOption::ParameterRequestList(vec![ v4::OptionCode::SubnetMask, v4::OptionCode::Router, v4::OptionCode::DomainNameServer, v4::OptionCode::DomainName, ])); msg.opts_mut() .insert(v4::DhcpOption::ClientIdentifier(chaddr)); // now encode to bytes let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); msg.encode(&mut e)?; // buf now has the contents of the encoded DHCP message ``` -------------------------------- ### Prepend Label to Name Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Add a new label to the beginning of an existing domain name. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let name = Name::from_str("example.com").unwrap(); let name = name.prepend_label("www").unwrap(); assert_eq!(name, Name::from_str("www.example.com").unwrap()); ``` -------------------------------- ### Check for Root Label Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Verify if a domain name represents the DNS root. ```rust use hickory_proto::rr::domain::Name; let root = Name::root(); assert_eq!(&root.to_string(), "."); ``` -------------------------------- ### Constructing DHCPv6 messages Source: https://docs.rs/dhcproto/latest/dhcproto/v6/index.html Demonstrates how to create a new DHCPv6 message, set options like ClientId, and encode the message into a byte buffer. ```rust use dhcproto::{v6, Encodable, Encoder}; // arbitrary DUID let duid = vec![ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, ]; // construct a new Message with a random xid let mut msg = v6::Message::new(v6::MessageType::Solicit); // set an option msg.opts_mut() .insert(v6::DhcpOption::ClientId(duid)); // now encode to bytes let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); msg.encode(&mut e)?; // buf now has the contents of the encoded DHCP message ``` -------------------------------- ### Append Domain to Name Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Append a domain to a name and mark the result as an FQDN. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let local = Name::from_str("www").unwrap(); let domain = Name::from_str("example.com").unwrap(); let name = local.append_domain(&domain).unwrap(); assert_eq!(name, Name::from_str("www.example.com.").unwrap()); assert!(name.is_fqdn()) ``` -------------------------------- ### DhcpOptions Methods Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.DhcpOptions.html Methods available for interacting with the DhcpOptions collection. ```APIDOC ## DhcpOptions Methods ### new() Constructs an empty DhcpOptions instance. ### get(code: OptionCode) -> Option<&DhcpOption> Retrieves the first element matching the specified option code. ### get_all(code: OptionCode) -> Option<&[DhcpOption]> Retrieves all elements matching the specified option code. ### get_mut(code: OptionCode) -> Option<&mut DhcpOption> Retrieves a mutable reference to the first element matching the specified option code. ### get_mut_all(code: OptionCode) -> Option<&mut [DhcpOption]> Retrieves a mutable reference to all elements matching the specified option code. ### remove(code: OptionCode) -> Option Removes the first element with a matching option code. ### remove_all(code: OptionCode) -> Option + '_> Removes all elements with a matching option code. ### insert(opt: DhcpOption) Inserts a new option into the list. ### iter() -> impl Iterator Returns an iterator over the options. ### iter_mut() -> impl Iterator Returns a mutable iterator over the options. ``` -------------------------------- ### Append Label to Name Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Add a new label to the end of an existing domain name. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let name = Name::from_str("www.example").unwrap(); let name = name.append_label("com").unwrap(); assert_eq!(name, Name::from_str("www.example.com").unwrap()); ``` -------------------------------- ### DataSourceFlags::new Source: https://docs.rs/dhcproto/latest/dhcproto/v4/bulk_query/struct.DataSourceFlags.html Creates a new instance of DataSourceFlags from a raw byte value. ```APIDOC ## pub fn new(n: u8) -> Self ### Description Creates a new DataSourceFlags instance from a u8 value. ### Parameters - **n** (u8) - The raw byte value representing the flags. ``` -------------------------------- ### Flags::new Source: https://docs.rs/dhcproto/latest/dhcproto/v4/struct.Flags.html Creates a new instance of Flags from a 16-bit integer. ```APIDOC ## pub fn new(n: u16) -> Self ### Description Creates a new Flags instance from a u16 value. ### Parameters - **n** (u16) - The 16-bit integer representing the flags. ``` -------------------------------- ### Check FQDN Status Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Determine if a name is a fully qualified domain name. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let name = Name::from_str("www").unwrap(); assert!(!name.is_fqdn()); let name = Name::from_str("www.example.com").unwrap(); assert!(!name.is_fqdn()); let name = Name::from_str("www.example.com.").unwrap(); assert!(name.is_fqdn()); ``` -------------------------------- ### Encode long option chunks in Rust Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_chunks.html Demonstrates splitting a vector of IPv4 addresses into chunks and encoding them using the NIS Servers option code. ```rust use dhcproto::{encoder::Encoder, v4::{OptionCode, encode_long_opt_chunks}}; let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); let opt = iter::repeat(Ipv4Addr::from([1,2,3,4])).take(80).collect::>(); let res = encode_long_opt_chunks(OptionCode::NisServers, 4, &opt, |ip, e| e.write_u32((*ip).into()), &mut e); // [code, 252, 1,2,3,4,1,2,3,4 ..., code, 68, 1,2,3,4, ...] let mut x = vec![OptionCode::NisServers.into(), 252]; x.extend(iter::repeat(Ipv4Addr::from([1,2,3,4])).map(|ip| u32::from(ip).to_be_bytes()).flatten().take(252)); x.push(OptionCode::NisServers.into()); x.push(68); x.extend(iter::repeat(Ipv4Addr::from([1,2,3,4])).map(|ip| u32::from(ip).to_be_bytes()).flatten().take(68)); assert_eq!(buf, x); ``` -------------------------------- ### Canonical DNS Name Order Specification Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Reference documentation for canonical DNS name ordering as defined in RFC 4034. ```text 6.1. Canonical DNS Name Order For the purposes of DNS security, owner names are ordered by treating individual labels as unsigned left-justified octet strings. The absence of a octet sorts before a zero value octet, and uppercase US-ASCII letters are treated as if they were lowercase US-ASCII letters. To compute the canonical ordering of a set of DNS names, start by sorting the names according to their most significant (rightmost) labels. For names in which the most significant label is identical, continue sorting according to their next most significant label, and so forth. For example, the following names are sorted in canonical DNS name order. The most significant label is "example". At this level, "example" sorts first, followed by names ending in "a.example", then by names ending "z.example". The names within each level are sorted in the same way. example a.example yljkjljk.a.example Z.a.example zABC.a.EXAMPLE z.example \001.z.example *.z.example \200.z.example ``` -------------------------------- ### Create Result References using as_ref Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.EncodeResult.html Converts a Result reference into a Result containing references to the inner 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")); ``` -------------------------------- ### Return alternative Result with or Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Returns the provided Result if the current one is Err, otherwise returns the Ok value. ```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)); ``` -------------------------------- ### Append Name to Another Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Combine two Name instances, preserving the FQDN status of the second name. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let local = Name::from_str("www").unwrap(); let domain = Name::from_str("example.com").unwrap(); assert!(!domain.is_fqdn()); let name = local.clone().append_name(&domain).unwrap(); assert_eq!(name, Name::from_str("www.example.com").unwrap()); assert!(!name.is_fqdn()); // see also `Name::append_domain` let domain = Name::from_str("example.com.").unwrap(); assert!(domain.is_fqdn()); let name = local.append_name(&domain).unwrap(); assert_eq!(name, Name::from_str("www.example.com.").unwrap()); assert!(name.is_fqdn()); ``` -------------------------------- ### ClientFQDN Struct Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fqdn/struct.ClientFQDN.html The primary structure definition for ClientFQDN. ```rust pub struct ClientFQDN { /* private fields */ } ``` -------------------------------- ### Create Name from Labels Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Construct a Name instance from an iterator of labels. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; // From strings, uses utf8 conversion let from_labels = Name::from_labels(vec!["www", "example", "com"]).unwrap(); assert_eq!(from_labels, Name::from_str("www.example.com.").unwrap()); // Force a set of bytes into labels (this is none-standard and potentially dangerous) let from_labels = Name::from_labels(vec!["bad chars".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap(); assert_eq!(from_labels.iter().next(), Some(&b"bad chars"[..])); let root = Name::from_labels(Vec::<&str>::new()).unwrap(); assert!(root.is_root()); ``` -------------------------------- ### Chain Results with And Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Returns the provided result if the current result is Ok, otherwise returns the Err. ```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")); ``` -------------------------------- ### Convert to wildcard Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Replaces the first label of the name with a wildcard. ```rust use std::str::FromStr; use hickory_proto::rr::Name; let name = Name::from_str("www.example.com.").unwrap().into_wildcard(); assert_eq!(name, Name::from_str("*.example.com.").unwrap()); // does nothing if the root let name = Name::root().into_wildcard(); assert_eq!(name, Name::root()); ``` -------------------------------- ### VendorOpts Struct Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.VendorOpts.html The structure definition for VendorOpts, which includes a numeric identifier and the associated DHCP options. ```rust pub struct VendorOpts { pub num: u32, pub opts: DhcpOptions, } ``` -------------------------------- ### Provide default value with unwrap_or Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.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); ``` -------------------------------- ### Define Architecture struct Source: https://docs.rs/dhcproto/latest/dhcproto/v4/struct.Architecture.html The base structure definition for processor architecture. ```rust #[repr(transparent)] pub struct Architecture(pub u16); ``` -------------------------------- ### Parse Name with relaxed rules Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Attempts to decode via from_utf8, falling back to ASCII decoding if IDNA checks fail. ```rust use std::str::FromStr; use hickory_proto::rr::Name; // Ok, underscore in the beginning of a name assert!(Name::from_utf8("_allows.example.com.").is_ok()); // Error, underscore in the end assert!(Name::from_utf8("dis_allowed.example.com.").is_err()); // Ok, relaxed mode assert!(Name::from_str_relaxed("allow_in_.example.com.").is_ok()); ``` -------------------------------- ### Decode and Encode DHCPv6 Messages Source: https://docs.rs/dhcproto/latest/dhcproto/index.html Demonstrates the basic workflow for decoding a DHCPv6 message from bytes and re-encoding it using the provided Encoder and Decoder types. ```rust use dhcproto::v6::{Message, Encoder, Decoder, Decodable, Encodable}; // decode let bytes = solicit(); let msg = Message::decode(&mut Decoder::new(&bytes))?; // now encode let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); msg.encode(&mut e)?; ``` -------------------------------- ### Authentication Struct Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.Authentication.html The structure definition for Authentication, including its fields for protocol, algorithm, replay detection, and information. ```rust pub struct Authentication { pub proto: u8, pub algo: u8, pub rdm: u8, pub replay_detection: u64, pub info: Vec, } ``` -------------------------------- ### Convert Result to Option using ok Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.EncodeResult.html Converts a Result into an Option, discarding the error value. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Encoding long option bytes in Rust Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_bytes.html Demonstrates splitting a 300-byte sequence into two chunks using the encode_long_opt_bytes function. ```rust use dhcproto::{encoder::Encoder, v4::{OptionCode, encode_long_opt_bytes}}; let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); let msg = std::iter::repeat(b'a').take(300).collect::>(); let res = encode_long_opt_bytes(OptionCode::Message, &msg, &mut e); // [code, 255, b'a', ..., code, 45, b'a', ...] let mut x = vec![OptionCode::Message.into(), 255]; x.extend(std::iter::repeat(b'a').take(255)); x.push(OptionCode::Message.into()); x.push(45); x.extend(std::iter::repeat(b'a').take(45)); assert_eq!(buf, x); ``` -------------------------------- ### Define DataSourceFlags struct Source: https://docs.rs/dhcproto/latest/dhcproto/v4/bulk_query/struct.DataSourceFlags.html The primary structure definition for lease query data source flags. ```rust pub struct DataSourceFlags(/* private fields */); ``` -------------------------------- ### Decode and Encode DHCPv4 Messages Source: https://docs.rs/dhcproto/latest/dhcproto/index.html Demonstrates the basic workflow for decoding a DHCPv4 message from bytes and re-encoding it using the provided Encoder and Decoder types. ```rust use dhcproto::v4::{Message, Encoder, Decoder, Decodable, Encodable}; // decode let bytes = dhcp_offer(); let msg = Message::decode(&mut Decoder::new(&bytes))?; // now encode let mut buf = Vec::new(); let mut e = Encoder::new(&mut buf); msg.encode(&mut e)?; ``` -------------------------------- ### IAPrefix Struct Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.IAPrefix.html The structure definition for IAPrefix, containing lifetime, prefix, and option fields. ```rust pub struct IAPrefix { pub preferred_lifetime: u32, pub valid_lifetime: u32, pub prefix_len: u8, pub prefix_ip: Ipv6Addr, pub opts: DhcpOptions, } ``` -------------------------------- ### DHCPv6 Message Format Diagram Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.Message.html Visual representation of the DHCPv6 message header and options layout. ```text 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | msg-type | transaction-id | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | . options . . (variable number and length) . | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ msg-type Identifies the DHCP message type; the available message types are listed in Section 7.3. A 1-octet field. transaction-id The transaction ID for this message exchange. A 3-octet field. options Options carried in this message; options are described in Section 21. A variable-length field (4 octets less than the size of the message). ``` -------------------------------- ### Expect Err Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Returns the Err value or panics if the result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Unwrap with Default Value Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Returns the Ok value or the default value of the type if the result is 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); ``` -------------------------------- ### Function Signature for encode_long_opt_domains Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_domains.html The function signature for encoding domain names into chunked segments. ```rust pub fn encode_long_opt_domains( code: OptionCode, names: &[Name], e: &mut Encoder<'_>, ) -> EncodeResult<()> ``` -------------------------------- ### IANA Struct Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v6/struct.IANA.html The structure definition for IANA, including its fields for ID, timing parameters, and DHCP options. ```rust pub struct IANA { pub id: u32, pub t1: u32, pub t2: u32, pub opts: DhcpOptions, } ``` -------------------------------- ### Chain Results with And Then Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Calls a function to produce a new Result if the current result is Ok. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### Accessing the DHCPv6 Server Port Constant Source: https://docs.rs/dhcproto/latest/dhcproto/v6/constant.SERVER_PORT.html Defines the standard port 547 used for DHCPv6 server operations. ```rust pub const SERVER_PORT: u16 = 547; ``` -------------------------------- ### Reference Result values with as_ref and as_mut Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Converts a Result to a 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); ``` -------------------------------- ### Compare Names ignoring root with case sensitivity Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Performs a non-FQDN-aware case-sensitive comparison. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let name1 = Name::from_str("a.com.").unwrap(); let name2 = Name::from_ascii("A.CoM.").unwrap(); let name3 = Name::from_ascii("A.CoM").unwrap(); assert_eq!(&name1, &name2); assert!(name1.eq_ignore_root(&name2)); assert!(!name1.eq_ignore_root_case(&name2)); assert!(name2.eq_ignore_root_case(&name3)); ``` -------------------------------- ### Expect Result Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.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`"); ``` -------------------------------- ### Define RelayAgentInformation Source: https://docs.rs/dhcproto/latest/dhcproto/v4/relay/struct.RelayAgentInformation.html Shows the structure definition for RelayAgentInformation. ```rust pub struct RelayAgentInformation(/* private fields */); ``` -------------------------------- ### Check for localhost Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Determines if the Name is localhost or within the localhost zone. ```rust use std::str::FromStr; use hickory_proto::rr::Name; let name = Name::from_str("localhost").unwrap(); assert!(name.is_localhost()); let name = Name::from_str("localhost.").unwrap(); assert!(name.is_localhost()); let name = Name::from_str("my.localhost.").unwrap(); assert!(name.is_localhost()); ``` -------------------------------- ### Check for wildcard Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Checks if the first label of the name is a wildcard ('*'). ```rust use std::str::FromStr; use hickory_proto::rr::Name; let name = Name::from_str("www.example.com").unwrap(); assert!(!name.is_wildcard()); let name = Name::from_str("*.example.com").unwrap(); assert!(name.is_wildcard()); let name = Name::root(); assert!(!name.is_wildcard()); ``` -------------------------------- ### Compare Names ignoring root Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Performs a non-FQDN-aware case-insensitive comparison, returning true if names are equal or if a relative and non-relative name are otherwise identical. ```rust use std::str::FromStr; use hickory_proto::rr::domain::Name; let name1 = Name::from_str("a.com.").unwrap(); let name2 = name1.clone(); assert_eq!(&name1, &name2); assert!(name1.eq_ignore_root(&name2)); // Make name2 uppercase. let name2 = Name::from_str("A.CoM.").unwrap(); assert_eq!(&name1, &name2); assert!(name1.eq_ignore_root(&name2)); // Make name2 a relative name. // Note that standard equality testing now returns false. let name2 = Name::from_str("a.com").unwrap(); assert!(&name1 != &name2); assert!(name1.eq_ignore_root(&name2)); // Make name2 a completely unrelated name. let name2 = Name::from_str("b.com.").unwrap(); assert!(&name1 != &name2); assert!(!name1.eq_ignore_root(&name2)); ``` -------------------------------- ### Decoder Methods Source: https://docs.rs/dhcproto/latest/dhcproto/decoder/struct.Decoder.html Methods available on the Decoder struct for reading data from the underlying buffer. ```APIDOC ## pub fn new(buffer: &'a [u8]) -> Self Creates a new Decoder instance wrapping the provided byte buffer. ## pub fn read_u8(&mut self) -> DecodeResult Reads a single byte (u8) from the buffer. ## pub fn read_u32(&mut self) -> DecodeResult Reads a 32-bit unsigned integer (u32) from the buffer. ## pub fn read_string(&mut self, len: usize) -> DecodeResult Reads a UTF-8 encoded string of a specified length. ## pub fn read_ipv4(&mut self, length: usize) -> DecodeResult Reads an IPv4 address from the buffer. ## pub fn peek_u8(&self) -> DecodeResult Peeks at the next byte without advancing the internal pointer. ``` -------------------------------- ### pub fn encode_long_opt_chunks Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_chunks.html Splits data into chunks of up to u8::MAX / factor (255 is the max opt length), where each chunk is prepended by the length of the chunk and the code. The factor accounts for writing data where T is more than 1 byte. ```APIDOC ## Function: encode_long_opt_chunks ### Signature `pub fn encode_long_opt_chunks<'a, T, F>(code: OptionCode, factor: usize, data: &[T], f: F, e: &mut Encoder<'a>) -> EncodeResult<()>` ### Description Splits `data` into chunks of up to `u8::MAX / factor` (255 is the max opt length), where each chunk is prepended by the length of the chunk and the `code`. The `factor` accounts for writing data where `T` is more than 1 byte. ### Parameters - **code** (OptionCode) - The option code to prepend to each chunk. - **factor** (usize) - The number of bytes in each `T`. - **data** (&[T]) - The data to be encoded. - **f** (F) - A closure that writes a single `T` to the encoder. - **e** (&mut Encoder<'a>) - The encoder instance. ### Returns - **EncodeResult<()>** - Returns `Ok(())` on success, or an error if encoding fails. ``` -------------------------------- ### Unwrap Err Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Returns the Err value or panics if the result is 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"); ``` -------------------------------- ### Collect Result Iterator Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Shows 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); ``` -------------------------------- ### NtpSuboption Enum Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v6/enum.NtpSuboption.html The structure of the NtpSuboption enum, which supports IPv6 addresses for server and multicast options, and a domain name for FQDN options. ```rust pub enum NtpSuboption { ServerAddress(Ipv6Addr), MulticastAddress(Ipv6Addr), FQDN(Name), } ``` -------------------------------- ### IntoIterator for Result Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Demonstrates converting 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, []); ``` -------------------------------- ### pub fn encode_long_opt_bytes Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_bytes.html Splits bytes into chunks of up to u8::MAX (255), where each chunk is prepended by the length of the chunk and the code. ```APIDOC ## Function: encode_long_opt_bytes ### Description Splits `bytes` into chunks of up to u8::MAX (255 is the max opt length), where each chunk is prepended by the length of the chunk and the code. ### Signature `pub fn encode_long_opt_bytes(code: OptionCode, bytes: &[u8], e: &mut Encoder<'_>) -> EncodeResult<()>` ### Parameters - **code** (OptionCode) - The option code to prepend to each chunk. - **bytes** (&[u8]) - The byte slice to be encoded. - **e** (&mut Encoder<'_>) - The encoder instance used to write the data. ### Returns - **EncodeResult<()>** - Returns Ok(()) on success, or an error if encoding fails. ``` -------------------------------- ### UnknownOption struct definition Source: https://docs.rs/dhcproto/latest/dhcproto/v4/struct.UnknownOption.html The definition of the UnknownOption struct, which contains private fields. ```rust pub struct UnknownOption { /* private fields */ } ``` -------------------------------- ### Calculate Product of Result Iterator Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Demonstrates using the Product trait to multiply elements in an iterator of Results, returning an Err if any parsing fails. ```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()); ``` -------------------------------- ### Accessing CLIENT_PORT Source: https://docs.rs/dhcproto/latest/dhcproto/v4/constant.CLIENT_PORT.html The constant is defined as a u16 with a value of 68. ```rust pub const CLIENT_PORT: u16 = 68; ``` -------------------------------- ### Check Result with predicate Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Checking if a Result is Ok and matches a predicate. ```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); ``` -------------------------------- ### DhcpOption Enum Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v4/enum.DhcpOption.html The complete list of variants for the DhcpOption enum, covering standard DHCP options and their associated data types. ```rust pub enum DhcpOption { Show 106 variants Pad, SubnetMask(Ipv4Addr), TimeOffset(i32), Router(Vec), TimeServer(Vec), NameServer(Vec), DomainNameServer(Vec), LogServer(Vec), QuoteServer(Vec), LprServer(Vec), ImpressServer(Vec), ResourceLocationServer(Vec), Hostname(String), BootFileSize(u16), MeritDumpFile(String), DomainName(String), SwapServer(Ipv4Addr), RootPath(String), ExtensionsPath(String), IpForwarding(bool), NonLocalSrcRouting(bool), PolicyFilter(Vec<(Ipv4Addr, Ipv4Addr)>), MaxDatagramSize(u16), DefaultIpTtl(u8), PathMtuAgingTimeout(u32), PathMtuPlateauTable(Vec), InterfaceMtu(u16), AllSubnetsLocal(bool), BroadcastAddr(Ipv4Addr), PerformMaskDiscovery(bool), MaskSupplier(bool), PerformRouterDiscovery(bool), RouterSolicitationAddr(Ipv4Addr), StaticRoutingTable(Vec<(Ipv4Addr, Ipv4Addr)>), TrailerEncapsulated(bool), ArpCacheTimeout(u32), EthernetEncapsulation(bool), DefaultTcpTtl(u8), TcpKeepaliveInterval(u32), TcpKeepaliveGarbage(bool), NisDomain(String), NisServers(Vec), NtpServers(Vec), VendorExtensions(Vec), NetBiosNameServers(Vec), NetBiosDatagramDistributionServer(Vec), NetBiosNodeType(NodeType), NetBiosScope(String), XFontServer(Vec), XDisplayManager(Vec), RequestedIpAddress(Ipv4Addr), AddressLeaseTime(u32), OptionOverload(u8), MessageType(MessageType), ServerIdentifier(Ipv4Addr), ParameterRequestList(Vec), Message(String), MaxMessageSize(u16), Renewal(u32), Rebinding(u32), ClassIdentifier(Vec), ClientIdentifier(Vec), NwipDomainName(String), NwipInformation(Vec), NispServiceDomain(String), NispServers(Vec), TFTPServerName(Vec), BootfileName(Vec), MobileIpHomeAgent(Vec), SmtpServer(Vec), Pop3Server(Vec), NntpServer(Vec), WwwServer(Vec), DefaultFingerServer(Vec), IrcServer(Vec), StreetTalkServer(Vec), StreetTalkDirectoryAssistance(Vec), UserClass(Vec), RapidCommit, ClientFQDN(ClientFQDN), RelayAgentInformation(RelayAgentInformation), BcmsControllerNames(Vec), BcmsControllerAddrs(Vec), ClientLastTransactionTime(u32), AssociatedIp(Vec), ClientSystemArchitecture(Architecture), ClientNetworkInterface(u8, u8, u8), ClientMachineIdentifier(Vec), TimezonePosixString(String), TimezoneDatabaseString(String), Ipv6OnlyPreferred(u32), CaptivePortal(String), DisableSLAAC(AutoConfig), SubnetSelection(Ipv4Addr), DomainSearch(Vec), ClasslessStaticRoute(Vec<(Ipv4Net, Ipv4Addr)>), TFTPServerAddress(Ipv4Addr), BulkLeaseQueryStatusCode(Code, String), BulkLeaseQueryBaseTime(u32), BulkLeasQueryStartTimeOfState(u32), BulkLeaseQueryQueryStartTime(u32), BulkLeaseQueryQueryEndTime(u32), BulkLeaseQueryDhcpState(QueryState), BulkLeaseQueryDataSource(DataSourceFlags), End, Unknown(UnknownOption), } ``` -------------------------------- ### Convert Result to Option with ok and err Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Converts a Result into an Option, either keeping the Ok value or the Err value. ```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")); ``` -------------------------------- ### RelayFlags API Source: https://docs.rs/dhcproto/latest/dhcproto/v4/relay/struct.RelayFlags.html Methods available for interacting with the RelayFlags struct. ```APIDOC ## pub fn new(n: u8) -> Self ### Description Creates a new instance of RelayFlags from a raw u8 value. ## pub fn unicast(&self) -> bool ### Description Retrieves the current status of the unicast flag. ## pub fn set_unicast(self) -> Self ### Description Sets the unicast bit and returns a new instance of RelayFlags. ``` -------------------------------- ### Define Flags struct Source: https://docs.rs/dhcproto/latest/dhcproto/v4/struct.Flags.html The definition of the Flags struct. ```rust pub struct Flags(/* private fields */); ``` -------------------------------- ### Decoding DHCPv4 Messages Source: https://docs.rs/dhcproto/latest/dhcproto/v4/index.html Shows the process of decoding a raw byte buffer into a DHCPv4 message structure using the Decoder. ```rust use dhcproto::{v4::Message, Decoder, Decodable}; let offer = bootreq(); let msg = Message::decode(&mut Decoder::new(&offer))?; ``` -------------------------------- ### Accessing the CLIENT_PORT constant Source: https://docs.rs/dhcproto/latest/dhcproto/v6/constant.CLIENT_PORT.html The constant is defined as a u16 with a value of 546. ```rust pub const CLIENT_PORT: u16 = 546; ``` -------------------------------- ### Convert string to Name Source: https://docs.rs/dhcproto/latest/dhcproto/struct.Name.html Converts a string to a Name using IDNA punycode encoding. Note that IDNA compatibility causes the name to be lowercased. ```rust use std::str::FromStr; use hickory_proto::rr::Name; let bytes_name = Name::from_labels(vec!["WWW".as_bytes(), "example".as_bytes(), "COM".as_bytes()]).unwrap(); // from_str calls through to from_utf8 let utf8_name = Name::from_str("WWW.example.COM.").unwrap(); let lower_name = Name::from_str("www.example.com.").unwrap(); assert!(!bytes_name.eq_case(&utf8_name)); assert!(lower_name.eq_case(&utf8_name)); ``` -------------------------------- ### Check Result with is_err_and Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Checks if the result is an Err and matches a specific predicate. ```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); ``` -------------------------------- ### UnknownInfo struct definition Source: https://docs.rs/dhcproto/latest/dhcproto/v4/relay/struct.UnknownInfo.html The definition of the UnknownInfo struct. ```rust pub struct UnknownInfo { /* private fields */ } ``` -------------------------------- ### encode_long_opt_domains Source: https://docs.rs/dhcproto/latest/dhcproto/v4/fn.encode_long_opt_domains.html Encodes a list of domain Names into chunked pieces for DHCP options. ```APIDOC ## Function: encode_long_opt_domains ### Description Encodes a list of domain `Name`s chunked into u8::MAX pieces. Each chunk is prepended by the length of the chunk and the provided option code. ### Signature `pub fn encode_long_opt_domains(code: OptionCode, names: &[Name], e: &mut Encoder<'_>) -> EncodeResult<()>` ### Parameters - **code** (OptionCode) - The option code to prepend to each chunk. - **names** (&[Name]) - A slice of domain names to be encoded. - **e** (&mut Encoder<'_>) - The encoder instance used to write the data. ### Returns - **EncodeResult<()>** - Returns Ok(()) on success, or an error if encoding fails. ``` -------------------------------- ### Create Mutable Result References using as_mut Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.EncodeResult.html Converts a mutable Result reference into a Result containing mutable references to the inner values. ```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); ``` -------------------------------- ### Compute default value with unwrap_or_else Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.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() } ``` -------------------------------- ### MIN_PACKET_SIZE Constant Definition Source: https://docs.rs/dhcproto/latest/dhcproto/v4/constant.MIN_PACKET_SIZE.html Represents the minimum packet size constant used in the dhcproto::v4 module. ```rust pub const MIN_PACKET_SIZE: usize = 300; ``` -------------------------------- ### Unwrap Result Values Source: https://docs.rs/dhcproto/latest/dhcproto/error/type.DecodeResult.html Extracts the Ok value or panics if the result is Err. Use with caution as it may abort the program. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ```