### LinuxSllPayloadSlice Search Examples Source: https://docs.rs/etherparse/latest/etherparse/struct.LinuxSllPayloadSlice.html?search= Examples demonstrating how to search within LinuxSllPayloadSlice. These examples cover basic searches and more complex type-to-type conversions. ```APIDOC ## Search Examples ### Basic Search This example shows a simple search for a common type. ```rust // Example: Search for std::vec let results = search("std::vec"); ``` ### Type Conversion Search This example demonstrates searching for type conversions, such as converting a `u32` to a `bool`. ```rust // Example: Search for u32 -> bool conversion let results = search("u32 -> bool"); ``` ### Generic Type Conversion Search This example illustrates searching for generic type conversions involving `Option`. ```rust // Example: Search for Option, (T -> U) -> Option let results = search("Option, (T -> U) -> Option"); ``` ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/etherparse/latest/etherparse/ip_number/constant.ARIS.html?search= An example search query demonstrating usage patterns. ```text std::vec ``` -------------------------------- ### Example: Parsing PacketHeaders from Ethernet Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketHeaders.html?search=std%3A%3Avec Demonstrates basic usage of PacketHeaders::from_ether_type to parse a packet slice starting with a specified EtherType. Shows how to access the different header components after successful parsing. ```rust use etherparse::{ether_type, PacketHeaders}; match PacketHeaders::from_ether_type(ether_type::IPV4, packet) { Err(value) => println!("Err {:?}", value), Ok(value) => { println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec println!("net: {:?}", value.net); // ip & arp println!("transport: {:?}", value.transport); } } ``` -------------------------------- ### PacketBuilder Starting Options Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketBuilder.html?search=u32+-%3E+bool Lists the initial options available for starting a packet construction with PacketBuilder. ```APIDOC ## Options * Starting Options: * `PacketBuilder::ethernet2` * `PacketBuilder::linux_sll` * `PacketBuilder::ip` * `PacketBuilder::ipv4` * `PacketBuilder::ipv6` ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/etherparse/latest/etherparse/ip_number/constant.GMTP.html?search=std%3A%3Avec Illustrative examples of search queries that can be performed, demonstrating common patterns in Rust documentation searches. ```rust std::vec ``` ```rust u32 -> bool ``` ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Example Search: u32 to bool Source: https://docs.rs/etherparse/latest/etherparse/ip_number/constant.ARIS.html?search= An example search query illustrating type conversion or mapping. ```text u32 -> bool ``` -------------------------------- ### Example: Parsing a packet from Ethernet using LaxSlicedPacket::from_ethernet Source: https://docs.rs/etherparse/latest/etherparse/struct.LaxSlicedPacket.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates basic usage of LaxSlicedPacket::from_ethernet to parse a packet slice starting from the Ethernet II header. It shows how to handle parsing errors and access different layers of the packet. ```rust use etherparse::{ ether_type, LaxSlicedPacket, LenSource, }; match LaxSlicedPacket::from_ethernet(&packet) { Err(value) => { // An error is returned in case the ethernet II header could // not be parsed (other errors are stored in the "stop_err" field) println!("Err {:?}", value) }, Ok(value) => { if let Some((stop_err, error_layer)) = value.stop_err.as_ref() { // error was encountered after parsing the ethernet 2 header println!("Error on layer {:?}: {:?}", error_layer, stop_err); } // parts that could be parsed without error println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec // net (ip or arp) println!("net: {:?}", value.net); if let Some(ip_payload) = value.net.as_ref().map(|net| net.ip_payload_ref()).flatten() { // the ip payload len_source field can be used to check // if the slice length was used as a fallback value if ip_payload.len_source == LenSource::Slice { println!(" Used slice length as fallback to identify the IP payload"); } else { println!(" IP payload could correctly be identified via the length field in the header"); } } // transport (udp or tcp) println!("transport: {:?}", value.transport); } }; ``` -------------------------------- ### PacketBuilder Example Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketBuilder.html Demonstrates how to use PacketBuilder to construct a packet starting with an Ethernet II header, followed by an IPv4 header and a UDP header, and then serializing it with a payload. ```APIDOC ## Example: Generating a packet that starts with an Ethernet II header: ```rust use etherparse::PacketBuilder; let builder = PacketBuilder:: ethernet2([1,2,3,4,5,6], //source mac [7,8,9,10,11,12]) //destination mac .ipv4([192,168,1,1], //source ip [192,168,1,2], //destination ip 20) //time to life .udp(21, //source port 1234); //destination port //payload of the udp packet let payload = [1,2,3,4,5,6,7,8]; //get some memory to store the result let mut result = Vec::::with_capacity( builder.size(payload.len())); //serialize builder.write(&mut result, &payload).unwrap(); println!("{:?}", result); ``` ``` -------------------------------- ### Example: Parsing a packet using LaxSlicedPacket::from_ether_type Source: https://docs.rs/etherparse/latest/etherparse/struct.LaxSlicedPacket.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates basic usage of LaxSlicedPacket::from_ether_type to parse a packet slice starting with a specified EtherType. It shows how to handle parsing errors and access different layers of the packet. ```rust use etherparse::{ ether_type, LaxSlicedPacket, }; let packet = LaxSlicedPacket::from_ether_type(ether_type::IPV4, packet); if let Some((stop_err, error_layer)) = packet.stop_err.as_ref() { // in case an error is encountered parsing is stopped println!("Error on layer {:?}: {:?}", error_layer, stop_err); } // parts that could be parsed without error println!("link: {:?}", packet.link); println!("link_exts: {:?}", packet.link_exts); // vlan & macsec println!("net: {:?}", packet.net); // ip & arp println!("transport: {:?}", packet.transport); ``` -------------------------------- ### IpHeaders Search Examples Source: https://docs.rs/etherparse/latest/etherparse/enum.IpHeaders.html?search= Examples of how to perform searches within IpHeaders. These demonstrate common search patterns. ```APIDOC ## Search Examples ### Example 1: Searching for a specific type ``` std::vec ``` ### Example 2: Searching for type conversions ``` u32 -> bool ``` ### Example 3: Searching for generic type transformations ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### Example Search: Option mapping Source: https://docs.rs/etherparse/latest/etherparse/ip_number/constant.ARIS.html?search= An example search query showing functional programming patterns with Option. ```text Option, (T -> U) -> Option ``` -------------------------------- ### Example Searches for IpSlice Source: https://docs.rs/etherparse/latest/etherparse/enum.IpSlice.html?search= Demonstrates various ways to search within IpSlice, providing examples for common use cases. ```APIDOC ## Example Searches This section provides examples of how to search within `IpSlice`. ### Search Examples - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### NdpOptionsIterator Search Examples Source: https://docs.rs/etherparse/latest/etherparse/icmpv6/struct.NdpOptionsIterator.html?search= Examples demonstrating how to search for different types of data within NdpOptionsIterator. ```APIDOC ## Search Examples ### Example 1: Searching for a specific type ```rust // Example search for std::vec let results = ndp_options_iterator.search("std::vec"); ``` ### Example 2: Searching for a type conversion ```rust // Example search for u32 -> bool conversion let results = ndp_options_iterator.search("u32 -> bool"); ``` ### Example 3: Searching for generic type transformations ```rust // Example search for Option, (T -> U) -> Option let results = ndp_options_iterator.search("Option, (T -> U) -> Option"); ``` ``` -------------------------------- ### PayloadSlice Search Examples Source: https://docs.rs/etherparse/latest/etherparse/enum.PayloadSlice.html?search= Demonstrates example searches that can be performed with PayloadSlice. ```APIDOC ## Example Searches ### Search for a specific type ``` std::vec ``` ### Search for type conversions ``` u32 -> bool ``` ### Search for generic type transformations ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### NetSlice Enum Search Examples Source: https://docs.rs/etherparse/latest/etherparse/enum.NetSlice.html?search= Examples of how to perform searches within NetSlice enums. ```APIDOC ## Search Examples ### Example searches: * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### LenError Example Source: https://docs.rs/etherparse/latest/etherparse/err/struct.LenError.html An example demonstrating how to construct a LenError when there is not enough data available to decode a UDP header. This illustrates the usage of `required_len`, `len`, `layer`, `len_source`, and `layer_start_offset`. ```APIDOC ## §Examples: An example for an error that could be returned when there is not enough data available to decode an UDP header would be: ```rust use etherparse::* err::LenError{ // Expected to have at least the length of an UDP header present: required_len: UdpHeader::LEN, // Could not decode the UDP header: layer: err::Layer::UdpHeader, // There was only 1 byte left (not enough for an UDP header): len: 1, // The provided length was determined by the total length field in the // IPv4 header: len_source: LenSource::Ipv4HeaderTotalLen, // Offset in bytes from the start of decoding (ethernet in this) case // to the expected UDP header start: layer_start_offset: Ethernet2Header::LEN + Ipv4Header::MIN_LEN }; ``` ``` -------------------------------- ### Example LenError for Insufficient UDP Header Data Source: https://docs.rs/etherparse/latest/etherparse/err/struct.LenError.html?search= Illustrates creating a LenError instance when there isn't enough data to decode a UDP header. This example shows how to set the required length, the available length, the layer, the length source, and the offset. ```rust use etherparse::* err::LenError{ // Expected to have at least the length of an UDP header present: required_len: UdpHeader::LEN, // Could not decode the UDP header: layer: err::Layer::UdpHeader, // There was only 1 byte left (not enough for an UDP header): len: 1, // The provided length was determined by the total length field in the // IPv4 header: len_source: LenSource::Ipv4HeaderTotalLen, // Offset in bytes from the start of decoding (ethernet in this) case // to the expected UDP header start: layer_start_offset: Ethernet2Header::LEN + Ipv4Header::MIN_LEN }; ``` -------------------------------- ### IpFragOffset Usage Examples Source: https://docs.rs/etherparse/latest/etherparse/struct.IpFragOffset.html?search=std%3A%3Avec Demonstrates how to create and use IpFragOffset instances, including value conversion and error handling for out-of-range values. ```APIDOC ## IpFragOffset The fragment offset is a 13 bit unsigned integer indicating the stating position of the payload of a packet relative to the originally fragmented packet payload. This value can be present in an `crate::Ipv4Header` or an `crate::Ipv6FragmentHeader`. ### Example Usage: #### Using try_into: ```rust use etherparse::IpFragOffset; let frag_offset: IpFragOffset = 123.try_into().unwrap(); assert_eq!(frag_offset.value(), 123); let value: u16 = frag_offset.into(); assert_eq!(123, value); ``` #### Using try_new: ```rust use etherparse::IpFragOffset; use etherparse::err::{ValueTooBigError, ValueType}; let frag_offset = IpFragOffset::try_new(123).unwrap(); assert_eq!(frag_offset.value(), 123); // Maximum allowed value is 0b0001_1111_1111_1111 assert_eq!( IpFragOffset::try_new(IpFragOffset::MAX_U16 + 1), Err(ValueTooBigError{ actual: IpFragOffset::MAX_U16 + 1, max_allowed: IpFragOffset::MAX_U16, value_type: ValueType::IpFragmentOffset, }) ); ``` #### Using new_unchecked (unsafe): ```rust use etherparse::IpFragOffset; // Use only if you are certain the value is within the allowed range (0 to IpFragOffset::MAX_U16) let frag_offset = unsafe { IpFragOffset::new_unchecked(123) }; assert_eq!(frag_offset.value(), 123); ``` ### Constants: * **MAX_U16**: The maximum value allowed for `IpFragOffset` (0x1FFF). ``` -------------------------------- ### Get element index using pointer arithmetic Source: https://docs.rs/etherparse/latest/etherparse/struct.TcpOptions.html?search=std%3A%3Avec Use `element_offset` to find the index of an element within a slice using pointer arithmetic. It returns `None` if the element reference is not aligned to the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); assert_eq!(arr.element_offset(weird_elm), None); ``` -------------------------------- ### VlanPcp::try_new Example Source: https://docs.rs/etherparse/latest/etherparse/struct.VlanPcp.html?search=std%3A%3Avec Demonstrates creating a VlanPcp with a valid value and handling errors for out-of-range values. ```rust use etherparse.VlanPcp; let pcp = VlanPcp::try_new(2).unwrap(); assert_eq!(pcp.value(), 2); // if a number that can not be represented in an 3 bit integer // gets passed in an error is returned use etherparse.err::{ValueTooBigError, ValueType}; assert_eq!( VlanPcp::try_new(VlanPcp::MAX_U8 + 1), Err(ValueTooBigError{ actual: VlanPcp::MAX_U8 + 1, max_allowed: VlanPcp::MAX_U8, value_type: ValueType::VlanPcp, }) ); ``` -------------------------------- ### LaxSlicedPacket::from_ethernet Example Source: https://docs.rs/etherparse/latest/etherparse/struct.LaxSlicedPacket.html?search=std%3A%3Avec Demonstrates basic usage of LaxSlicedPacket::from_ethernet to parse a network packet slice starting from the Ethernet II header. Handles potential parsing errors and accesses parsed header information. ```rust use etherparse::{ ether_type, LaxSlicedPacket, LenSource, }; match LaxSlicedPacket::from_ethernet(&packet) { Err(value) => { // An error is returned in case the ethernet II header could // not be parsed (other errors are stored in the "stop_err" field) println!("Err {:?}", value) }, Ok(value) => { if let Some((stop_err, error_layer)) = value.stop_err.as_ref() { // error was encountered after parsing the ethernet 2 header println!("Error on layer {}: {:?}", error_layer, stop_err); } // parts that could be parsed without error println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec // net (ip or arp) println!("net: {:?}", value.net); if let Some(ip_payload) = value.net.as_ref().map(|net| net.ip_payload_ref()).flatten() { // the ip payload len_source field can be used to check // if the slice length was used as a fallback value if ip_payload.len_source == LenSource::Slice { println!(" Used slice length as fallback to identify the IP payload"); } else { println!(" IP payload could correctly be identified via the length field in the header"); } } // transport (udp or tcp) println!("transport: {:?}", value.transport); } }; ``` -------------------------------- ### Ipv4Options Conversion Examples Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to convert various data types into Ipv4Options, including static arrays, slices, and handling potential errors. ```APIDOC ## Ipv4Options Conversion Examples ### Description Examples showing how to create `Ipv4Options` from different sources and how to handle errors. ### Example 1: Static sized arrays ```rust use etherparse::Ipv4Options; let options: Ipv4Options = [1,2,3,4].into(); assert_eq!(&options[..], &[1,2,3,4]); ``` ### Example 2: Slices ```rust use etherparse::Ipv4Options; let some_data = vec![1,2,3,4,5,6,7,8]; let options: Ipv4Options = (&some_data[..]).try_into().unwrap(); assert_eq!(options.as_slice(), &[1,2,3,4,5,6,7,8]); ``` ### Example 3: Error Handling for Invalid Length ```rust use etherparse::err::ipv4::BadOptionsLen; use etherparse::Ipv4Options; let result = Ipv4Options::try_from(&[1,2,3][..]); assert_eq!(result, Err(BadOptionsLen { bad_len: 3 })); ``` ``` -------------------------------- ### IpFragOffset Usage Examples Source: https://docs.rs/etherparse/latest/etherparse/struct.IpFragOffset.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates various ways to create and use the IpFragOffset struct, including conversion from u16, safe creation with try_new, and unsafe creation with new_unchecked. ```APIDOC ## IpFragOffset ### Description The fragment offset is a 13 bit unsigned integer indicating the stating position of the payload of a packet relative to the originally fragmented packet payload. This value can be present in an `crate::Ipv4Header` or an `crate::Ipv6FragmentHeader`. ### Example Usage: ```rust use etherparse::IpFragOffset; // try into { let frag_offset: IpFragOffset = 123.try_into().unwrap(); assert_eq!(frag_offset.value(), 123); // fragment offset can always be converted back to an u16 let value: u16 = frag_offset.into(); assert_eq!(123, value); } // via try_new { let frag_offset = IpFragOffset::try_new(123).unwrap(); assert_eq!(frag_offset.value(), 123); // note that only 13 bit numbers are allowed (meaning // 0b0001_1111_1111_1111 is the maximum allowed value) use etherparse::err::{ValueTooBigError, ValueType}; assert_eq!( IpFragOffset::try_new(IpFragOffset::MAX_U16 + 1), Err(ValueTooBigError{ actual: IpFragOffset::MAX_U16 + 1, max_allowed: IpFragOffset::MAX_U16, value_type: ValueType::IpFragmentOffset, }) ); } // via new_unchecked { // in case you are sure the number does not exceed the max // you can use the unsafe new_unchecked function let frag_offset = unsafe { // please make sure that the value is not greater than IpFragOffset::MAX_U16 // before calling this method IpFragOffset::new_unchecked(123) }; assert_eq!(frag_offset.value(), 123); } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.rs/etherparse/latest/etherparse/struct.SlicedPacket.html?search=u32+-%3E+bool Demonstrates how to use `SlicedPacket::from_ethernet` to parse a packet and access its different layers. ```APIDOC ## Examples Basic usage: ```rust match SlicedPacket::from_ethernet(&packet) { Err(value) => println!("Err {:?}", value), Ok(value) => { println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec println!("net: {:?}", value.net); // ip & arp println!("transport: {:?}", value.transport); } }; ``` ``` -------------------------------- ### Example Usage of Ipv4Header Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Header.html Demonstrates creating, calculating checksum, serializing, and deserializing an IPv4 header. ```rust use etherparse::{Ipv4Header, IpNumber}; let mut header = Ipv4Header { source: [1,2,3,4], destination: [1,2,3,4], time_to_live: 4, total_len: Ipv4Header::MIN_LEN as u16 + 100, protocol: IpNumber::UDP, ..Default::default() }; // depending on your use case you might want to set the correct checksum header.header_checksum = header.calc_header_checksum(); // header can be serialized into the "on the wire" format // using the "write" or "to_bytes" methods let bytes = header.to_bytes(); // IPv4 headers can be decoded via "read" or "from_slice" let (decoded, slice_rest) = Ipv4Header::from_slice(&bytes).unwrap(); assert_eq!(header, decoded); assert_eq!(slice_rest, &[]); ``` -------------------------------- ### Example Usage of Ipv4Header Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Header.html?search= Demonstrates how to create an Ipv4Header instance, set its fields, calculate the header checksum, serialize it into bytes, and deserialize it back from a byte slice. ```APIDOC ## Example Usage: ```rust use etherparse::{Ipv4Header, IpNumber}; let mut header = Ipv4Header { source: [1,2,3,4], destination: [1,2,3,4], time_to_live: 4, total_len: Ipv4Header::MIN_LEN as u16 + 100, protocol: IpNumber::UDP, ..Default::default() }; // depending on your use case you might want to set the correct checksum header.header_checksum = header.calc_header_checksum(); // header can be serialized into the "on the wire" format // using the "write" or "to_bytes" methods let bytes = header.to_bytes(); // IPv4 headers can be decoded via "read" or "from_slice" let (decoded, slice_rest) = Ipv4Header::from_slice(&bytes).unwrap(); assert_eq!(header, decoded); assert_eq!(slice_rest, &[]); ``` ``` -------------------------------- ### get Source: https://docs.rs/etherparse/latest/etherparse/struct.TcpOptions.html Safely gets a reference to an element or subslice using an index or range. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> where I: SliceIndex<[T]> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Examples ``` let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` ``` -------------------------------- ### Example Searches for Ipv6Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv6Slice.html?search= Demonstrates various ways to search within Ipv6Slice, including searching for specific types, type conversions, and generic type manipulations. ```APIDOC ## Example Searches This section provides examples of how to search within Ipv6Slice. ### Search Examples - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Basic SIMD Slice Splitting Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Illustrates splitting a slice into prefix, middle SIMD types, and suffix using `as_simd`. This example shows a case where there are not enough elements for the middle SIMD part. ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); ``` -------------------------------- ### Get Element or Subslice by Index Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `get` to safely retrieve a reference to an element or subslice. Returns `None` if the index is out of bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Get Last Element of a Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `last` to safely get an immutable reference to the last element, returning `None` for empty slices. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Example: Parsing Packet Headers from IP Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketHeaders.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `PacketHeaders::from_ip_slice` to parse IP packet data. It includes error handling and printing of the parsed header fields. ```rust use etherparse::PacketHeaders; match PacketHeaders::from_ip_slice(&packet) { Err(value) => println!("Err {:?}", value), Ok(value) => { println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec println!("net: {:?}", value.net); // ip & arp println!("transport: {:?}", value.transport); } } ``` -------------------------------- ### Example Usage of Ipv4Header Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Header.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create, serialize, and deserialize an Ipv4Header using the etherparse library. ```APIDOC ## Example Usage: ```rust use etherparse::{Ipv4Header, IpNumber}; let mut header = Ipv4Header { source: [1,2,3,4], destination: [1,2,3,4], time_to_live: 4, total_len: Ipv4Header::MIN_LEN as u16 + 100, protocol: IpNumber::UDP, ..Default::default() }; // depending on your use case you might want to set the correct checksum header.header_checksum = header.calc_header_checksum(); // header can be serialized into the "on the wire" format // using the "write" or "to_bytes" methods let bytes = header.to_bytes(); // IPv4 headers can be decoded via "read" or "from_slice" let (decoded, slice_rest) = Ipv4Header::from_slice(&bytes).unwrap(); assert_eq!(header, decoded); assert_eq!(slice_rest, &[]); ``` ``` -------------------------------- ### SlicedPacket::from_ether_type Source: https://docs.rs/etherparse/latest/etherparse/struct.SlicedPacket.html?search= Parses a packet starting from a specified EtherType. This is useful when you want to bypass the Ethernet header and start parsing from a specific protocol type. ```APIDOC ## SlicedPacket::from_ether_type ### Description Parses a packet starting from a specified EtherType. ### Method `SlicedPacket::from_ether_type` ### Parameters - `ether_type`: u16 - The EtherType to start parsing from. - `packet`: &[u8] - The raw packet data to parse. ### Response - `Result` - Ok(SlicedPacket) on success, Err(String) on parsing failure. ### Request Example ```rust // Example usage would be similar to from_ethernet, but specifying the ether_type ``` ``` -------------------------------- ### LenError Example: Insufficient Data Source: https://docs.rs/etherparse/latest/etherparse/err/struct.LenError.html?search=std%3A%3Avec An example demonstrating how to construct a LenError when there is not enough data available to decode a UDP header, highlighting the `required_len` and `len` fields. ```APIDOC ## Example: Insufficient Data for UDP Header ### Description This example shows how to create a `LenError` instance to represent a scenario where the provided data slice is too short to contain a complete UDP header. ### Code ```rust use etherparse::err::{LenError, LenSource, Layer}; use etherparse::{UdpHeader, Ethernet2Header, Ipv4Header}; let udp_header_error = LenError { // Expected to have at least the length of an UDP header present: required_len: UdpHeader::LEN, // Could not decode the UDP header: layer: Layer::UdpHeader, // There was only 1 byte left (not enough for an UDP header): len: 1, // The provided length was determined by the total length field in the // IPv4 header: len_source: LenSource::Ipv4HeaderTotalLen, // Offset in bytes from the start of decoding (ethernet in this) case // to the expected UDP header start: layer_start_offset: Ethernet2Header::LEN + Ipv4Header::MIN_LEN }; ``` ``` -------------------------------- ### Split Off Slice Starting with Third Element Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Removes and returns a subslice starting from the third element. The original slice is modified to contain the elements before the split point. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### Example: Parsing Packet Headers by EtherType Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketHeaders.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates basic usage of `PacketHeaders::from_ether_type` to parse packet data. Handles potential parsing errors and prints decoded header information. ```rust use etherparse::{ether_type, PacketHeaders}; match PacketHeaders::from_ether_type(ether_type::IPV4, packet) { Err(value) => println!("Err {:?}", value), Ok(value) => { println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec println!("net: {:?}", value.net); // ip & arp println!("transport: {:?}", value.transport); } } ``` -------------------------------- ### Example Search: Option, (T -> U) -> Option Source: https://docs.rs/etherparse/latest/etherparse/ip_number/constant.FC.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates a common functional programming pattern for transforming Option types. ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Get Reference to Underlying Array Source: https://docs.rs/etherparse/latest/etherparse/struct.TcpOptions.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use `as_array` to get a reference to the underlying array if its length exactly matches the specified size `N`. Returns `None` otherwise. ```rust let slice = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); assert!(array_ref.is_some()); let wrong_size_ref: Option<&[i32; 2]> = slice.as_array(); assert!(wrong_size_ref.is_none()); ``` -------------------------------- ### IpDefragPool::new Source: https://docs.rs/etherparse/latest/etherparse/defrag/struct.IpDefragPool.html Creates a new instance of IpDefragPool. ```APIDOC ## IpDefragPool::new ### Description Creates a new instance of IpDefragPool. ### Returns - `IpDefragPool` - A new IpDefragPool instance. ``` -------------------------------- ### Get Last Chunk of Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `last_chunk` with a const generic `N` to get an array reference to the last `N` elements. Returns `None` if the slice is too short. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Get First Chunk of Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `first_chunk` with a const generic `N` to get an array reference to the first `N` elements. Returns `None` if the slice is too short. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### Iterating over IPv4 Options Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html?search=std%3A%3Avec Demonstrates how to iterate over IPv4 options using an iterator, showing the start and end ranges of each option. ```APIDOC ## Example ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` ``` -------------------------------- ### Ipv4Options::new Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html?search=u32+-%3E+bool Creates a new, empty Ipv4Options instance. ```APIDOC ## Ipv4Options::new ### Description Setup an empty options array. ### Returns - `Ipv4Options`: An empty IPv4 options instance. ``` -------------------------------- ### Get Slice as Underlying Array Reference Source: https://docs.rs/etherparse/latest/etherparse/struct.TcpOptions.html?search=std%3A%3Avec Use `as_array` to attempt to get a reference to the underlying array if its length exactly matches `N`. Returns `None` if lengths do not match. ```rust let data = [1, 2, 3]; let slice = &data[..]; // This will succeed because N is 3, matching the slice length let array_ref: Option<&[i32; 3]> = slice.as_array::<3>(); assert!(array_ref.is_some()); // This will fail because N is 2, not matching the slice length let array_ref_fail: Option<&[i32; 2]> = slice.as_array::<2>(); assert!(array_ref_fail.is_none()); ``` -------------------------------- ### Example Searches for LaxEtherPayloadSlice Source: https://docs.rs/etherparse/latest/etherparse/struct.LaxEtherPayloadSlice.html?search= Demonstrates various ways to search within LaxEtherPayloadSlice, including searching for specific types, type conversions, and generic type transformations. ```APIDOC ## Example Searches This section provides examples of search queries that can be performed. ### Search Patterns - **Searching for a specific type:** `std::vec` - **Searching for type conversions:** `u32 -> bool` - **Searching for generic type transformations:** `Option, (T -> U) -> Option` ``` -------------------------------- ### Get meaningful sender address bytes Source: https://docs.rs/etherparse/latest/etherparse/struct.LinuxSllHeaderSlice.html Get the meaningful bytes of the slice of the link layer address. This returns only the relevant part of the sender address based on the length field. ```rust pub fn sender_address(&self) -> &'a [u8] ``` -------------------------------- ### Get Raw Pointer to Slice Buffer Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `as_ptr` to get a raw pointer to the slice's buffer. Ensure the slice outlives the pointer and the memory is not mutated through this pointer. ```rust let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` -------------------------------- ### VlanId::try_new Example Source: https://docs.rs/etherparse/latest/etherparse/struct.VlanId.html?search= Demonstrates creating a VlanId using try_new, which checks for valid 12-bit values. Shows successful creation and error handling for out-of-range values. ```rust use etherparse.VlanId; let vlanid = VlanId::try_new(2).unwrap(); assert_eq!(vlanid.value(), 2); // if a number that can not be represented in an 12 bit integer // gets passed in an error is returned use etherparse.err.{ValueTooBigError, ValueType}; assert_eq!( VlanId::try_new(VlanId::MAX_U16 + 1), Err(ValueTooBigError{ actual: VlanId::MAX_U16 + 1, max_allowed: VlanId::MAX_U16, value_type: ValueType::VlanId, }) ); ``` -------------------------------- ### Get Mutable Reference to Last N Items Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `last_chunk_mut` to get a mutable reference to the last N items of a slice. Returns `None` if the slice is shorter than N. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); assert_eq!(None, x.last_chunk_mut::<4>()); ``` -------------------------------- ### IpFragOffset Creation and Conversion Source: https://docs.rs/etherparse/latest/etherparse/struct.IpFragOffset.html Demonstrates creating an IpFragOffset from an integer using try_into and try_new, and converting it back to a u16. Also shows error handling for values exceeding the maximum allowed. ```rust use etherparse::IpFragOffset; // try into { let frag_offset: IpFragOffset = 123.try_into().unwrap(); assert_eq!(frag_offset.value(), 123); // fragment offset can always be converted back to an u16 let value: u16 = frag_offset.into(); assert_eq!(123, value); } // via try_new { let frag_offset = IpFragOffset::try_new(123).unwrap(); assert_eq!(frag_offset.value(), 123); // note that only 13 bit numbers are allowed ( // meaning // 0b0001_1111_1111_1111 is the maximum allowed value) use etherparse::err::{ValueTooBigError, ValueType}; assert_eq!( IpFragOffset::try_new(IpFragOffset::MAX_U16 + 1), Err(ValueTooBigError{ actual: IpFragOffset::MAX_U16 + 1, max_allowed: IpFragOffset::MAX_U16, value_type: ValueType::IpFragmentOffset, }) ); } ``` -------------------------------- ### Get Mutable Reference to Last Element Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `last_mut` to safely get a mutable reference to the last element, returning `None` for empty slices. Allows in-place modification. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### Split Off Slice Starting with Third Element (Mutable) Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Removes and returns a mutable reference to a subslice starting from the third element. The original mutable slice is updated to contain the preceding elements. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.split_off_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` -------------------------------- ### Iterating over IPv4 Options Ranges Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Demonstrates iterating through the ranges of IPv4 options. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### TryFrom for LinuxNonstandardEtherType Source: https://docs.rs/etherparse/latest/etherparse/struct.LinuxNonstandardEtherType.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Allows attempting to convert a u16 into a LinuxNonstandardEtherType, returning an error if the conversion fails. ```APIDOC ## type Error = () The type returned in the event of a conversion error. ``` ```APIDOC ## fn try_from(value: u16) -> Result Performs the conversion. ``` -------------------------------- ### Get Mutable First Chunk of Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Use `first_chunk_mut` with a const generic `N` to get a mutable array reference to the first `N` elements. Returns `None` if the slice is too short. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### MtuOptionSlice Methods Source: https://docs.rs/etherparse/latest/etherparse/icmpv6/struct.MtuOptionSlice.html?search= Provides methods for interacting with the MtuOptionSlice, including getting its length, creating it from a byte slice, retrieving the option type, accessing raw bytes, and getting the MTU value. ```APIDOC ## MtuOptionSlice etherparse::icmpv6 ### Struct MtuOptionSlice `pub struct MtuOptionSlice<'a>` MTU option slice (RFC 4861, Section 4.6.4, type 5). ### Implementations #### impl<'a> MtuOptionSlice<'a> ##### `pub const LEN: usize = 8` Serialized MTU option length in bytes. ##### `pub fn from_slice(slice: &'a [u8]) -> Result` Creates an `MtuOptionSlice` from a byte slice. ##### `pub const fn option_type(&self) -> NdpOptionType` Returns the option type value (5). ##### `pub fn as_bytes(&self) -> &'a [u8]` Returns the serialized option bytes. ##### `pub fn mtu(&self) -> u32` Returns the MTU value carried by the option. ``` -------------------------------- ### Ipv6FlowLabel Usage Examples Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv6FlowLabel.html?search= Demonstrates various ways to create and use the Ipv6FlowLabel struct, including conversion from u32, using try_new for safe creation, and new_unchecked for performance-critical scenarios where the value is guaranteed to be within limits. ```APIDOC ## Ipv6FlowLabel Struct Usage The `Ipv6FlowLabel` struct represents the 20-bit unsigned integer Flow Label in an IPv6 header. It provides methods for safe creation and conversion. ### Creating and Converting Ipv6FlowLabel #### Using `try_into()` This method attempts to convert a `u32` into an `Ipv6FlowLabel`. It returns a `Result` which will be `Ok` if the value is within the 20-bit limit, and `Err` otherwise. ```rust use etherparse::Ipv6FlowLabel; let flow_label: Ipv6FlowLabel = 123.try_into().unwrap(); assert_eq!(flow_label.value(), 123); let value: u32 = flow_label.into(); assert_eq!(123, value); ``` #### Using `try_new()` This is a safe constructor that takes a `u32` value and returns a `Result`. It ensures the provided value does not exceed the maximum allowed for a 20-bit flow label. ```rust use etherparse::Ipv6FlowLabel; use etherparse::err::{ValueTooBigError, ValueType}; let flow_label = Ipv6FlowLabel::try_new(123).unwrap(); assert_eq!(flow_label.value(), 123); // Example of an error case when the value is too large: assert_eq!( Ipv6FlowLabel::try_new(Ipv6FlowLabel::MAX_U32 + 1), Err(ValueTooBigError{ actual: Ipv6FlowLabel::MAX_U32 + 1, max_allowed: Ipv6FlowLabel::MAX_U32, value_type: ValueType::Ipv6FlowLabel, }) ); ``` #### Using `new_unchecked()` This is an `unsafe` constructor that bypasses the bounds check. It should only be used when you are certain that the provided `u32` value is within the valid 20-bit range (0 to `Ipv6FlowLabel::MAX_U32`). ```rust use etherparse::Ipv6FlowLabel; // Safety: Ensure the value is not greater than Ipv6FlowLabel::MAX_U32 let flow_label = unsafe { Ipv6FlowLabel::new_unchecked(123) }; assert_eq!(flow_label.value(), 123); ``` ### Constants - `Ipv6FlowLabel::MAX_U32`: The maximum value a 20-bit flow label can hold. ``` -------------------------------- ### Get Mutable Slice to Array Source: https://docs.rs/etherparse/latest/etherparse/struct.Ipv4Options.html Attempts to get a mutable reference to the slice’s underlying array if the requested size `N` exactly matches the slice length. Returns `None` otherwise. ```Rust let mut slice = [1, 2, 3]; let array: Option<&mut [i32; 3]> = slice.as_mut_array(); if let Some(arr) = array { arr[0] = 10; } assert_eq!(slice[0], 10); ``` -------------------------------- ### Example Searches for LaxPayloadSlice Source: https://docs.rs/etherparse/latest/etherparse/enum.LaxPayloadSlice.html?search= Demonstrates various ways to search within LaxPayloadSlice, including searching for specific types, type conversions, and generic type manipulations. ```APIDOC ## Example Searches ### Search for a specific type ``` std::vec ``` ### Search for type conversion ``` u32 -> bool ``` ### Search for generic type conversion with Option ``` Option, (T -> U) -> Option ``` ``` -------------------------------- ### Example: Parsing PacketHeaders from IP Slice Source: https://docs.rs/etherparse/latest/etherparse/struct.PacketHeaders.html?search=std%3A%3Avec Illustrates how to use PacketHeaders::from_ip_slice to decode an IP packet and its transport headers, assuming the input slice begins with the IP header. Displays how to inspect the parsed header fields. ```rust use etherparse::PacketHeaders; match PacketHeaders::from_ip_slice(&packet) { Err(value) => println!("Err {:?}", value), Ok(value) => { println!("link: {:?}", value.link); println!("link_exts: {:?}", value.link_exts); // vlan & macsec println!("net: {:?}", value.net); // ip & arp println!("transport: {:?}", value.transport); } } ```