diff -Nru rust-ipnetwork-0.14.0/benches/parse_bench.rs rust-ipnetwork-0.17.0/benches/parse_bench.rs --- rust-ipnetwork-0.14.0/benches/parse_bench.rs 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/benches/parse_bench.rs 2020-01-19 11:06:55.000000000 +0000 @@ -0,0 +1,49 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use ipnetwork::{Ipv4Network, Ipv6Network}; +use std::net::{Ipv4Addr, Ipv6Addr}; + +fn parse_ipv4_prefix_benchmark(c: &mut Criterion) { + c.bench_function("parse ipv4 prefix", |b| { + b.iter(|| "127.1.0.0/24".parse::().unwrap()) + }); +} + +fn parse_ipv6_benchmark(c: &mut Criterion) { + c.bench_function("parse ipv6", |b| { + b.iter(|| "FF01:0:0:17:0:0:0:2/64".parse::().unwrap()) + }); +} + +fn parse_ipv4_netmask_benchmark(c: &mut Criterion) { + c.bench_function("parse ipv4 netmask", |b| { + b.iter(|| "127.1.0.0/255.255.255.0".parse::().unwrap()) + }); +} + +fn contains_ipv4_benchmark(c: &mut Criterion) { + let cidr = "74.125.227.0/25".parse::().unwrap(); + c.bench_function("contains ipv4", |b| { + b.iter(|| { + cidr.contains(Ipv4Addr::new(74, 125, 227, 4)) + }) + }); +} + +fn contains_ipv6_benchmark(c: &mut Criterion) { + let cidr = "FF01:0:0:17:0:0:0:2/65".parse::().unwrap(); + c.bench_function("contains ipv6", |b| { + b.iter(|| { + cidr.contains(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0x7fff, 0, 0, 0x2)) + }) + }); +} + +criterion_group!( + benches, + parse_ipv4_prefix_benchmark, + parse_ipv6_benchmark, + parse_ipv4_netmask_benchmark, + contains_ipv4_benchmark, + contains_ipv6_benchmark +); +criterion_main!(benches); diff -Nru rust-ipnetwork-0.14.0/Cargo.toml rust-ipnetwork-0.17.0/Cargo.toml --- rust-ipnetwork-0.14.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/Cargo.toml 2020-07-13 10:52:23.000000000 +0000 @@ -3,7 +3,7 @@ # 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 +# 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 @@ -11,30 +11,36 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "ipnetwork" -version = "0.14.0" +version = "0.17.0" authors = ["Abhishek Chanda ", "Linus Färnstrand "] -description = "A library to work with IP CIDRs in Rust, heavily WIP" -documentation = "https://docs.rs/ipnetwork/" +description = "A library to work with IP CIDRs in Rust" readme = "README.md" -keywords = ["network", "ip", "address"] -categories = ["network-programming", "os"] -license = "Apache-2.0" +keywords = ["network", "ip", "address", "cidr"] +categories = ["network-programming", "parser-implementations"] +license = "MIT OR Apache-2.0" repository = "https://github.com/achanda/ipnetwork" -[dependencies.clippy] -version = "0.0.302" -optional = true +[[bench]] +name = "parse_bench" +harness = false [dependencies.serde] -version = ">=0.8.0, <2.0" +version = "1" +optional = true +[dev-dependencies.criterion] +version = "0.3.0" + [dev-dependencies.serde_derive] -version = ">=0.8.0, <2.0" +version = "1" [dev-dependencies.serde_json] version = "1.0" [features] -default = [] -dev = ["clippy"] +default = ["serde"] +[badges.maintenance] +status = "passively-maintained" + [badges.travis-ci] repository = "achanda/ipnetwork" diff -Nru rust-ipnetwork-0.14.0/Cargo.toml.orig rust-ipnetwork-0.17.0/Cargo.toml.orig --- rust-ipnetwork-0.14.0/Cargo.toml.orig 2019-02-01 22:22:52.000000000 +0000 +++ rust-ipnetwork-0.17.0/Cargo.toml.orig 2020-07-13 10:48:58.000000000 +0000 @@ -1,26 +1,30 @@ [package] name = "ipnetwork" -version = "0.14.0" # When updating version, also modify html_root_url in the lib.rs +version = "0.17.0" # When updating version, also modify html_root_url in the lib.rs authors = ["Abhishek Chanda ", "Linus Färnstrand "] -description = "A library to work with IP CIDRs in Rust, heavily WIP" -license = "Apache-2.0" +description = "A library to work with IP CIDRs in Rust" +license = "MIT OR Apache-2.0" repository = "https://github.com/achanda/ipnetwork" -keywords = ["network", "ip", "address"] +keywords = ["network", "ip", "address", "cidr"] readme = "README.md" -documentation = "https://docs.rs/ipnetwork/" -categories = ["network-programming", "os"] +categories = ["network-programming", "parser-implementations"] +edition = "2018" [dependencies] -clippy = {version = "0.0.302", optional = true} -serde = ">=0.8.0, <2.0" +serde = { version = "1", optional = true } [dev-dependencies] serde_json = "1.0" -serde_derive = ">=0.8.0, <2.0" +serde_derive = "1" +criterion = "0.3.0" [badges] travis-ci = { repository = "achanda/ipnetwork" } +maintenance = { status = "passively-maintained" } [features] -default = [] -dev = ["clippy"] +default = ["serde"] + +[[bench]] +name = "parse_bench" +harness = false diff -Nru rust-ipnetwork-0.14.0/.cargo_vcs_info.json rust-ipnetwork-0.17.0/.cargo_vcs_info.json --- rust-ipnetwork-0.14.0/.cargo_vcs_info.json 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/.cargo_vcs_info.json 2020-07-13 10:52:23.000000000 +0000 @@ -1,5 +1,5 @@ { "git": { - "sha1": "aff0419a755d47379d90ac5ff7d0bc1b8e688a10" + "sha1": "0b98eecf6abeb48e995d46a1c2b450e8fb19972c" } } diff -Nru rust-ipnetwork-0.14.0/debian/cargo-checksum.json rust-ipnetwork-0.17.0/debian/cargo-checksum.json --- rust-ipnetwork-0.14.0/debian/cargo-checksum.json 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/cargo-checksum.json 2020-10-29 08:52:36.000000000 +0000 @@ -1 +1 @@ -{"package":"Could not get crate checksum","files":{}} +{"package":"02c3eaab3ac0ede60ffa41add21970a7df7d91772c03383aac6c2c3d53cc716b","files":{}} diff -Nru rust-ipnetwork-0.14.0/debian/changelog rust-ipnetwork-0.17.0/debian/changelog --- rust-ipnetwork-0.14.0/debian/changelog 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/changelog 2020-10-29 08:52:36.000000000 +0000 @@ -1,3 +1,10 @@ +rust-ipnetwork (0.17.0-1) unstable; urgency=medium + + * Team upload. + * Package ipnetwork 0.17.0 from crates.io using debcargo 2.4.3 + + -- Andrej Shadura Thu, 29 Oct 2020 09:52:36 +0100 + rust-ipnetwork (0.14.0-2) unstable; urgency=medium * Team upload. diff -Nru rust-ipnetwork-0.14.0/debian/control rust-ipnetwork-0.17.0/debian/control --- rust-ipnetwork-0.14.0/debian/control 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/control 2020-10-29 08:52:36.000000000 +0000 @@ -1,16 +1,16 @@ Source: rust-ipnetwork Section: rust Priority: optional -Build-Depends: debhelper (>= 11), - dh-cargo (>= 15), +Build-Depends: debhelper (>= 12), + dh-cargo (>= 18), cargo:native , rustc:native , libstd-rust-dev , - librust-serde-1+default-dev | librust-serde-0+default-dev (>= 0.8.0-~~) + librust-serde-1+default-dev Maintainer: Debian Rust Maintainers Uploaders: kpcyrd -Standards-Version: 4.2.0 +Standards-Version: 4.4.1 Vcs-Git: https://salsa.debian.org/rust-team/debcargo-conf.git [src/ipnetwork] Vcs-Browser: https://salsa.debian.org/rust-team/debcargo-conf/tree/master/src/ipnetwork @@ -19,15 +19,21 @@ Multi-Arch: same Depends: ${misc:Depends}, - librust-serde-1+default-dev | librust-serde-0+default-dev (>= 0.8.0-~~) + librust-serde-1+default-dev Provides: - librust-ipnetwork+default-dev (= ${binary:Version}), + librust-ipnetwork+default-dev, librust-ipnetwork-0-dev (= ${binary:Version}), + librust-ipnetwork-0.17-dev (= ${binary:Version}), + librust-ipnetwork-0.17.0-dev (= ${binary:Version}), + librust-ipnetwork+serde-dev (= ${binary:Version}), librust-ipnetwork-0+default-dev (= ${binary:Version}), - librust-ipnetwork-0.14-dev (= ${binary:Version}), - librust-ipnetwork-0.14+default-dev (= ${binary:Version}), - librust-ipnetwork-0.14.0-dev (= ${binary:Version}), - librust-ipnetwork-0.14.0+default-dev (= ${binary:Version}) -Description: Work with IP CIDRs in Rust, heavily WIP - Rust source code + librust-ipnetwork-0+serde-dev (= ${binary:Version}), + librust-ipnetwork-0.17+default-dev (= ${binary:Version}), + librust-ipnetwork-0.17+serde-dev (= ${binary:Version}), + librust-ipnetwork-0.17.0+default-dev (= ${binary:Version}), + librust-ipnetwork-0.17.0+serde-dev (= ${binary:Version}) +Description: Work with IP CIDRs in Rust - Rust source code This package contains the source for the Rust ipnetwork crate, packaged by debcargo for use with cargo and dh-cargo. + . + Additionally, this package also provides the "serde" feature. diff -Nru rust-ipnetwork-0.14.0/debian/copyright rust-ipnetwork-0.17.0/debian/copyright --- rust-ipnetwork-0.14.0/debian/copyright 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/copyright 2020-10-29 08:52:36.000000000 +0000 @@ -13,10 +13,29 @@ Files: debian/* Copyright: - 2019 Debian Rust Maintainers + 2019-2020 Debian Rust Maintainers 2019 kpcyrd -License: Apache-2.0 +License: Apache-2.0 or Expat License: Apache-2.0 Debian systems provide the Apache 2.0 license in /usr/share/common-licenses/Apache-2.0 + +License: Expat + 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. diff -Nru rust-ipnetwork-0.14.0/debian/copyright.debcargo.hint rust-ipnetwork-0.17.0/debian/copyright.debcargo.hint --- rust-ipnetwork-0.14.0/debian/copyright.debcargo.hint 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/copyright.debcargo.hint 2020-10-29 08:52:36.000000000 +0000 @@ -9,19 +9,45 @@ Copyright: FIXME (overlay) UNKNOWN-YEARS Abhishek Chanda FIXME (overlay) UNKNOWN-YEARS Linus Färnstrand -License: Apache-2.0 +License: MIT or Apache-2.0 Comment: FIXME (overlay): Since upstream copyright years are not available in Cargo.toml, they were extracted from the upstream Git repository. This may not be correct information so you should review and fix this before uploading to the archive. +Files: ./LICENSE-MIT.md +Copyright: 2020 Developers of the ipnetwork project +License: UNKNOWN-LICENSE; FIXME (overlay) +Comment: + FIXME (overlay): These notices are extracted from files. Please review them + before uploading to the archive. + Files: debian/* Copyright: - 2019 Debian Rust Maintainers - 2019 kpcyrd -License: Apache-2.0 + 2019-2020 Debian Rust Maintainers + 2019-2020 kpcyrd +License: MIT or Apache-2.0 License: Apache-2.0 Debian systems provide the Apache 2.0 license in /usr/share/common-licenses/Apache-2.0 + +License: MIT + 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. diff -Nru rust-ipnetwork-0.14.0/debian/patches/no-clippy.patch rust-ipnetwork-0.17.0/debian/patches/no-clippy.patch --- rust-ipnetwork-0.14.0/debian/patches/no-clippy.patch 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/patches/no-clippy.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ ---- a/Cargo.toml -+++ b/Cargo.toml -@@ -21,9 +21,6 @@ - categories = ["network-programming", "os"] - license = "Apache-2.0" - repository = "https://github.com/achanda/ipnetwork" --[dependencies.clippy] --version = "0.0.302" --optional = true - - [dependencies.serde] - version = ">=0.8.0, <2.0" -@@ -35,6 +32,5 @@ - - [features] - default = [] --dev = ["clippy"] - [badges.travis-ci] - repository = "achanda/ipnetwork" diff -Nru rust-ipnetwork-0.14.0/debian/patches/series rust-ipnetwork-0.17.0/debian/patches/series --- rust-ipnetwork-0.14.0/debian/patches/series 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/patches/series 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -no-clippy.patch diff -Nru rust-ipnetwork-0.14.0/debian/tests/control rust-ipnetwork-0.17.0/debian/tests/control --- rust-ipnetwork-0.14.0/debian/tests/control 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/tests/control 2020-10-29 08:52:36.000000000 +0000 @@ -0,0 +1,14 @@ +Test-Command: /usr/share/cargo/bin/cargo-auto-test ipnetwork 0.17.0 --all-targets --all-features +Features: test-name=@ +Depends: dh-cargo (>= 18), librust-criterion-0.3+default-dev, librust-serde-derive-1+default-dev, librust-serde-json-1+default-dev, @ +Restrictions: allow-stderr, skip-not-installable + +Test-Command: /usr/share/cargo/bin/cargo-auto-test ipnetwork 0.17.0 --all-targets --no-default-features +Features: test-name=librust-ipnetwork-dev +Depends: dh-cargo (>= 18), librust-criterion-0.3+default-dev, librust-serde-derive-1+default-dev, librust-serde-json-1+default-dev, @ +Restrictions: allow-stderr, skip-not-installable + +Test-Command: /usr/share/cargo/bin/cargo-auto-test ipnetwork 0.17.0 --all-targets --features default +Features: test-name=librust-ipnetwork+default-dev +Depends: dh-cargo (>= 18), librust-criterion-0.3+default-dev, librust-serde-derive-1+default-dev, librust-serde-json-1+default-dev, @ +Restrictions: allow-stderr, skip-not-installable diff -Nru rust-ipnetwork-0.14.0/debian/watch rust-ipnetwork-0.17.0/debian/watch --- rust-ipnetwork-0.14.0/debian/watch 2019-08-06 16:10:54.000000000 +0000 +++ rust-ipnetwork-0.17.0/debian/watch 2020-10-29 08:52:36.000000000 +0000 @@ -2,4 +2,3 @@ opts=filenamemangle=s/.*\/(.*)\/download/ipnetwork-$1\.tar\.gz/g,\ uversionmangle=s/(\d)[_\.\-\+]?((RC|rc|pre|dev|beta|alpha)\d*)$/$1~$2/ \ https://qa.debian.org/cgi-bin/fakeupstream.cgi?upstream=crates.io/ipnetwork .*/crates/ipnetwork/@ANY_VERSION@/download - diff -Nru rust-ipnetwork-0.14.0/.github/workflows/rust.yml rust-ipnetwork-0.17.0/.github/workflows/rust.yml --- rust-ipnetwork-0.14.0/.github/workflows/rust.yml 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/.github/workflows/rust.yml 2019-10-30 22:19:25.000000000 +0000 @@ -0,0 +1,28 @@ +name: Rust + +on: + pull_request: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: [stable, beta, nightly] + steps: + - uses: hecrj/setup-rust-action@v1 + with: + rust-version: ${{ matrix.rust }} + - uses: actions/checkout@master + with: + ref: ${{ github.ref }} + - name: Show current git branch + run: git branch + - name: Build + run: cargo build --verbose + - name: Run tests + run: cargo test --verbose + - name: Build docs + run: cargo doc --verbose diff -Nru rust-ipnetwork-0.14.0/LICENSE-APACHE.md rust-ipnetwork-0.17.0/LICENSE-APACHE.md --- rust-ipnetwork-0.14.0/LICENSE-APACHE.md 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/LICENSE-APACHE.md 2020-02-26 16:50:33.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru rust-ipnetwork-0.14.0/LICENSE.md rust-ipnetwork-0.17.0/LICENSE.md --- rust-ipnetwork-0.14.0/LICENSE.md 2016-03-19 18:11:17.000000000 +0000 +++ rust-ipnetwork-0.17.0/LICENSE.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru rust-ipnetwork-0.14.0/LICENSE-MIT.md rust-ipnetwork-0.17.0/LICENSE-MIT.md --- rust-ipnetwork-0.14.0/LICENSE-MIT.md 1970-01-01 00:00:00.000000000 +0000 +++ rust-ipnetwork-0.17.0/LICENSE-MIT.md 2020-02-26 16:50:33.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright 2020 Developers of the ipnetwork project + +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. diff -Nru rust-ipnetwork-0.14.0/README.md rust-ipnetwork-0.17.0/README.md --- rust-ipnetwork-0.14.0/README.md 2016-12-21 18:00:49.000000000 +0000 +++ rust-ipnetwork-0.17.0/README.md 2020-06-19 20:42:43.000000000 +0000 @@ -1,14 +1,14 @@ ipnetwork === -This is a library to work with IPv4 and v6 CIDRs in rust -The IPv4 implementation is stable, IPv6 implementation is not done yet. +This is a library to work with IPv4 and IPv6 CIDRs in Rust [![Build Status](https://travis-ci.org/achanda/ipnetwork.svg?branch=master)](https://travis-ci.org/achanda/ipnetwork) [![Merit Badge](http://meritbadge.herokuapp.com/ipnetwork)](https://crates.io/crates/ipnetwork) Run Clippy by doing ``` -cargo test --features "dev" +rustup component add clippy +cargo clippy ``` ### Installation @@ -20,7 +20,7 @@ ``` You can also add `ipnetwork` as a dependency to your project's `Cargo.toml`: -``` +```toml [dependencies] ipnetwork = "*" ``` diff -Nru rust-ipnetwork-0.14.0/src/common.rs rust-ipnetwork-0.17.0/src/common.rs --- rust-ipnetwork-0.14.0/src/common.rs 2018-11-26 11:14:05.000000000 +0000 +++ rust-ipnetwork-0.17.0/src/common.rs 2020-02-26 13:44:40.000000000 +0000 @@ -1,5 +1,4 @@ -use std::error::Error; -use std::fmt; +use std::{error::Error, fmt}; /// Represents a bunch of errors that can occur while working with a `IpNetwork` #[derive(Debug, Clone, PartialEq, Eq)] @@ -10,8 +9,8 @@ } impl fmt::Display for IpNetworkError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use IpNetworkError::*; + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use crate::IpNetworkError::*; match *self { InvalidAddr(ref s) => write!(f, "invalid address: {}", s), InvalidPrefix => write!(f, "invalid prefix"), @@ -22,7 +21,7 @@ impl Error for IpNetworkError { fn description(&self) -> &str { - use IpNetworkError::*; + use crate::IpNetworkError::*; match *self { InvalidAddr(_) => "address is invalid", InvalidPrefix => "prefix is invalid", @@ -32,16 +31,22 @@ } pub fn cidr_parts(cidr: &str) -> Result<(&str, Option<&str>), IpNetworkError> { - let parts = cidr.split('/').collect::>(); - if parts.len() == 1 { - Ok((parts[0], None)) - } else if parts.len() == 2 { - Ok((parts[0], Some(parts[1]))) + // Try to find a single slash + if let Some(sep) = cidr.find('/') { + let (ip, prefix) = cidr.split_at(sep); + // Error if cidr has multiple slashes + if prefix[1..].find('/').is_some() { + Err(IpNetworkError::InvalidCidrFormat(format!( + "CIDR must contain a single '/': {}", + cidr + ))) + } else { + // Handle the case when cidr has exactly one slash + Ok((ip, Some(&prefix[1..]))) + } } else { - Err(IpNetworkError::InvalidCidrFormat(format!( - "CIDR must contain a single '/': {}", - cidr - ))) + // Handle the case when cidr does not have a slash + Ok((cidr, None)) } } diff -Nru rust-ipnetwork-0.14.0/src/ipv4.rs rust-ipnetwork-0.17.0/src/ipv4.rs --- rust-ipnetwork-0.14.0/src/ipv4.rs 2018-12-08 22:05:05.000000000 +0000 +++ rust-ipnetwork-0.17.0/src/ipv4.rs 2020-02-26 13:44:40.000000000 +0000 @@ -1,10 +1,5 @@ -use std::fmt; -use std::net::Ipv4Addr; -use std::str::FromStr; - -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; - -use common::{cidr_parts, parse_prefix, IpNetworkError}; +use crate::common::{cidr_parts, parse_prefix, IpNetworkError}; +use std::{fmt, net::Ipv4Addr, str::FromStr}; const IPV4_BITS: u8 = 32; @@ -15,20 +10,22 @@ prefix: u8, } -impl<'de> Deserialize<'de> for Ipv4Network { +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for Ipv4Network { fn deserialize(deserializer: D) -> Result where - D: Deserializer<'de>, + D: serde::Deserializer<'de>, { - let s = <&str>::deserialize(deserializer)?; - Ipv4Network::from_str(s).map_err(de::Error::custom) + let s = ::deserialize(deserializer)?; + Ipv4Network::from_str(&s).map_err(serde::de::Error::custom) } } -impl Serialize for Ipv4Network { +#[cfg(feature = "serde")] +impl serde::Serialize for Ipv4Network { fn serialize(&self, serializer: S) -> Result where - S: Serializer, + S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } @@ -36,6 +33,7 @@ impl Ipv4Network { /// Constructs a new `Ipv4Network` from any `Ipv4Addr` and a prefix denoting the network size. + /// /// If the prefix is larger than 32 this will return an `IpNetworkError::InvalidPrefix`. pub fn new(addr: Ipv4Addr, prefix: u8) -> Result { if prefix > IPV4_BITS { @@ -45,23 +43,58 @@ } } + /// Constructs a new `Ipv4Network` from a network address and a network mask. + /// + /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. + pub fn with_netmask( + netaddr: Ipv4Addr, + netmask: Ipv4Addr, + ) -> Result { + let prefix = ipv4_mask_to_prefix(netmask)?; + let net = Self { + addr: netaddr, + prefix, + }; + Ok(net) + } + /// Returns an iterator over `Ipv4Network`. Each call to `next` will return the next /// `Ipv4Addr` in the given network. `None` will be returned when there are no more /// addresses. - pub fn iter(&self) -> Ipv4NetworkIterator { + pub fn iter(self) -> Ipv4NetworkIterator { let start = u32::from(self.network()); - let end = start + self.size(); - Ipv4NetworkIterator { next: start, end } + let end = start + (self.size() - 1); + Ipv4NetworkIterator { + next: Some(start), + end, + } } - pub fn ip(&self) -> Ipv4Addr { + pub fn ip(self) -> Ipv4Addr { self.addr } - pub fn prefix(&self) -> u8 { + pub fn prefix(self) -> u8 { self.prefix } + /// Checks if the given `Ipv4Network` is a subnet of the other. + pub fn is_subnet_of(self, other: Ipv4Network) -> bool { + other.ip() <= self.ip() && other.broadcast() >= self.broadcast() + } + + /// Checks if the given `Ipv4Network` is a supernet of the other. + pub fn is_supernet_of(self, other: Ipv4Network) -> bool { + other.is_subnet_of(self) + } + + /// Checks if the given `Ipv4Network` is partly contained in other. + pub fn overlaps(self, other: Ipv4Network) -> bool { + other.contains(self.ip()) + || (other.contains(self.broadcast()) + || (self.contains(other.ip()) || (self.contains(other.broadcast())))) + } + /// Returns the mask for this `Ipv4Network`. /// That means the `prefix` most significant bits will be 1 and the rest 0 /// @@ -76,7 +109,7 @@ /// let net: Ipv4Network = "127.0.0.0/16".parse().unwrap(); /// assert_eq!(net.mask(), Ipv4Addr::new(255, 255, 0, 0)); /// ``` - pub fn mask(&self) -> Ipv4Addr { + pub fn mask(self) -> Ipv4Addr { let prefix = self.prefix; let mask = !(0xffff_ffff as u64 >> prefix) as u32; Ipv4Addr::from(mask) @@ -94,7 +127,7 @@ /// let net: Ipv4Network = "10.1.9.32/16".parse().unwrap(); /// assert_eq!(net.network(), Ipv4Addr::new(10, 1, 0, 0)); /// ``` - pub fn network(&self) -> Ipv4Addr { + pub fn network(self) -> Ipv4Addr { let mask = u32::from(self.mask()); let ip = u32::from(self.addr) & mask; Ipv4Addr::from(ip) @@ -112,7 +145,7 @@ /// let net: Ipv4Network = "10.9.0.32/16".parse().unwrap(); /// assert_eq!(net.broadcast(), Ipv4Addr::new(10, 9, 255, 255)); /// ``` - pub fn broadcast(&self) -> Ipv4Addr { + pub fn broadcast(self) -> Ipv4Addr { let mask = u32::from(self.mask()); let broadcast = u32::from(self.addr) | !mask; Ipv4Addr::from(broadcast) @@ -130,9 +163,9 @@ /// assert!(net.contains(Ipv4Addr::new(127, 0, 0, 70))); /// assert!(!net.contains(Ipv4Addr::new(127, 0, 1, 70))); /// ``` - pub fn contains(&self, ip: Ipv4Addr) -> bool { - let net = u32::from(self.network()); - let mask = u32::from(self.mask()); + pub fn contains(self, ip: Ipv4Addr) -> bool { + let mask = !(0xffff_ffff as u64 >> self.prefix) as u32; + let net = u32::from(self.addr) & mask; (u32::from(ip) & mask) == net } @@ -150,7 +183,7 @@ /// let tinynet: Ipv4Network = "0.0.0.0/32".parse().unwrap(); /// assert_eq!(tinynet.size(), 1); /// ``` - pub fn size(&self) -> u32 { + pub fn size(self) -> u32 { let host_bits = u32::from(IPV4_BITS - self.prefix); (2 as u32).pow(host_bits) } @@ -172,7 +205,7 @@ /// let net2: Ipv4Network = "10.0.0.0/16".parse().unwrap(); /// assert_eq!(net2.nth(256).unwrap(), Ipv4Addr::new(10, 0, 1, 0)); /// ``` - pub fn nth(&self, n: u32) -> Option { + pub fn nth(self, n: u32) -> Option { if n < self.size() { let net = u32::from(self.network()); Some(Ipv4Addr::from(net + n)) @@ -183,7 +216,7 @@ } impl fmt::Display for Ipv4Network { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}/{}", self.ip(), self.prefix()) } } @@ -208,7 +241,13 @@ let addr = Ipv4Addr::from_str(addr_str) .map_err(|_| IpNetworkError::InvalidAddr(addr_str.to_string()))?; let prefix = match prefix_str { - Some(v) => parse_prefix(v, IPV4_BITS)?, + Some(v) => { + if let Ok(netmask) = Ipv4Addr::from_str(v) { + ipv4_mask_to_prefix(netmask)? + } else { + parse_prefix(v, IPV4_BITS)? + } + } None => IPV4_BITS, }; Ipv4Network::new(addr, prefix) @@ -224,8 +263,9 @@ } } +#[derive(Copy, Clone, Debug)] pub struct Ipv4NetworkIterator { - next: u32, + next: Option, end: u32, } @@ -233,17 +273,26 @@ type Item = Ipv4Addr; fn next(&mut self) -> Option { - if self.next < self.end { - let next = Ipv4Addr::from(self.next as u32); - self.next += 1; - Some(next) - } else { + let next = self.next?; + self.next = if next == self.end { None - } + } else { + Some(next + 1) + }; + Some(next.into()) + } +} + +impl IntoIterator for &'_ Ipv4Network { + type IntoIter = Ipv4NetworkIterator; + type Item = Ipv4Addr; + fn into_iter(self) -> Ipv4NetworkIterator { + self.iter() } } /// Converts a `Ipv4Addr` network mask into a prefix. +/// /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ipv4_mask_to_prefix(mask: Ipv4Addr) -> Result { let mask = u32::from(mask); @@ -429,6 +478,22 @@ assert_eq!(prefix, 25); } + /// Parse netmask as well as prefix + #[test] + fn parse_netmask() { + let from_netmask: Ipv4Network = "192.168.1.0/255.255.255.0".parse().unwrap(); + let from_prefix: Ipv4Network = "192.168.1.0/24".parse().unwrap(); + assert_eq!(from_netmask, from_prefix); + } + + #[test] + fn parse_netmask_broken_v4() { + assert_eq!( + "192.168.1.0/255.0.255.0".parse::(), + Err(IpNetworkError::InvalidPrefix) + ); + } + #[test] fn invalid_v4_mask_to_prefix() { let mask = Ipv4Addr::new(255, 0, 255, 0); @@ -437,6 +502,24 @@ } #[test] + fn ipv4network_with_netmask() { + { + // Positive test-case. + let addr = Ipv4Addr::new(127, 0, 0, 1); + let mask = Ipv4Addr::new(255, 0, 0, 0); + let net = Ipv4Network::with_netmask(addr, mask).unwrap(); + let expected = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 8).unwrap(); + assert_eq!(net, expected); + } + { + // Negative test-case. + let addr = Ipv4Addr::new(127, 0, 0, 1); + let mask = Ipv4Addr::new(255, 0, 255, 0); + Ipv4Network::with_netmask(addr, mask).unwrap_err(); + } + } + + #[test] fn ipv4network_from_ipv4addr() { let net = Ipv4Network::from(Ipv4Addr::new(127, 0, 0, 1)); let expected = Ipv4Network::new(Ipv4Addr::new(127, 0, 0, 1), 32).unwrap(); @@ -454,4 +537,125 @@ fn assert_sync() {} assert_sync::(); } + + // Tests from cpython https://github.com/python/cpython/blob/e9bc4172d18db9c182d8e04dd7b033097a994c06/Lib/test/test_ipaddress.py + #[test] + fn test_is_subnet_of() { + let mut test_cases: HashMap<(Ipv4Network, Ipv4Network), bool> = HashMap::new(); + + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.1.0/24".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.0.0/24".parse().unwrap(), + ), + true, + ); + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.1.0/24".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "10.0.1.0/24".parse().unwrap(), + "10.0.0.0/30".parse().unwrap(), + ), + false, + ); + + for (key, val) in test_cases.iter() { + let (src, dest) = (key.0, key.1); + assert_eq!( + src.is_subnet_of(dest), + *val, + "testing with {} and {}", + src, + dest + ); + } + } + + #[test] + fn test_is_supernet_of() { + let mut test_cases: HashMap<(Ipv4Network, Ipv4Network), bool> = HashMap::new(); + + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.1.0/24".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.0.0/24".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "10.0.0.0/30".parse().unwrap(), + "10.0.1.0/24".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "10.0.0.0/24".parse().unwrap(), + "10.0.0.0/30".parse().unwrap(), + ), + true, + ); + + for (key, val) in test_cases.iter() { + let (src, dest) = (key.0, key.1); + assert_eq!( + src.is_supernet_of(dest), + *val, + "testing with {} and {}", + src, + dest + ); + } + } + + #[test] + fn test_overlaps() { + let other: Ipv4Network = "1.2.3.0/30".parse().unwrap(); + let other2: Ipv4Network = "1.2.2.0/24".parse().unwrap(); + let other3: Ipv4Network = "1.2.2.64/26".parse().unwrap(); + + let skynet: Ipv4Network = "1.2.3.0/24".parse().unwrap(); + assert_eq!(skynet.overlaps(other), true); + assert_eq!(skynet.overlaps(other2), false); + assert_eq!(other2.overlaps(other3), true); + } + + #[test] + fn edges() { + let low: Ipv4Network = "0.0.0.0/24".parse().unwrap(); + let low_addrs: Vec = low.iter().collect(); + assert_eq!(256, low_addrs.len()); + assert_eq!("0.0.0.0".parse::().unwrap(), low_addrs[0]); + assert_eq!("0.0.0.255".parse::().unwrap(), low_addrs[255]); + + let high: Ipv4Network = "255.255.255.0/24".parse().unwrap(); + let high_addrs: Vec = high.iter().collect(); + assert_eq!(256, high_addrs.len()); + assert_eq!("255.255.255.0".parse::().unwrap(), high_addrs[0]); + assert_eq!( + "255.255.255.255".parse::().unwrap(), + high_addrs[255] + ); + } } diff -Nru rust-ipnetwork-0.14.0/src/ipv6.rs rust-ipnetwork-0.17.0/src/ipv6.rs --- rust-ipnetwork-0.14.0/src/ipv6.rs 2018-11-26 11:29:09.000000000 +0000 +++ rust-ipnetwork-0.17.0/src/ipv6.rs 2020-02-26 13:44:40.000000000 +0000 @@ -1,11 +1,5 @@ -use std::cmp; -use std::fmt; -use std::net::Ipv6Addr; -use std::str::FromStr; - -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; - -use common::{cidr_parts, parse_prefix, IpNetworkError}; +use crate::common::{cidr_parts, parse_prefix, IpNetworkError}; +use std::{cmp, fmt, net::Ipv6Addr, str::FromStr}; const IPV6_BITS: u8 = 128; const IPV6_SEGMENT_BITS: u8 = 16; @@ -17,20 +11,22 @@ prefix: u8, } -impl<'de> Deserialize<'de> for Ipv6Network { +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for Ipv6Network { fn deserialize(deserializer: D) -> Result where - D: Deserializer<'de>, + D: serde::Deserializer<'de>, { - let s = <&str>::deserialize(deserializer)?; - Ipv6Network::from_str(s).map_err(de::Error::custom) + let s = ::deserialize(deserializer)?; + Ipv6Network::from_str(&s).map_err(serde::de::Error::custom) } } -impl Serialize for Ipv6Network { +#[cfg(feature = "serde")] +impl serde::Serialize for Ipv6Network { fn serialize(&self, serializer: S) -> Result where - S: Serializer, + S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } @@ -38,6 +34,7 @@ impl Ipv6Network { /// Constructs a new `Ipv6Network` from any `Ipv6Addr` and a prefix denoting the network size. + /// /// If the prefix is larger than 128 this will return an `IpNetworkError::InvalidPrefix`. pub fn new(addr: Ipv6Addr, prefix: u8) -> Result { if prefix > IPV6_BITS { @@ -47,6 +44,18 @@ } } + /// Constructs a new `Ipv6Network` from a network address and a network mask. + /// + /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. + pub fn with_netmask(netaddr: Ipv6Addr, netmask: Ipv6Addr) -> Result { + let prefix = ipv6_mask_to_prefix(netmask)?; + let net = Self { + addr: netaddr, + prefix, + }; + Ok(net) + } + /// Returns an iterator over `Ipv6Network`. Each call to `next` will return the next /// `Ipv6Addr` in the given network. `None` will be returned when there are no more /// addresses. @@ -62,8 +71,8 @@ let end: u128 = dec | mask; Ipv6NetworkIterator { - next: start, - end: end, + next: Some(start), + end, } } @@ -111,6 +120,23 @@ self.prefix } + /// Checks if the given `Ipv6Network` is a subnet of the other. + pub fn is_subnet_of(self, other: Ipv6Network) -> bool { + other.ip() <= self.ip() && other.broadcast() >= self.broadcast() + } + + /// Checks if the given `Ipv6Network` is a supernet of the other. + pub fn is_supernet_of(self, other: Ipv6Network) -> bool { + other.is_subnet_of(self) + } + + /// Checks if the given `Ipv6Network` is partly contained in other. + pub fn overlaps(self, other: Ipv6Network) -> bool { + other.contains(self.ip()) + || (other.contains(self.broadcast()) + || (self.contains(other.ip()) || (self.contains(other.broadcast())))) + } + /// Returns the mask for this `Ipv6Network`. /// That means the `prefix` most significant bits will be 1 and the rest 0 /// @@ -202,8 +228,9 @@ } } +#[derive(Copy, Clone, Debug)] pub struct Ipv6NetworkIterator { - next: u128, + next: Option, end: u128, } @@ -211,18 +238,26 @@ type Item = Ipv6Addr; fn next(&mut self) -> Option { - if self.next <= self.end { - let next = Ipv6Addr::from(self.next); - self.next += 1; - Some(next) - } else { + let next = self.next?; + self.next = if next == self.end { None - } + } else { + Some(next + 1) + }; + Some(next.into()) + } +} + +impl IntoIterator for &'_ Ipv6Network { + type IntoIter = Ipv6NetworkIterator; + type Item = Ipv6Addr; + fn into_iter(self) -> Ipv6NetworkIterator { + self.iter() } } impl fmt::Display for Ipv6Network { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "{}/{}", self.ip(), self.prefix()) } } @@ -231,7 +266,7 @@ /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ipv6_mask_to_prefix(mask: Ipv6Addr) -> Result { let mask = mask.segments(); - let mut mask_iter = mask.into_iter(); + let mut mask_iter = mask.iter(); // Count the number of set bits from the start of the address let mut prefix = 0; @@ -265,6 +300,7 @@ #[cfg(test)] mod test { use super::*; + use std::collections::HashMap; use std::net::Ipv6Addr; #[test] @@ -274,6 +310,14 @@ } #[test] + fn parse_netmask_broken_v6() { + assert_eq!( + "FF01:0:0:17:0:0:0:2/255.255.255.0".parse::(), + Err(IpNetworkError::InvalidPrefix) + ); + } + + #[test] fn create_v6_invalid_prefix() { let cidr = Ipv6Network::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 129); assert!(cidr.is_err()); @@ -354,6 +398,25 @@ } #[test] + fn ipv6network_with_netmask() { + { + // Positive test-case. + let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); + let mask = Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0, 0, 0, 0, 0); + let net = Ipv6Network::with_netmask(addr, mask).unwrap(); + let expected = + Ipv6Network::new(Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2), 48).unwrap(); + assert_eq!(net, expected); + } + { + // Negative test-case. + let addr = Ipv6Addr::new(0xff01, 0, 0, 0x17, 0, 0, 0, 0x2); + let mask = Ipv6Addr::new(0, 0, 0xffff, 0xffff, 0, 0, 0, 0); + Ipv6Network::with_netmask(addr, mask).unwrap_err(); + } + } + + #[test] fn iterator_v6() { let cidr: Ipv6Network = "2001:db8::/126".parse().unwrap(); let mut iter = cidr.iter(); @@ -436,4 +499,116 @@ fn assert_sync() {} assert_sync::(); } + + // Tests from cpython https://github.com/python/cpython/blob/e9bc4172d18db9c182d8e04dd7b033097a994c06/Lib/test/test_ipaddress.py + #[test] + fn test_is_subnet_of() { + let mut test_cases: HashMap<(Ipv6Network, Ipv6Network), bool> = HashMap::new(); + + test_cases.insert( + ( + "2000:999::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "2000:aaa::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + true, + ); + test_cases.insert( + ( + "2000:bbb::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "2000:aaa::/48".parse().unwrap(), + "2000:aaa::/56".parse().unwrap(), + ), + false, + ); + + for (key, val) in test_cases.iter() { + let (src, dest) = (key.0, key.1); + assert_eq!( + src.is_subnet_of(dest), + *val, + "testing with {} and {}", + src, + dest + ); + } + } + + #[test] + fn test_is_supernet_of() { + let mut test_cases: HashMap<(Ipv6Network, Ipv6Network), bool> = HashMap::new(); + + test_cases.insert( + ( + "2000:999::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "2000:aaa::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "2000:bbb::/56".parse().unwrap(), + "2000:aaa::/48".parse().unwrap(), + ), + false, + ); + test_cases.insert( + ( + "2000:aaa::/48".parse().unwrap(), + "2000:aaa::/56".parse().unwrap(), + ), + true, + ); + + for (key, val) in test_cases.iter() { + let (src, dest) = (key.0, key.1); + assert_eq!( + src.is_supernet_of(dest), + *val, + "testing with {} and {}", + src, + dest + ); + } + } + + #[test] + fn test_overlaps() { + let other: Ipv6Network = "2001:DB8:ACAD::1/64".parse().unwrap(); + let other2: Ipv6Network = "2001:DB8:ACAD::20:2/64".parse().unwrap(); + + assert_eq!(other2.overlaps(other), true); + } + + #[test] + fn edges() { + let low: Ipv6Network = "::0/120".parse().unwrap(); + let low_addrs: Vec = low.iter().collect(); + assert_eq!(256, low_addrs.len()); + + let high: Ipv6Network = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ff00/120" + .parse() + .unwrap(); + let high_addrs: Vec = high.iter().collect(); + assert_eq!(256, high_addrs.len()); + } } diff -Nru rust-ipnetwork-0.14.0/src/lib.rs rust-ipnetwork-0.17.0/src/lib.rs --- rust-ipnetwork-0.14.0/src/lib.rs 2019-02-01 22:22:52.000000000 +0000 +++ rust-ipnetwork-0.17.0/src/lib.rs 2020-07-13 10:48:58.000000000 +0000 @@ -1,27 +1,25 @@ //! The `ipnetwork` crate provides a set of APIs to work with IP CIDRs in -//! Rust. Implementation for IPv4 is more or less stable, IPv6 implementation -//! is still WIP. -#![cfg_attr(feature = "dev", feature(plugin))] -#![cfg_attr(feature = "dev", plugin(clippy))] +//! Rust. #![crate_type = "lib"] -#![doc(html_root_url = "https://docs.rs/ipnetwork/0.14.0")] +#![doc(html_root_url = "https://docs.rs/ipnetwork/0.17.0")] -extern crate serde; +#![deny(missing_copy_implementations, + missing_debug_implementations, + unsafe_code, + unused_extern_crates, + unused_import_braces)] -use std::fmt; -use std::net::IpAddr; +use std::{fmt, net::IpAddr, str::FromStr}; mod common; mod ipv4; mod ipv6; -use std::str::FromStr; - -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; - -pub use common::IpNetworkError; -pub use ipv4::{ipv4_mask_to_prefix, Ipv4Network}; -pub use ipv6::{ipv6_mask_to_prefix, Ipv6Network}; +pub use crate::common::IpNetworkError; +use crate::ipv4::Ipv4NetworkIterator; +pub use crate::ipv4::{ipv4_mask_to_prefix, Ipv4Network}; +use crate::ipv6::Ipv6NetworkIterator; +pub use crate::ipv6::{ipv6_mask_to_prefix, Ipv6Network}; /// Represents a generic network range. This type can have two variants: /// the v4 and the v6 case. @@ -31,20 +29,22 @@ V6(Ipv6Network), } -impl<'de> Deserialize<'de> for IpNetwork { +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for IpNetwork { fn deserialize(deserializer: D) -> Result where - D: Deserializer<'de>, + D: serde::Deserializer<'de>, { let s = ::deserialize(deserializer)?; - IpNetwork::from_str(&s).map_err(de::Error::custom) + IpNetwork::from_str(&s).map_err(serde::de::Error::custom) } } -impl Serialize for IpNetwork { +#[cfg(feature = "serde")] +impl serde::Serialize for IpNetwork { fn serialize(&self, serializer: S) -> Result where - S: Serializer, + S: serde::Serializer, { serializer.serialize_str(&self.to_string()) } @@ -69,6 +69,14 @@ } } + /// Constructs a new `IpNetwork` from a network address and a network mask. + /// + /// If the netmask is not valid this will return an `IpNetworkError::InvalidPrefix`. + pub fn with_netmask(netaddr: IpAddr, netmask: IpAddr) -> Result { + let prefix = ip_mask_to_prefix(netmask)?; + Self::new(netaddr, prefix) + } + /// Returns the IP part of a given `IpNetwork` pub fn ip(&self) -> IpAddr { match *self { @@ -200,6 +208,10 @@ } } + // TODO(abhishek) when TryFrom is stable, implement it for IpNetwork to + // variant conversions. Then use that to implement a generic is_subnet_of + // is_supernet_of, overlaps + /// Checks if a given `IpAddr` is in this `IpNetwork` /// /// # Examples @@ -241,6 +253,17 @@ IpNetwork::V6(ref ip) => NetworkSize::V6(ip.size()), } } + + /// Returns an iterator over the addresses contained in the network. + /// + /// This lists all the addresses in the network range, in ascending order. + pub fn iter(&self) -> IpNetworkIterator { + let inner = match self { + IpNetwork::V4(ip) => IpNetworkIteratorInner::V4(ip.iter()), + IpNetwork::V6(ip) => IpNetworkIteratorInner::V6(ip.iter()), + }; + IpNetworkIterator { inner } + } } /// Tries to parse the given string into a `IpNetwork`. Will first try to parse @@ -292,7 +315,7 @@ } impl fmt::Display for IpNetwork { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { IpNetwork::V4(net) => net.fmt(f), IpNetwork::V6(net) => net.fmt(f), @@ -300,6 +323,35 @@ } } +#[derive(Clone, Debug)] +enum IpNetworkIteratorInner { + V4(Ipv4NetworkIterator), + V6(Ipv6NetworkIterator), +} + +#[derive(Clone, Debug)] +pub struct IpNetworkIterator { + inner: IpNetworkIteratorInner, +} + +impl Iterator for IpNetworkIterator { + type Item = IpAddr; + fn next(&mut self) -> Option { + match &mut self.inner { + IpNetworkIteratorInner::V4(iter) => iter.next().map(IpAddr::V4), + IpNetworkIteratorInner::V6(iter) => iter.next().map(IpAddr::V6), + } + } +} + +impl IntoIterator for &'_ IpNetwork { + type IntoIter = IpNetworkIterator; + type Item = IpAddr; + fn into_iter(self) -> IpNetworkIterator { + self.iter() + } +} + /// Converts a `IpAddr` network mask into a prefix. /// If the mask is invalid this will return an `IpNetworkError::InvalidPrefix`. pub fn ip_mask_to_prefix(mask: IpAddr) -> Result { @@ -312,11 +364,13 @@ #[cfg(test)] mod test { #[test] + #[cfg(feature = "serde")] fn deserialize_from_serde_json_value() { use super::*; let network = IpNetwork::from_str("0.0.0.0/0").unwrap(); - let val: serde_json::value::Value = serde_json::from_str(&serde_json::to_string(&network).unwrap()).unwrap(); - let _deser: IpNetwork = - serde_json::from_value(val).expect("Fails to deserialize from json_value::value::Value"); + let val: serde_json::value::Value = + serde_json::from_str(&serde_json::to_string(&network).unwrap()).unwrap(); + let _deser: IpNetwork = serde_json::from_value(val) + .expect("Fails to deserialize from json_value::value::Value"); } } diff -Nru rust-ipnetwork-0.14.0/tests/test_json.rs rust-ipnetwork-0.17.0/tests/test_json.rs --- rust-ipnetwork-0.14.0/tests/test_json.rs 2018-04-18 21:54:47.000000000 +0000 +++ rust-ipnetwork-0.17.0/tests/test_json.rs 2020-01-05 10:54:26.000000000 +0000 @@ -1,16 +1,9 @@ -extern crate serde; - -extern crate serde_json; - -#[macro_use] -extern crate serde_derive; - -extern crate ipnetwork; +#![cfg(feature = "serde")] #[cfg(test)] mod tests { - use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network}; + use serde_derive::{Deserialize, Serialize}; use std::net::{Ipv4Addr, Ipv6Addr}; #[test] diff -Nru rust-ipnetwork-0.14.0/.travis.yml rust-ipnetwork-0.17.0/.travis.yml --- rust-ipnetwork-0.14.0/.travis.yml 2018-05-12 13:02:39.000000000 +0000 +++ rust-ipnetwork-0.17.0/.travis.yml 2020-01-05 13:32:09.000000000 +0000 @@ -9,6 +9,8 @@ - FEATURES: default script: + - cargo build --verbose --no-default-features + - cargo test --verbose --no-default-features - cargo build --verbose - cargo test --verbose - cargo build --release --verbose