eui48-1.1.0/.cargo_vcs_info.json0000644000000001121372100205700120160ustar { "git": { "sha1": "7a72ad41e34470dae157bbb5418a5e343f23cda4" } } eui48-1.1.0/.github/workflows/rust.yml010066600017500001750000000004331370270663200157570ustar 00000000000000name: Rust on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose eui48-1.1.0/.github/workflows/stale.yml010066600017500001750000000006441370270663200160760ustar 00000000000000name: Mark stale issues and pull requests on: schedule: - cron: "0 0 * * *" jobs: stale: runs-on: ubuntu-latest steps: - uses: actions/stale@v1 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: 'Stale issue message' stale-pr-message: 'Stale pull request message' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity' eui48-1.1.0/Cargo.toml0000644000000037631372100205700100330ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "eui48" version = "1.1.0" authors = ["Andrew Baumhauer ", "", "Michal 'vorner' Vaner ", "Stan Drozd "] exclude = [".gitignore", ".travis.yml", ".gitlab-ci.yml", ".travis/*"] description = "A library to generate and parse IEEE EUI-48 and EUI-64, also known as MAC-48 media access\ncontrol addresses. The IEEE claims trademarks on the names EUI-48 and EUI-64, in which EUI is an\nabbreviation for Extended Unique Identifier.\n" homepage = "https://github.com/abaumhauer/eui48" readme = "README.md" keywords = ["EUI-48", "MAC", "MAC-48", "networking", "MACADDR"] categories = ["network-programming", "parser-implementations"] license = "MIT/Apache-2.0" repository = "https://github.com/abaumhauer/eui48" [dependencies.regex] version = "1.3.9" optional = false [dependencies.rustc-serialize] version = "0.3.24" optional = true [dependencies.serde] version = "1.0.114" optional = true [dependencies.serde_json] version = "1.0.56" optional = true [dev-dependencies.bincode] version = "1.3.1" [features] default = ["rustc-serialize"] disp_hexstring = [] serde_bytes = ["serde"] [badges.appveyor] branch = "master" repository = "abaumhauer/eui48" service = "github" [badges.codecov] branch = "master" repository = "abaumhauer/eui48" service = "github" [badges.gitlab] branch = "master" repository = "abaumhauer/eui48" [badges.travis-ci] branch = "master" repository = "abaumhauer/eui48" eui48-1.1.0/Cargo.toml.orig010064400017500001750000000027721372100101700135170ustar 00000000000000[package] name = "eui48" version = "1.1.0" authors = ["Andrew Baumhauer ", "", "Michal 'vorner' Vaner ", "Stan Drozd " ] license = "MIT/Apache-2.0" edition = "2018" readme = "README.md" repository = "https://github.com/abaumhauer/eui48" homepage = "https://github.com/abaumhauer/eui48" keywords = ["EUI-48", "MAC", "MAC-48", "networking", "MACADDR"] categories = ["network-programming", "parser-implementations"] description = """ A library to generate and parse IEEE EUI-48 and EUI-64, also known as MAC-48 media access control addresses. The IEEE claims trademarks on the names EUI-48 and EUI-64, in which EUI is an abbreviation for Extended Unique Identifier. """ exclude = [ ".gitignore", ".travis.yml", ".gitlab-ci.yml", ".travis/*" ] [dependencies] regex = { version = "1.3.9", optional = false } rustc-serialize = { version = "0.3.24", optional = true } serde = { version = "1.0.114", optional = true } serde_json = { version = "1.0.56", optional = true } [dev-dependencies] bincode = "1.3.1" [badges] travis-ci = { repository = "abaumhauer/eui48", branch = "master" } codecov = { repository = "abaumhauer/eui48", branch = "master", service = "github" } gitlab = { repository = "abaumhauer/eui48", branch = "master" } appveyor = { repository = "abaumhauer/eui48", branch = "master", service = "github" } [features] default = ["rustc-serialize"] disp_hexstring = [] serde_bytes = ["serde"] eui48-1.1.0/LICENSE-APACHE010066400017500001750000000251371370041236300125650ustar 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. eui48-1.1.0/LICENSE-MIT010066400017500001750000000017771370041236400123020ustar 00000000000000Permission 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. eui48-1.1.0/README.md010064400017500001750000000110471372100101700121020ustar 00000000000000[![Crates.io](https://img.shields.io/crates/v/eui48.svg)](https://crates.io/crates/eui48) [![docs.rs](https://docs.rs/eui48/badge.svg)](https://docs.rs/eui48) [![Build Status](https://ci.appveyor.com/api/projects/status/github/abaumhauer/eui48?branch=master&svg=true)](https://ci.appveyor.com/project/abaumhauer/eui48/branch/master) [![Build Status](https://gitlab.com/abaumhauer/eui48/badges/master/build.svg)](https://gitlab.com/abaumhauer/eui48/commits/master) [![Build Status](https://travis-ci.org/abaumhauer/eui48.svg?branch=master)](https://travis-ci.org/abaumhauer/eui48) [![Coverage Status](https://codecov.io/gh/abaumhauer/eui48/branch/master/graph/badge.svg)](https://codecov.io/gh/abaumhauer/eui48) eui48 ==== A Rust library to represent and parse IEEE EUI-48 also known as MAC-48 media access control addresses. The IEEE claims trademarks on the names EUI-48 and EUI-64, in which EUI is an abbreviation for Extended Unique Identifier. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] eui48 = "1.0.1" ``` and this to your crate root: ```rust extern crate eui48; ``` ## Examples To create a new MAC address and print it out in canonical form: ```rust extern crate eui48; use eui48::{MacAddress, Eui48}; fn main() { let eui: Eui48 = [ 0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF ]; let mac = MacAddress::new( eui ); println!("{}", mac.to_canonical()); println!("{}", mac.to_hex_string()); println!("{}", mac.to_dot_string()); println!("{}", mac.to_hexadecimal()); println!("{}", mac.to_interfaceid()); println!("{}", mac.to_link_local()); let mac = MacAddress::parse_str( "01-02-03-0A-0b-0f" ).expect("Parse error {}"); let mac = MacAddress::parse_str( "01:02:03:0A:0b:0f" ).expect("Parse error {}"); let mac = MacAddress::parse_str( "0102.030A.0b0f" ).expect("Parse error {}"); let mac = MacAddress::parse_str( "0x1234567890ab" ).expect("Parse error {}"); } ``` ## Notes * The default display format is cannonical form `01-02-03-04-05-06` unless a compile time feature `disp_hexstring` is enabled, then the default format is of the form `01:02:03:04:05:06`. Version 1.0.0 and above allows a more flexible parsing of MAC address strings, compliments of Stan Drozd: * Enables the library's caller to parse the MACs that don't follow fixed-length MAC address convention (I'm looking at you, ebtables!). In general, the parsing function tries harder to interpret a given string than before. * Rewrite parse_str to use a regex and be more lenient (now it permits one-off string chopping errors and mixed delimiters are accepted as long as we manage to read 6 bytes) * Exchange the InvalidCharacter error enum value for InvalidByteCount - InvalidCharacter is no longer supported. See versions >=0.5.0 and < 1.0.0 if you need legacy behavior. ## Serialization When using `serde` to serialize a MAC address the address is stored as a formatted string. This fits well for text-based protocols like JSON but creates overhead for binary serialization. The overhead gets even bigger when the string is deserialized again, as a full-grown parser is needed instead of reading raw bytes. To reduce this overhead use the `serde_bytes` feature when serializing and deserializing MAC addresses to binary protocols. NOTE: `serde_bytes` and `serde_json` are mutually exclusive! ## References [Wikipedia: MAC address](https://en.wikipedia.org/wiki/MAC_address) ## Authors - 0.1 Andrew Baumhauer - Initial design - 0.2 rlcomstock3 - Added support for btree keys - 0.3 Michal 'vorner' Vaner - Serde 1.0 support - 0.3.1 Michal 'vorner' Vaner - Derive useful traits - 0.4.0 Rainer Stademann - Define ABI as repr(C) - 0.4.1 Andrew Baumhauer - Add IPv6 Interface ID and Link Local conversions - 0.4.2 Andrew Baumhauer / Eric Clone - Bug fix in is_local() and is_unicast() functions - 0.4.3 Andrew Baumhauer - Update travis-ci, appveyor, codecov - 0.4.4 Andrew Baumhauer - Update documentation - 0.4.5 Andrew Baumhauer - Improve code coverage and tests - 0.4.6 Jiwoong Lee - Add to_array() for compatibility, add feature disp_hexstring - 0.4.7 Adam Reichold - WASM updates - 0.4.8 @kamek-pf - respect disp_hexstring flag - 0.4.9 Sebastian Dietze - New const added - 0.5.0 Andrew Baumhauer - cleanup, update versions, fmt, merge PRs, update unit tests - 0.5.1 jrb0001 - Fixed incorrect IPv6 to_link_local for Link-Scoped Unicast - 1.0.0 Stan Drozd, @rlcomstock3, and Andrew Baumhauer - merged all forks and improvements back to this repo - 1.0.1 jrb0001 - Fixed incorrect IPv6 to_link_local for Link-Scoped Unicast - 1.1.0 Felix Schreiner - binary serialization optimization eui48-1.1.0/README.tpl010066400017500001750000000010211370041236300123010ustar 00000000000000[![Crates.io](https://img.shields.io/crates/v/eui48.svg)](https://crates.io/crates/eui48) [![docs.rs](https://docs.rs/eui48/badge.svg)](https://docs.rs/eui48) {{badges}} # {{crate}} {{readme}} ## License Licensed under the MIT/Apache-2.0 licenses. Please see the LICENSE-Apache and LICENSE-MIT files for more information. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be licensed as above, without any additional terms or conditions. eui48-1.1.0/appveyor.yml010066400017500001750000000102011370041236400132140ustar 00000000000000# Appveyor configuration template for Rust using rustup for Rust installation # https://github.com/starkat99/appveyor-rust ## Operating System (VM environment) ## # Rust needs at least Visual Studio 2013 Appveyor OS for MSVC targets. os: Visual Studio 2015 ## Build Matrix ## # This configuration will setup a build for each channel & target combination (12 windows # combinations in all). # # There are 3 channels: stable, beta, and nightly. # # Alternatively, the full version may be specified for the channel to build using that specific # version (e.g. channel: 1.5.0) # # The values for target are the set of windows Rust build targets. Each value is of the form # # ARCH-pc-windows-TOOLCHAIN # # Where ARCH is the target architecture, either x86_64 or i686, and TOOLCHAIN is the linker # toolchain to use, either msvc or gnu. See https://www.rust-lang.org/downloads.html#win-foot for # a description of the toolchain differences. # See https://github.com/rust-lang-nursery/rustup.rs/#toolchain-specification for description of # toolchains and host triples. # # Comment out channel/target combos you do not wish to build in CI. # # You may use the `cargoflags` and `RUSTFLAGS` variables to set additional flags for cargo commands # and rustc, respectively. For instance, you can uncomment the cargoflags lines in the nightly # channels to enable unstable features when building for nightly. Or you could add additional # matrix entries to test different combinations of features. environment: matrix: ### MSVC Toolchains ### # Stable 64-bit MSVC - channel: stable target: x86_64-pc-windows-msvc # Stable 32-bit MSVC - channel: stable target: i686-pc-windows-msvc # Beta 64-bit MSVC - channel: beta target: x86_64-pc-windows-msvc # Beta 32-bit MSVC - channel: beta target: i686-pc-windows-msvc # Nightly 64-bit MSVC - channel: nightly target: x86_64-pc-windows-msvc #cargoflags: --features "unstable" # Nightly 32-bit MSVC - channel: nightly target: i686-pc-windows-msvc #cargoflags: --features "unstable" ### GNU Toolchains ### # Stable 64-bit GNU - channel: stable target: x86_64-pc-windows-gnu # Stable 32-bit GNU - channel: stable target: i686-pc-windows-gnu # Beta 64-bit GNU - channel: beta target: x86_64-pc-windows-gnu # Beta 32-bit GNU - channel: beta target: i686-pc-windows-gnu # Nightly 64-bit GNU - channel: nightly target: x86_64-pc-windows-gnu #cargoflags: --features "unstable" # Nightly 32-bit GNU - channel: nightly target: i686-pc-windows-gnu #cargoflags: --features "unstable" ### Allowed failures ### # See Appveyor documentation for specific details. In short, place any channel or targets you wish # to allow build failures on (usually nightly at least is a wise choice). This will prevent a build # or test failure in the matching channels/targets from failing the entire build. matrix: allow_failures: - channel: nightly # If you only care about stable channel build failures, uncomment the following line: #- channel: beta ## Install Script ## # This is the most important part of the Appveyor configuration. This installs the version of Rust # specified by the 'channel' and 'target' environment variables from the build matrix. This uses # rustup to install Rust. # # For simple configurations, instead of using the build matrix, you can simply set the # default-toolchain and default-host manually here. install: - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - rustup-init -yv --default-toolchain %channel% --default-host %target% - set PATH=%PATH%;%USERPROFILE%\.cargo\bin - rustc -vV - cargo -vV ## Build Script ## # 'cargo test' takes care of building for us, so disable Appveyor's build stage. This prevents # the "directory does not contain a project or solution file" error. build: false # Uses 'cargo test' to run tests and build. Alternatively, the project may call compiled programs #directly or perform other testing commands. Rust will automatically be placed in the PATH # environment variable. test_script: - cargo test --verbose %cargoflags% eui48-1.1.0/src/lib.rs010064400017500001750000000635711372100101700125370ustar 00000000000000// Copyright 2016 Andrew Baumhauer // // 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. //! Represent and parse IEEE EUI-48 Media Access Control addresses //! The IEEE claims trademarks on the names EUI-48 and EUI-64, in which EUI is an //! abbreviation for Extended Unique Identifier. #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/eui48/" )] extern crate regex; #[cfg(feature = "rustc-serialize")] extern crate rustc_serialize; #[cfg(feature = "serde")] extern crate serde; #[cfg(feature = "serde_json")] extern crate serde_json; use std::default::Default; use std::error::Error; use std::fmt; use std::str::FromStr; use regex::Regex; #[cfg(feature = "rustc-serialize")] use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; #[cfg(feature = "serde")] use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; /// A 48-bit (6 byte) buffer containing the EUI address pub const EUI48LEN: usize = 6; pub type Eui48 = [u8; EUI48LEN]; /// A 64-bit (8 byte) buffer containing the EUI address pub const EUI64LEN: usize = 8; pub type Eui64 = [u8; EUI64LEN]; /// A MAC address (EUI-48) #[repr(C)] #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct MacAddress { /// The 48-bit number stored in 6 bytes eui: Eui48, } #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] /// Format to display MacAddress pub enum MacAddressFormat { /// Use - notaion Canonical, /// Use : notation HexString, /// Use . notation DotNotation, /// Use 0x notation Hexadecimal, } #[derive(PartialEq, Eq, Copy, Clone, Debug, Ord, PartialOrd, Hash)] /// Parsing errors pub enum ParseError { /// Length is incorrect (should be 11 to 17) InvalidLength(usize), /// The input string is invalid, usize bytes were found, and we put up to 6 bytes into Eui48 InvalidByteCount(usize, Eui48), } impl MacAddress { /// Create a new MacAddress from `[u8; 6]`. pub const fn new(eui: Eui48) -> MacAddress { MacAddress { eui } } /// Create a new MacAddress from a byte slice. /// /// Returns an error (without any description) if the slice doesn't have the proper length. pub fn from_bytes(bytes: &[u8]) -> Result { if bytes.len() != EUI48LEN { return Err(ParseError::InvalidLength(bytes.len())); } let mut input: [u8; EUI48LEN] = Default::default(); input[..EUI48LEN].clone_from_slice(&bytes[..EUI48LEN]); Ok(Self::new(input)) } /// Returns empty EUI-48 address pub fn nil() -> MacAddress { MacAddress { eui: [0; EUI48LEN] } } /// Returns 'ff:ff:ff:ff:ff:ff', a MAC broadcast address pub fn broadcast() -> MacAddress { MacAddress { eui: [0xFF; EUI48LEN], } } /// Returns true if the address is '00:00:00:00:00:00' pub fn is_nil(&self) -> bool { self.eui.iter().all(|&b| b == 0) } /// Returns true if the address is 'ff:ff:ff:ff:ff:ff' pub fn is_broadcast(&self) -> bool { self.eui.iter().all(|&b| b == 0xFF) } /// Returns true if bit 1 of Y is 0 in address 'xY:xx:xx:xx:xx:xx' pub fn is_unicast(&self) -> bool { self.eui[0] & 1 == 0 } /// Returns true if bit 1 of Y is 1 in address 'xY:xx:xx:xx:xx:xx' pub fn is_multicast(&self) -> bool { self.eui[0] & 1 == 1 } /// Returns true if bit 2 of Y is 0 in address 'xY:xx:xx:xx:xx:xx' pub fn is_universal(&self) -> bool { self.eui[0] & 1 << 1 == 0 } /// Returns true if bit 2 of Y is 1 in address 'xY:xx:xx:xx:xx:xx' pub fn is_local(&self) -> bool { self.eui[0] & 1 << 1 == 2 } /// Returns a String representation in the format '00-00-00-00-00-00' pub fn to_canonical(&self) -> String { format!( "{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}", self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String representation in the format '00:00:00:00:00:00' pub fn to_hex_string(&self) -> String { format!( "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String representation in the format '0000.0000.0000' pub fn to_dot_string(&self) -> String { format!( "{:02x}{:02x}.{:02x}{:02x}.{:02x}{:02x}", self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String representation in the format '0x000000000000' pub fn to_hexadecimal(&self) -> String { format!( "0x{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", self.eui[0], self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String representation in the EUI-64 interface ID format '0000:00ff:fe00:0000' pub fn to_interfaceid(&self) -> String { format!( "{:02x}{:02x}:{:02x}ff:fe{:02x}:{:02x}{:02x}", (self.eui[0] ^ 0x02), self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String representation in the IPv6 link local format 'fe80::0000:00ff:fe00:0000' pub fn to_link_local(&self) -> String { format!( "fe80::{:02x}{:02x}:{:02x}ff:fe{:02x}:{:02x}{:02x}", (self.eui[0] ^ 0x02), self.eui[1], self.eui[2], self.eui[3], self.eui[4], self.eui[5] ) } /// Returns a String in the format selected by fmt pub fn to_string(&self, fmt: MacAddressFormat) -> String { match fmt { MacAddressFormat::Canonical => self.to_canonical(), MacAddressFormat::HexString => self.to_hex_string(), MacAddressFormat::DotNotation => self.to_dot_string(), MacAddressFormat::Hexadecimal => self.to_hexadecimal(), } } /// Parses a String representation from any format supported pub fn parse_str(s: &str) -> Result { let re = Regex::new("(0x)?([0-9a-fA-F]{1,2})[:.-]?").unwrap(); let mut eui: Eui48 = [0; EUI48LEN]; match s.len() { 11..=17 => {} _ => { return Err(ParseError::InvalidLength(s.len())); } } let mut i = 0; for caps in re.captures_iter(s) { // Fill the array and keep counting for InvalidByteCount if i < EUI48LEN { let matched_byte = caps.get(2).unwrap().as_str(); eui[i] = u8::from_str_radix(matched_byte, 16).unwrap(); } i += 1; } if i != EUI48LEN { return Err(ParseError::InvalidByteCount(i, eui)); } Ok(MacAddress::new(eui)) } /// Return the internal structure as a slice of bytes pub fn as_bytes(&self) -> &[u8] { &self.eui } /// Returns an array in Eui48. Works as an inverse function of new() pub fn to_array(&self) -> Eui48 { self.eui } /// Returns Display MacAddressFormat, determined at compile time. pub fn get_display_format() -> MacAddressFormat { if cfg!(feature = "disp_hexstring") { MacAddressFormat::HexString } else { MacAddressFormat::Canonical } } } impl FromStr for MacAddress { type Err = ParseError; /// Create a MacAddress from String fn from_str(us: &str) -> Result { MacAddress::parse_str(us) } } impl Default for MacAddress { /// Create a Default MacAddress (00-00-00-00-00-00) fn default() -> MacAddress { MacAddress::nil() } } impl fmt::Debug for MacAddress { /// Debug format for MacAddress is HexString notation fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "MacAddress(\"{}\")", self.to_string(MacAddressFormat::HexString) ) } } impl fmt::Display for MacAddress { /// Display format is canonical format (00-00-00-00-00-00) by default fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let disp_fmt = MacAddress::get_display_format(); write!(f, "{}", self.to_string(disp_fmt)) } } impl fmt::Display for ParseError { /// Human readable error strings for ParseError enum fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ParseError::InvalidLength(found) => write!( f, "Invalid length; expecting 11 to 17 chars, found {}", found ), ParseError::InvalidByteCount(found, eui) => write!( f, "Invalid byte count; Matched `{}` bytes ({:?})", found, &eui[..found] ), } } } impl Error for ParseError { /// Human readable description for ParseError enum fn description(&self) -> &str { "MacAddress parse error" } } #[cfg(feature = "rustc-serialize")] impl Encodable for MacAddress { /// Encode a MacAddress using the default format fn encode(&self, e: &mut E) -> Result<(), E::Error> { let disp_fmt = MacAddress::get_display_format(); e.emit_str(&self.to_string(disp_fmt)) } } #[cfg(feature = "rustc-serialize")] impl Decodable for MacAddress { /// Decode a MacAddress from a string in canonical form fn decode(d: &mut D) -> Result { let string = d.read_str()?; string.parse().map_err(|err| d.error(&format!("{}", err))) } } #[cfg(all(feature = "serde", not(feature = "serde_bytes")))] impl Serialize for MacAddress { /// Serialize a MacAddress in the default format using the serde crate fn serialize(&self, serializer: S) -> Result { let disp_fmt = MacAddress::get_display_format(); serializer.serialize_str(&self.to_string(disp_fmt)) } } #[cfg(feature = "serde_bytes")] impl Serialize for MacAddress { /// Serialize a MacAddress as raw bytes using the serde crate fn serialize(&self, serializer: S) -> Result { serializer.serialize_bytes(self.as_bytes()) } } #[cfg(all(feature = "serde", not(feature = "serde_bytes")))] impl<'de> Deserialize<'de> for MacAddress { /// Deserialize a MacAddress from canonical form using the serde crate fn deserialize>(deserializer: D) -> Result { struct MacAddressVisitor; impl<'de> de::Visitor<'de> for MacAddressVisitor { type Value = MacAddress; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "a string representation of a MAC address") } fn visit_str(self, value: &str) -> Result { value.parse().map_err(|err| E::custom(&format!("{}", err))) } } deserializer.deserialize_str(MacAddressVisitor) } } #[cfg(feature = "serde_bytes")] impl<'de> Deserialize<'de> for MacAddress { /// Deserialize a MacAddress from raw bytes using the serde crate fn deserialize>(deserializer: D) -> Result { struct MacAddressVisitor; impl<'de> de::Visitor<'de> for MacAddressVisitor { type Value = MacAddress; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "6-element byte array") } fn visit_bytes(self, value: &[u8]) -> Result { MacAddress::from_bytes(value).map_err(|_| E::invalid_length(value.len(), &self)) } } deserializer.deserialize_bytes(MacAddressVisitor) } } // ************** TESTS BEGIN HERE *************** #[cfg(test)] mod tests { use super::{Eui48, MacAddress, MacAddressFormat, ParseError}; #[test] fn test_new() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert!(mac.eui[0..5] == eui[0..5]); } #[test] fn test_from_bytes() { assert_eq!( "12:34:56:ab:cd:ef", MacAddress::from_bytes(&[0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]) .unwrap() .to_hex_string() ); assert!(MacAddress::from_bytes(&[0x12, 0x34, 0x56, 0xAB, 0xCD]).is_err()); } #[test] fn test_nil() { let nil = MacAddress::nil(); let not_nil = MacAddress::broadcast(); assert_eq!("00:00:00:00:00:00", nil.to_hex_string()); assert!(nil.is_nil()); assert!(!not_nil.is_nil()); } #[test] fn test_default() { let default = MacAddress::default(); assert!(default.is_nil()); } #[test] fn test_broadcast() { let broadcast = MacAddress::broadcast(); let not_broadcast = MacAddress::nil(); assert_eq!("ff:ff:ff:ff:ff:ff", broadcast.to_hex_string()); assert!(broadcast.is_broadcast()); assert!(!not_broadcast.is_broadcast()); } #[test] fn test_is_nil() { let nil = MacAddress::nil(); let not_nil = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap(); assert!(nil.is_nil()); assert!(!not_nil.is_nil()); } #[test] fn test_is_broadcast() { let broadcast = MacAddress::broadcast(); let not_broadcast = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap(); assert!(broadcast.is_broadcast()); assert!(!not_broadcast.is_broadcast()); } #[test] fn test_is_unicast() { let mac_u = MacAddress::parse_str("FE:00:5E:AB:CD:EF").unwrap(); let mac_m = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap(); assert!(mac_u.is_unicast()); assert!(!mac_m.is_unicast()); assert_eq!("fe:00:5e:ab:cd:ef", mac_u.to_hex_string()); // Catch modifying first octet let mac = MacAddress::parse_str("FF:00:5E:AB:CD:EF").unwrap(); assert!(!mac.is_unicast()); assert_eq!("ff:00:5e:ab:cd:ef", mac.to_hex_string()); // Catch modifying first octet assert!(MacAddress::nil().is_unicast()); assert!(!MacAddress::broadcast().is_unicast()); } #[test] fn test_is_multicast() { let mac_u = MacAddress::parse_str("FE:00:5E:AB:CD:EF").unwrap(); let mac_m = MacAddress::parse_str("01:00:5E:AB:CD:EF").unwrap(); assert!(!mac_u.is_multicast()); assert!(mac_m.is_multicast()); assert!(!MacAddress::nil().is_multicast()); assert_eq!("01:00:5e:ab:cd:ef", mac_m.to_hex_string()); // Catch modifying first octet let mac = MacAddress::parse_str("F0:00:5E:AB:CD:EF").unwrap(); assert!(!mac.is_multicast()); assert_eq!("f0:00:5e:ab:cd:ef", mac.to_hex_string()); // Catch modifying first octet assert!(MacAddress::broadcast().is_multicast()); } #[test] fn test_is_universal() { let universal = MacAddress::parse_str("11:24:56:AB:CD:EF").unwrap(); let not_universal = MacAddress::parse_str("12:24:56:AB:CD:EF").unwrap(); assert!(universal.is_universal()); assert!(!not_universal.is_universal()); assert_eq!("11:24:56:ab:cd:ef", universal.to_hex_string()); // Catch modifying first octet } #[test] fn test_is_local() { let local = MacAddress::parse_str("06:34:56:AB:CD:EF").unwrap(); let not_local = MacAddress::parse_str("00:34:56:AB:CD:EF").unwrap(); assert!(local.is_local()); assert!(!not_local.is_local()); assert_eq!("06:34:56:ab:cd:ef", local.to_hex_string()); // Catch modifying first octet } #[test] fn test_to_canonical() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("12-34-56-ab-cd-ef", mac.to_canonical()); } #[test] fn test_to_hex_string() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("12:34:56:ab:cd:ef", mac.to_hex_string()); } #[test] fn test_to_dot_string() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("1234.56ab.cdef", mac.to_dot_string()); } #[test] fn test_to_hexadecimal() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("0x123456abcdef", mac.to_hexadecimal()); } #[test] fn test_to_interfaceid() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("1034:56ff:feab:cdef", mac.to_interfaceid()); } #[test] fn test_to_link_local() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!("fe80::1034:56ff:feab:cdef", mac.to_link_local()); } #[test] fn test_to_string() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!( "0x123456abcdef", mac.to_string(MacAddressFormat::Hexadecimal) ); assert_eq!( "1234.56ab.cdef", mac.to_string(MacAddressFormat::DotNotation) ); assert_eq!( "12:34:56:ab:cd:ef", mac.to_string(MacAddressFormat::HexString) ); assert_eq!( "12-34-56-ab-cd-ef", mac.to_string(MacAddressFormat::Canonical) ); } #[test] fn test_parse_str() { use super::ParseError::*; assert_eq!( "0x123456abcdef", MacAddress::parse_str("0x123456ABCDEF") .unwrap() .to_hexadecimal() ); assert_eq!( "1234.56ab.cdef", MacAddress::parse_str("1234.56AB.CDEF") .unwrap() .to_dot_string() ); assert_eq!( "12:34:56:ab:cd:ef", MacAddress::parse_str("12:34:56:AB:CD:EF") .unwrap() .to_hex_string() ); assert_eq!( "12-34-56-ab-cd-ef", MacAddress::parse_str("12-34-56-AB-CD-EF") .unwrap() .to_canonical() ); assert_eq!( "12-34-56-78-90-0a", MacAddress::parse_str("0x1234567890A") .unwrap() .to_canonical() ); assert_eq!( "12-34-56-ab-cd-ef", MacAddress::parse_str("123456ABCDEF") .unwrap() .to_canonical() ); assert_eq!( "00-00-00-00-00-00", MacAddress::parse_str("!0x00000000000") .unwrap() .to_canonical() ); assert_eq!( "00-00-00-00-00-00", MacAddress::parse_str("0x00000000000!") .unwrap() .to_canonical() ); // Test error parsing assert_eq!(MacAddress::parse_str(""), Err(InvalidLength(0))); assert_eq!(MacAddress::parse_str("0"), Err(InvalidLength(1))); assert_eq!( MacAddress::parse_str("1234567890ABCD"), Err(InvalidByteCount(7, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB])) ); assert_eq!( MacAddress::parse_str("1234567890ABCDEF"), Err(InvalidByteCount(8, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB])) ); assert_eq!( MacAddress::parse_str("01234567890ABCDEF"), Err(InvalidByteCount(9, [0x01, 0x23, 0x45, 0x67, 0x89, 0x0A])) ); assert_eq!( MacAddress::parse_str("0x1234567890ABCDE"), Err(InvalidByteCount(8, [0x12, 0x34, 0x56, 0x78, 0x90, 0xAB])) ); assert_eq!( MacAddress::parse_str("0x00:01:02:03:"), Err(InvalidByteCount(4, [0, 1, 2, 3, 0, 0])) ); assert_eq!( MacAddress::parse_str("0x00:01:02:03:04:"), Err(InvalidByteCount(5, [0, 1, 2, 3, 4, 0])) ); assert_eq!( MacAddress::parse_str("::::::::::::::"), Err(InvalidByteCount(0, [0, 0, 0, 0, 0, 0])) ); assert_eq!( MacAddress::parse_str(":::::::::::::::::"), Err(InvalidByteCount(0, [0, 0, 0, 0, 0, 0])) ); assert_eq!( MacAddress::parse_str("0x0x0x0x0x0x0x"), Err(InvalidByteCount(4, [0, 0, 0, 0, 0, 0])) ); } #[test] fn test_as_bytes() { let mac = MacAddress::broadcast(); let bytes = mac.as_bytes(); assert!(bytes.len() == 6); assert!(bytes.iter().all(|&b| b == 0xFF)); } #[test] fn test_compare() { let m1 = MacAddress::nil(); let m2 = MacAddress::broadcast(); assert_eq!(m1, m1); assert_eq!(m2, m2); assert_ne!(m1, m2); assert_ne!(m2, m1); } #[test] fn test_clone() { let m1 = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); let m2 = m1; assert_eq!(m1, m1); assert_eq!(m2, m2); assert_eq!(m1, m2); assert_eq!(m2, m1); } #[test] fn test_serialize() { use rustc_serialize::json; let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); // Format returned is base on compile time of feature(disp_hexstring) if cfg!(feature = "disp_hexstring") { assert_eq!("\"12:34:56:ab:cd:ef\"", json::encode(&mac).unwrap()); } else { assert_eq!("\"12-34-56-ab-cd-ef\"", json::encode(&mac).unwrap()); } } #[test] fn test_deserialize() { use rustc_serialize::json; let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); if cfg!(feature = "disp_hexstring") { let d = "\"12:34:56:AB:CD:EF\""; assert_eq!(mac, json::decode(&d).unwrap()); } else { let d = "\"12-34-56-AB-CD-EF\""; assert_eq!(mac, json::decode(&d).unwrap()); } } #[test] fn test_serialize_roundtrip() { use rustc_serialize::json; let m1 = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); let s = json::encode(&m1).unwrap(); let m2 = json::decode(&s).unwrap(); assert_eq!(m1, m2); } #[test] fn test_fmt_debug() { let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); assert_eq!( "MacAddress(\"12:34:56:ab:cd:ef\")".to_owned(), format!("{:?}", mac) ); } #[test] fn test_fmt() { let mac = MacAddress::parse_str("0x123456ABCDEF").unwrap(); match MacAddress::get_display_format() { MacAddressFormat::HexString => { assert_eq!("12:34:56:ab:cd:ef".to_owned(), format!("{}", mac)) } _ => assert_eq!("12-34-56-ab-cd-ef".to_owned(), format!("{}", mac)), }; } #[test] fn test_fmt_parse_errors() { assert_eq!( "Err(InvalidByteCount(7, [18, 52, 86, 171, 205, 239]))".to_owned(), format!("{:?}", MacAddress::parse_str("123456ABCDEF1")) ); assert_eq!( "Err(InvalidLength(19))", format!("{:?}", MacAddress::parse_str("12##45#67#89#AB#C#D")) ); } #[test] #[cfg(feature = "serde_json")] fn test_serde_json_serialize() { use serde_json; let serialized = serde_json::to_string(&MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap()).unwrap(); if cfg!(feature = "disp_hexstring") { assert_eq!("\"12:34:56:ab:cd:ef\"", serialized); } else { assert_eq!("\"12-34-56-ab-cd-ef\"", serialized); } } #[test] #[cfg(feature = "serde_json")] fn test_serde_json_deserialize() { use serde_json; let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); let deserialized: MacAddress = serde_json::from_str("\"12-34-56-AB-CD-EF\"").unwrap(); assert_eq!(deserialized, mac); } #[test] #[should_panic(expected = "Invalid length; expecting 11 to 17 chars, found 2")] #[cfg(feature = "serde_json")] fn test_serde_json_deserialize_panic() { let _should_panic: MacAddress = serde_json::from_str("\"12\"").unwrap(); } #[test] #[cfg(feature = "serde_bytes")] fn test_serde_bytes_serialization_roundtrip() { use bincode; let mac = MacAddress::parse_str("12:34:56:AB:CD:EF").unwrap(); let mut buffer = Vec::new(); bincode::serialize_into(&mut buffer, &mac).unwrap(); let deserialized: MacAddress = bincode::deserialize_from(&*buffer).unwrap(); assert_eq!(deserialized, mac); } #[test] fn test_macaddressformat_derive() { assert_eq!(MacAddressFormat::HexString, MacAddressFormat::HexString); assert_ne!(MacAddressFormat::HexString, MacAddressFormat::Canonical); } #[test] fn test_parseerror_fmt() { assert_eq!( "Invalid length; expecting 11 to 17 chars, found 2".to_owned(), format!("{}", ParseError::InvalidLength(2)) ); assert_eq!( "Invalid length; expecting 11 to 17 chars, found 2".to_owned(), ParseError::InvalidLength(2).to_string() ); } #[test] fn test_to_array() { let eui: Eui48 = [0x12, 0x34, 0x56, 0xAB, 0xCD, 0xEF]; let mac = MacAddress::new(eui); assert_eq!(eui, MacAddress::new(eui).to_array()); assert_eq!(mac, MacAddress::new(mac.to_array())); } }