pnet_base-0.35.0/.cargo_vcs_info.json0000644000000001470000000000100130630ustar { "git": { "sha1": "97ece70e2f87744f2ab47b4177c3888289f89a8f" }, "path_in_vcs": "pnet_base" }pnet_base-0.35.0/Cargo.toml0000644000000023350000000000100110620ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "pnet_base" version = "0.35.0" authors = [ "Robert Clipsham ", "Linus Färnstrand ", ] description = "Fundamental base types and code used by pnet." homepage = "https://github.com/libpnet/libpnet" readme = "README.md" keywords = [ "networking", "ethernet", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/libpnet/libpnet" [package.metadata.docs.rs] features = ["serde"] [dependencies.no-std-net] version = "0.6.0" default-features = false [dependencies.serde] version = "1.0.171" optional = true default-features = false [dev-dependencies.serde_test] version = "1.0.171" [features] default = ["std"] std = ["no-std-net/std"] pnet_base-0.35.0/Cargo.toml.orig000064400000000000000000000015041046102023000145400ustar 00000000000000[package] name = "pnet_base" version = "0.35.0" authors = ["Robert Clipsham ", "Linus Färnstrand "] license = "MIT OR Apache-2.0" homepage = "https://github.com/libpnet/libpnet" repository = "https://github.com/libpnet/libpnet" description = "Fundamental base types and code used by pnet." readme = "../README.md" keywords = ["networking", "ethernet"] categories = ["network-programming"] edition = "2021" [dependencies] no-std-net = { version = "0.6.0", default-features = false } serde = { version = "1.0.171", optional = true, default-features = false } [dev-dependencies] serde_test = "1.0.171" [features] std = ["no-std-net/std"] default = ["std"] [package.metadata.docs.rs] # Enable the serde feature when generating docs on docs.rs, so the traits are visible features = ["serde"] pnet_base-0.35.0/LICENSE-APACHE000064400000000000000000000251371046102023000136050ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pnet_base-0.35.0/LICENSE-MIT000064400000000000000000000020501046102023000133020ustar 00000000000000Copyright (c) 2014-2016 Robert Clipsham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pnet_base-0.35.0/README.md000064400000000000000000000101641046102023000131320ustar 00000000000000# libpnet [![Crates.io](https://img.shields.io/crates/v/pnet.svg)](https://crates.io/crates/pnet) ![License](https://img.shields.io/crates/l/pnet.svg) [![Documentation](https://docs.rs/pnet/badge.svg)](https://docs.rs/pnet/) Build Status: [![Build Status](https://github.com/libpnet/libpnet/actions/workflows/ci.yml/badge.svg)](https://github.com/libpnet/libpnet/actions/workflows/ci.yml) Discussion and support: * Live chat on IRC - [#libpnet on irc.libera.chat](https://kiwiirc.com/nextclient/irc.libera.chat/libpnet?nick=pnet-user42) * [GitHub Discussions](https://github.com/libpnet/libpnet/discussions) `libpnet` provides a cross-platform API for low level networking using Rust. There are four key components: * The `packet` module, allowing safe construction and manipulation of packets; * The `pnet_macros` crate, providing infrastructure for the packet module; * The `transport` module, which allows implementation of transport protocols; * The `datalink` module, which allows sending and receiving data link packets directly. ## Why? There are lots of reasons to use low level networking, and many more to do it using Rust. A few are outlined here: ### Developing Transport Protocols There are usually two ways to go about developing a new transport layer protocol: * Write it in a scripting language such as Python; * Write it using C. The former is great for trying out new ideas and rapid prototyping, however not so great as a real-world implementation. While you can usually get reasonable performance out of these implementations, they're generally significantly slower than an implementation in C, and not suitable for any "heavy lifting". The next option is to write it in C - this will give you great performance, but comes with a number of other issues: * Lack of memory safety - this is a huge source of security vulnerabilities and other bugs in C-based network stacks. It is far too easy to forget a bounds check or use a pointer after it is freed. * Lack of thread safety - you have to be very careful to make sure the correct locks are used, and used correctly. * Lack of high level abstractions - part of the appeal of scripting languages such as Python is the higher level of abstraction which enables simpler APIs and ease of programming. Using `libpnet` and Rust, you get the best of both worlds. The higher level abstractions, memory and thread safety, alongside the performance of C. ### Network Utilities Many networking utilities such as ping and traceroute rely on being able to manipulate network and transport headers, which isn't possible with standard networking stacks such as those provided by `std::io::net`. ### Data Link Layer It can be useful to work directly at the data link layer, to see packets as they are "on the wire". There are lots of uses for this, including network diagnostics, packet capture and traffic shaping. ## Documentation API documentation for the latest build can be found here: https://docs.rs/pnet/ ## Usage To use `libpnet` in your project, add the following to your Cargo.toml: ``` [dependencies.pnet] version = "0.35.0" ``` `libpnet` should work with the latest stable version of Rust. When running the test suite, there are a number of networking tests which will likely fail - the easiest way to workaround this is to run `cargo test` as a root or administrative user. This can often be avoided, however it is more involved. ### Windows There are three requirements for building on Windows: * You must use a version of Rust which uses the MSVC toolchain * You must have [WinPcap](https://www.winpcap.org/) or [npcap](https://nmap.org/npcap/) installed (tested with version WinPcap 4.1.3) (If using npcap, make sure to install with the "Install Npcap in WinPcap API-compatible Mode") * You must place `Packet.lib` from the [WinPcap Developers pack](https://www.winpcap.org/devel.htm) in a directory named `lib`, in the root of this repository. Alternatively, you can use any of the locations listed in the `%LIB%`/`$Env:LIB` environment variables. For the 64 bit toolchain it is in `WpdPack/Lib/x64/Packet.lib`, for the 32 bit toolchain, it is in `WpdPack/Lib/Packet.lib`. pnet_base-0.35.0/src/lib.rs000064400000000000000000000010771046102023000135610ustar 00000000000000// Copyright (c) 2014-2016 Robert Clipsham // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(warnings)] #![cfg_attr(all(not(test), not(feature = "std")), no_std)] #[cfg(feature = "serde")] extern crate serde; mod macaddr; pub use crate::macaddr::*; pub use no_std_net as core_net; pnet_base-0.35.0/src/macaddr.rs000064400000000000000000000274551046102023000144160ustar 00000000000000// Copyright (c) 2014-2016 Robert Clipsham // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(feature = "std")] use std::error::Error; use core::fmt; use core::str::FromStr; #[cfg(feature = "serde")] use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; /// The number of bytes in an ethernet (MAC) address. pub const ETHER_ADDR_LEN: usize = 6; /// Structure of a 48-bit Ethernet address. type EtherAddr = [u8; ETHER_ADDR_LEN]; const LOCAL_ADDR_BIT: u8 = 0x02; const MULTICAST_ADDR_BIT: u8 = 0x01; /// A MAC address. #[derive(PartialEq, Eq, Clone, Copy, Default, Hash, Ord, PartialOrd)] pub struct MacAddr(pub u8, pub u8, pub u8, pub u8, pub u8, pub u8); impl MacAddr { /// Construct a new `MacAddr` instance. pub fn new(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) -> MacAddr { MacAddr(a, b, c, d, e, f) } /// Construct an all-zero `MacAddr` instance. pub fn zero() -> MacAddr { Default::default() } /// Construct a broadcast `MacAddr` instance. pub fn broadcast() -> MacAddr { [0xff; ETHER_ADDR_LEN].into() } /// Returns true if a `MacAddr` is an all-zero address. pub fn is_zero(&self) -> bool { *self == Self::zero() } /// Returns true if the MacAddr is a universally administered addresses (UAA). pub fn is_universal(&self) -> bool { !self.is_local() } /// Returns true if the MacAddr is a locally administered addresses (LAA). pub fn is_local(&self) -> bool { (self.0 & LOCAL_ADDR_BIT) == LOCAL_ADDR_BIT } /// Returns true if the MacAddr is a unicast address. pub fn is_unicast(&self) -> bool { !self.is_multicast() } /// Returns true if the MacAddr is a multicast address. pub fn is_multicast(&self) -> bool { (self.0 & MULTICAST_ADDR_BIT) == MULTICAST_ADDR_BIT } /// Returns true if the MacAddr is a broadcast address. pub fn is_broadcast(&self) -> bool { *self == Self::broadcast() } /// Returns the six eight-bit integers that make up this address pub fn octets(&self) -> [u8; 6] { [self.0, self.1, self.2, self.3, self.4, self.5] } } impl From for MacAddr { fn from(addr: EtherAddr) -> MacAddr { MacAddr(addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]) } } impl From for EtherAddr { fn from(addr: MacAddr) -> Self { [addr.0, addr.1, addr.2, addr.3, addr.4, addr.5] } } impl PartialEq for MacAddr { fn eq(&self, other: &EtherAddr) -> bool { *self == MacAddr::from(*other) } } impl fmt::Display for MacAddr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.0, self.1, self.2, self.3, self.4, self.5 ) } } #[cfg(feature = "serde")] impl Serialize for MacAddr { /// Serializes the MAC address. /// /// It serializes either to a string or its binary representation, depending on what the format /// prefers. fn serialize(&self, serializer: S) -> Result { if serializer.is_human_readable() { serializer.collect_str(self) } else { serializer.serialize_bytes(&[self.0, self.1, self.2, self.3, self.4, self.5]) } } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for MacAddr { /// Deserializes the MAC address. /// /// It deserializes it from either a byte array (of size 6) or a string. If the format is /// self-descriptive (like JSON or MessagePack), it auto-detects it. If not, it obeys the /// human-readable property of the deserializer. fn deserialize>(deserializer: D) -> Result { struct MacAddrVisitor; impl<'de> de::Visitor<'de> for MacAddrVisitor { type Value = MacAddr; fn visit_str(self, value: &str) -> Result { value.parse().map_err(|err| E::custom(err)) } fn visit_bytes(self, v: &[u8]) -> Result { if v.len() == 6 { Ok(MacAddr::new(v[0], v[1], v[2], v[3], v[4], v[5])) } else { Err(E::invalid_length(v.len(), &self)) } } fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!( formatter, "either a string representation of a MAC address or 6-element byte array" ) } } // Decide what hint to provide to the deserializer based on if it is human readable or not if deserializer.is_human_readable() { deserializer.deserialize_str(MacAddrVisitor) } else { deserializer.deserialize_bytes(MacAddrVisitor) } } } impl fmt::Debug for MacAddr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, fmt) } } /// Represents an error which occurred whilst parsing a MAC address. #[derive(Copy, Debug, PartialEq, Eq, Clone)] pub enum ParseMacAddrErr { /// The MAC address has too many components, eg. 00:11:22:33:44:55:66. TooManyComponents, /// The MAC address has too few components, eg. 00:11. TooFewComponents, /// One of the components contains an invalid value, eg. 00:GG:22:33:44:55. InvalidComponent, } #[cfg(feature = "std")] impl Error for ParseMacAddrErr {} impl ParseMacAddrErr { fn description(&self) -> &str { match *self { ParseMacAddrErr::TooManyComponents => "Too many components in a MAC address string", ParseMacAddrErr::TooFewComponents => "Too few components in a MAC address string", ParseMacAddrErr::InvalidComponent => "Invalid component in a MAC address string", } } } impl fmt::Display for ParseMacAddrErr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl FromStr for MacAddr { type Err = ParseMacAddrErr; fn from_str(s: &str) -> Result { let mut parts = [0u8; 6]; let splits = s.split(':'); let mut i = 0; for split in splits { if i == 6 { return Err(ParseMacAddrErr::TooManyComponents); } match u8::from_str_radix(split, 16) { Ok(b) if split.len() != 0 => parts[i] = b, _ => return Err(ParseMacAddrErr::InvalidComponent), } i += 1; } if i == 6 { Ok(MacAddr( parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], )) } else { Err(ParseMacAddrErr::TooFewComponents) } } } #[cfg(test)] mod tests { use super::*; #[test] fn mac_addr_from_str() { assert_eq!("00:00:00:00:00:00".parse(), Ok(MacAddr::zero())); assert_eq!("ff:ff:ff:ff:ff:ff".parse(), Ok(MacAddr::broadcast())); assert_eq!( "12:34:56:78:90:ab".parse(), Ok(MacAddr(0x12, 0x34, 0x56, 0x78, 0x90, 0xAB)) ); assert_eq!( "::::::".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); assert_eq!( "0::::::".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); assert_eq!( "::::0::".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); assert_eq!( "12:34:56:78".parse::(), Err(ParseMacAddrErr::TooFewComponents) ); assert_eq!( "12:34:56:78:".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); assert_eq!( "12:34:56:78:90".parse::(), Err(ParseMacAddrErr::TooFewComponents) ); assert_eq!( "12:34:56:78:90:".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); assert_eq!( "12:34:56:78:90:00:00".parse::(), Err(ParseMacAddrErr::TooManyComponents) ); assert_eq!( "xx:xx:xx:xx:xx:xx".parse::(), Err(ParseMacAddrErr::InvalidComponent) ); } #[test] fn str_from_mac_addr() { assert_eq!(format!("{}", MacAddr::zero()), "00:00:00:00:00:00"); assert_eq!(format!("{}", MacAddr::broadcast()), "ff:ff:ff:ff:ff:ff"); assert_eq!( format!("{}", MacAddr(0x12, 0x34, 0x56, 0x78, 0x09, 0xAB)), "12:34:56:78:09:ab" ); } #[test] fn fixed_size_slice_from_mac_addr() { assert_eq!( MacAddr(0x00, 0x01, 0x02, 0x03, 0x04, 0x05).octets(), [0x00, 0x01, 0x02, 0x03, 0x04, 0x05] ); } #[test] fn type_of_addr() { assert!(MacAddr::zero().is_zero()); assert!(MacAddr::broadcast().is_broadcast()); let mac = MacAddr(0x12, 0x34, 0x56, 0x78, 0x90, 0xAB); assert!(mac.is_local()); assert!(mac.is_unicast()); let mac = MacAddr(0xac, 0x87, 0xa3, 0x07, 0x32, 0xb8); assert!(mac.is_universal()); assert!(mac.is_unicast()); } #[test] fn conversion() { let mac = MacAddr(0x12, 0x34, 0x56, 0x78, 0x90, 0xAB); let addr = [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB]; assert_eq!(mac, MacAddr::from(addr)); assert_eq!(addr, EtherAddr::from(mac)); assert!(mac == addr); } #[cfg(feature = "serde")] mod serde { extern crate serde_test; use self::serde_test::{ assert_de_tokens, assert_de_tokens_error, assert_tokens, Compact, Configure, Readable, Token, }; use super::*; #[test] fn string() { let mac = MacAddr::new(0x11, 0x22, 0x33, 0x44, 0x55, 0x66); assert_tokens(&mac.readable(), &[Token::Str("11:22:33:44:55:66")]); assert_de_tokens(&mac.readable(), &[Token::String("11:22:33:44:55:66")]); assert_de_tokens(&mac.readable(), &[Token::BorrowedStr("11:22:33:44:55:66")]); assert_de_tokens_error::>( &[Token::Str("not an address")], "Invalid component in a MAC address string", ); // It still can detect bytes if provided assert_de_tokens( &mac.readable(), &[Token::Bytes(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66])], ); } #[test] fn bytes() { let mac = MacAddr::new(0x11, 0x22, 0x33, 0x44, 0x55, 0x66); assert_tokens( &mac.compact(), &[Token::Bytes(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66])], ); assert_de_tokens( &mac.compact(), &[Token::BorrowedBytes(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66])], ); let err = "invalid length 2, expected either a string representation of a MAC address or 6-element byte array"; assert_de_tokens_error::>(&[Token::Bytes(&[0x11, 0x33])], err); let err = "invalid length 7, expected either a string representation of a MAC address or 6-element byte array"; assert_de_tokens_error::>( &[Token::Bytes(&[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77])], err, ); // Still can decode string in the compact mode assert_de_tokens(&mac.compact(), &[Token::Str("11:22:33:44:55:66")]); } } }