Convert end of lines to Unix style LF.

This commit is contained in:
Kris Price
2020-03-15 18:09:36 -07:00
parent 83cbb9b7e5
commit acd3f5cf28
8 changed files with 3509 additions and 3509 deletions
+10 -10
View File
@@ -1,10 +1,10 @@
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
script: cargo test --all-features --verbose
language: rust
rust:
- stable
- beta
- nightly
matrix:
allow_failures:
- rust: nightly
script: cargo test --all-features --verbose
+201 -201
View File
@@ -1,201 +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 2017 Juniper Networks, Inc.
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.
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 2017 Juniper Networks, Inc.
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.
+7 -7
View File
@@ -1,7 +1,7 @@
Copyright 2017 Juniper Networks, Inc.
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.
Copyright 2017 Juniper Networks, Inc.
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.
+183 -183
View File
@@ -1,183 +1,183 @@
[![Build Status](https://travis-ci.org/krisprice/ipnet.svg?branch=master)](https://travis-ci.org/krisprice/ipnet)
This module provides types and useful methods for working with IPv4 and IPv6 network addresses, commonly called IP prefixes. The new `IpNet`, `Ipv4Net`, and `Ipv6Net` types build on the existing `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` types already provided in Rust's standard library and align to their design to stay consistent.
The module also provides the `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets` types for interating over the subnets contained in an IP address range. The `IpAddrRange`, `Ipv4AddrRange`, and `Ipv6AddrRange` types for iterating over IP addresses in a range. And traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for addition, subtraction, bitwise-and, and bitwise-or operations that are missing in Rust's standard library.
The module only uses stable features so it is guaranteed to compile using the stable toolchain. Tests aim for thorough coverage and can be found in both the test modules and doctests. Please file an [issue on GitHub] if you have any problems, requests, or suggested improvements.
Read the [documentation] for the full details. And find it on [Crates.io].
[documentation]: https://docs.rs/ipnet/
[Crates.io]: https://crates.io/crates/ipnet
[issue on GitHub]: https://github.com/krisprice/ipnet/issues
## Release 2.0 requirements
Release 2.0 requires Rust 1.26 or later. Release 1.0 used a custom emulated 128-bit integer type (`Emu128`) to fully support IPv6 addresses. This has been replaced with Rust's built-in 128-bit integer, which is now stable as of Rust 1.26. There are reports of issues using Rust's 128-bit integers on some targets (e.g. Emscripten). If you have issues on your chosen target, please continue to use the 1.0 release until that has been resolved.
## Examples
### Create a network address and print the hostmask and netmask
```rust
extern crate ipnet;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
fn main() {
// Create an Ipv4Net and Ipv6Net from their constructors.
let net4 = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 24).unwrap();
let net6 = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24).unwrap();
// They can also be created from string representations.
let net4 = Ipv4Net::from_str("10.1.1.0/24").unwrap();
let net6 = Ipv6Net::from_str("fd00::/24").unwrap();
// Or alternatively as follows.
let net4: Ipv4Net = "10.1.1.0/24".parse().unwrap();
let net6: Ipv6Net = "fd00::/24".parse().unwrap();
// IpNet can represent either an IPv4 or IPv6 network address.
let net = IpNet::from(net4);
// It can also be created from string representations.
let net = IpNet::from_str("10.1.1.0/24").unwrap();
let net: IpNet = "10.1.1.0/24".parse().unwrap();
// There are a number of methods that can be used. Read the
// documentation for the full details.
println!("{} hostmask = {}", net, net.hostmask());
println!("{} netmask = {}", net4, net4.netmask());
}
```
### Subdivide an existing IP network into smaller subnets
```rust
extern crate ipnet;
use ipnet::Ipv4Net;
fn main() {
let net: Ipv4Net = "192.168.0.0/23".parse().unwrap();
println!("\n/25 subnets in {}:", net);
// Note: `subnets()` returns a `Result`. If the given prefix length
// is less than the existing prefix length the `Result` will contain
// an error.
let subnets = net.subnets(25)
.expect("PrefixLenError: new prefix length cannot be shorter than existing");
// Output:
// subnet 0 = 192.168.0.0/25
// subnet 1 = 192.168.0.128/25
// subnet 2 = 192.168.1.0/25
// subnet 3 = 192.168.1.128/25
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
}
```
### Iterate over the valid subnets between two IPv4 addresses
```rust
extern crate ipnet;
use std::net::Ipv4Addr;
use ipnet::Ipv4Subnets;
fn main() {
let start = Ipv4Addr::new(10, 0, 0, 0);
let end = Ipv4Addr::new(10, 0, 0, 239);
println!("\n/0 or greater subnets between {} and {}:", start, end);
// Output all subnets starting with the largest that will fit. This
// will give us the smallest possible set of valid subnets.
//
// Output:
// subnet 0 = 10.0.0.0/25
// subnet 1 = 10.0.0.128/26
// subnet 2 = 10.0.0.192/27
// subnet 3 = 10.0.0.224/28
let subnets = Ipv4Subnets::new(start, end, 0);
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
println!("\n/26 or greater subnets between {} and {}:", start, end);
// Output all subnets with prefix lengths less than or equal to 26.
// This results in more subnets, but limits them to a maximum size.
//
// Output:
// subnet 0 = 10.0.0.0/26
// subnet 1 = 10.0.0.64/26
// subnet 2 = 10.0.0.128/26
// subnet 3 = 10.0.0.192/27
// subnet 4 = 10.0.0.224/28
let subnets = Ipv4Subnets::new(start, end, 26);
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
}
```
### Aggregate a list of IP prefixes
```rust
extern crate ipnet;
use ipnet::IpNet;
fn main() {}
// Example input list of overlapping and adjacent prefixes.
let strings = vec![
"10.0.0.0/24", "10.0.1.0/24", "10.0.1.1/24", "10.0.1.2/24",
"10.0.2.0/24",
"10.1.0.0/24", "10.1.1.0/24",
"192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24", "192.168.3.0/24",
"fd00::/32", "fd00:1::/32",
];
let nets: Vec<IpNet> = strings.iter().filter_map(|p| p.parse().ok()).collect();
println!("\nAggregated IP prefixes:");
// Output:
// 10.0.0.0/23
// 10.0.2.0/24
// 10.1.0.0/23
// 192.168.0.0/22
// fd00::/31
for n in IpNet::aggregate(&nets) {
println!("\t{}", n);
}
}
```
## Future
* Implementing `std::ops::{Add, Sub, BitAnd, BitOr}` for `Ipv4Addr` and `Ipv6Addr` would be useful as these are common operations on IP addresses. If done, the extension traits provided in this module would be removed and the major version incremented. Implementing these requires a change to the standard library. I've started a thread on this topic on the [Rust Internals](https://internals.rust-lang.org/t/pre-rfc-implementing-add-sub-bitand-bitor-for-ipaddr-ipv4addr-ipv6addr/) discussion board.
* The results of `hosts()` and potentially `subnets()` should be represented as a `Range` rather than the custom `IpAddrRange` and `IpSubnets` types provided in this module. This requires the target types to have `Add` and `Step` implemented for them. Implementing `Add` for `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` requires a change to the standard library (see above). And `Step` is still unstable so exploring this will also wait until it has stablized.
## License
Copyright (c) 2017, Juniper Networks, Inc. All rights reserved.
This code is licensed to you under either the MIT License or Apache License, Version 2.0 at your choice (the "License"). You may not use this code except in compliance with the License. This code is not an official Juniper product. You can obtain a copy of the License at: https://opensource.org/licenses/MIT or http://www.apache.org/licenses/LICENSE-2.0
[![Build Status](https://travis-ci.org/krisprice/ipnet.svg?branch=master)](https://travis-ci.org/krisprice/ipnet)
This module provides types and useful methods for working with IPv4 and IPv6 network addresses, commonly called IP prefixes. The new `IpNet`, `Ipv4Net`, and `Ipv6Net` types build on the existing `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` types already provided in Rust's standard library and align to their design to stay consistent.
The module also provides the `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets` types for interating over the subnets contained in an IP address range. The `IpAddrRange`, `Ipv4AddrRange`, and `Ipv6AddrRange` types for iterating over IP addresses in a range. And traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for addition, subtraction, bitwise-and, and bitwise-or operations that are missing in Rust's standard library.
The module only uses stable features so it is guaranteed to compile using the stable toolchain. Tests aim for thorough coverage and can be found in both the test modules and doctests. Please file an [issue on GitHub] if you have any problems, requests, or suggested improvements.
Read the [documentation] for the full details. And find it on [Crates.io].
[documentation]: https://docs.rs/ipnet/
[Crates.io]: https://crates.io/crates/ipnet
[issue on GitHub]: https://github.com/krisprice/ipnet/issues
## Release 2.0 requirements
Release 2.0 requires Rust 1.26 or later. Release 1.0 used a custom emulated 128-bit integer type (`Emu128`) to fully support IPv6 addresses. This has been replaced with Rust's built-in 128-bit integer, which is now stable as of Rust 1.26. There are reports of issues using Rust's 128-bit integers on some targets (e.g. Emscripten). If you have issues on your chosen target, please continue to use the 1.0 release until that has been resolved.
## Examples
### Create a network address and print the hostmask and netmask
```rust
extern crate ipnet;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
fn main() {
// Create an Ipv4Net and Ipv6Net from their constructors.
let net4 = Ipv4Net::new(Ipv4Addr::new(10, 1, 1, 0), 24).unwrap();
let net6 = Ipv6Net::new(Ipv6Addr::new(0xfd, 0, 0, 0, 0, 0, 0, 0), 24).unwrap();
// They can also be created from string representations.
let net4 = Ipv4Net::from_str("10.1.1.0/24").unwrap();
let net6 = Ipv6Net::from_str("fd00::/24").unwrap();
// Or alternatively as follows.
let net4: Ipv4Net = "10.1.1.0/24".parse().unwrap();
let net6: Ipv6Net = "fd00::/24".parse().unwrap();
// IpNet can represent either an IPv4 or IPv6 network address.
let net = IpNet::from(net4);
// It can also be created from string representations.
let net = IpNet::from_str("10.1.1.0/24").unwrap();
let net: IpNet = "10.1.1.0/24".parse().unwrap();
// There are a number of methods that can be used. Read the
// documentation for the full details.
println!("{} hostmask = {}", net, net.hostmask());
println!("{} netmask = {}", net4, net4.netmask());
}
```
### Subdivide an existing IP network into smaller subnets
```rust
extern crate ipnet;
use ipnet::Ipv4Net;
fn main() {
let net: Ipv4Net = "192.168.0.0/23".parse().unwrap();
println!("\n/25 subnets in {}:", net);
// Note: `subnets()` returns a `Result`. If the given prefix length
// is less than the existing prefix length the `Result` will contain
// an error.
let subnets = net.subnets(25)
.expect("PrefixLenError: new prefix length cannot be shorter than existing");
// Output:
// subnet 0 = 192.168.0.0/25
// subnet 1 = 192.168.0.128/25
// subnet 2 = 192.168.1.0/25
// subnet 3 = 192.168.1.128/25
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
}
```
### Iterate over the valid subnets between two IPv4 addresses
```rust
extern crate ipnet;
use std::net::Ipv4Addr;
use ipnet::Ipv4Subnets;
fn main() {
let start = Ipv4Addr::new(10, 0, 0, 0);
let end = Ipv4Addr::new(10, 0, 0, 239);
println!("\n/0 or greater subnets between {} and {}:", start, end);
// Output all subnets starting with the largest that will fit. This
// will give us the smallest possible set of valid subnets.
//
// Output:
// subnet 0 = 10.0.0.0/25
// subnet 1 = 10.0.0.128/26
// subnet 2 = 10.0.0.192/27
// subnet 3 = 10.0.0.224/28
let subnets = Ipv4Subnets::new(start, end, 0);
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
println!("\n/26 or greater subnets between {} and {}:", start, end);
// Output all subnets with prefix lengths less than or equal to 26.
// This results in more subnets, but limits them to a maximum size.
//
// Output:
// subnet 0 = 10.0.0.0/26
// subnet 1 = 10.0.0.64/26
// subnet 2 = 10.0.0.128/26
// subnet 3 = 10.0.0.192/27
// subnet 4 = 10.0.0.224/28
let subnets = Ipv4Subnets::new(start, end, 26);
for (i, n) in subnets.enumerate() {
println!("\tsubnet {} = {}", i, n);
}
}
```
### Aggregate a list of IP prefixes
```rust
extern crate ipnet;
use ipnet::IpNet;
fn main() {}
// Example input list of overlapping and adjacent prefixes.
let strings = vec![
"10.0.0.0/24", "10.0.1.0/24", "10.0.1.1/24", "10.0.1.2/24",
"10.0.2.0/24",
"10.1.0.0/24", "10.1.1.0/24",
"192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24", "192.168.3.0/24",
"fd00::/32", "fd00:1::/32",
];
let nets: Vec<IpNet> = strings.iter().filter_map(|p| p.parse().ok()).collect();
println!("\nAggregated IP prefixes:");
// Output:
// 10.0.0.0/23
// 10.0.2.0/24
// 10.1.0.0/23
// 192.168.0.0/22
// fd00::/31
for n in IpNet::aggregate(&nets) {
println!("\t{}", n);
}
}
```
## Future
* Implementing `std::ops::{Add, Sub, BitAnd, BitOr}` for `Ipv4Addr` and `Ipv6Addr` would be useful as these are common operations on IP addresses. If done, the extension traits provided in this module would be removed and the major version incremented. Implementing these requires a change to the standard library. I've started a thread on this topic on the [Rust Internals](https://internals.rust-lang.org/t/pre-rfc-implementing-add-sub-bitand-bitor-for-ipaddr-ipv4addr-ipv6addr/) discussion board.
* The results of `hosts()` and potentially `subnets()` should be represented as a `Range` rather than the custom `IpAddrRange` and `IpSubnets` types provided in this module. This requires the target types to have `Add` and `Step` implemented for them. Implementing `Add` for `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` requires a change to the standard library (see above). And `Step` is still unstable so exploring this will also wait until it has stablized.
## License
Copyright (c) 2017, Juniper Networks, Inc. All rights reserved.
This code is licensed to you under either the MIT License or Apache License, Version 2.0 at your choice (the "License"). You may not use this code except in compliance with the License. This code is not an official Juniper product. You can obtain a copy of the License at: https://opensource.org/licenses/MIT or http://www.apache.org/licenses/LICENSE-2.0
+51 -51
View File
@@ -1,51 +1,51 @@
# Releases
## Version 2.3.0 (2020-03-15)
* Merge @imp's `Default` implementation. See #18. `Ipv4Net` and `Ipv6Net` now default to 0.0.0.0/0 and ::/0 respectively. `IpNet` defaults to the 0/0 `Ipv4Net`.
* Add `#[allow(arithmetic_overflow)]` for `Ipv4AddrRange::count()` and `Ipv6AddrRange::count()`. Since 1.43.0-nightly it gives a build error but this panic behavior is desired. In future it may be replaced with explicit use of `panic!`. See #21.
## Version 2.2.0 (2020-02-02)
* Implement `From<IpAddr>`, `From<Ipv4Addr>`, and `From<Ipv6Addr>` for `IpNet`, `Ipv4Net`, and `Ipv6Net` respectively.
## Version 2.1.0 (2019-11-08)
* Implement `FusedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`, `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets`.
* Implement `DoubleEndedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`.
* Implement custom `count()`, `last()`, `max()`, `min()`, `nth()`, and `size_hint()` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`.
## Version 2.0.1 (2019-10-12)
* Fix bug where IpAddrRange never ends when start and end are both 0 #11
* Fix warning about missing 'dyn'
## Version 2.0.0 (2018-08-21)
* The `Emu128` module has been removed. This provided an emulated 128-bit integer for supporting IPv6 addresses. As of Rust 1.26 the built-in 128-bit integers have been marked stable and this library has been updated to use these instead of `Emu128`.
* The `with-serde` feature name shim has been removed. The `serde` feature should now be used using the bare `serde` feature name per the Rust API Guidelines.
* The `Deref` on `Ipv4Net` and `Ipv6Net` has been removed. This dereferenced to the `Ipv4Addr` and `Ipv6Addr` contained in the type. To use these methods call them directly on the contained IP address of interest, which may be accessed using the `addr()` or `network()` methods.
* In prior versions it was necessary to use the `Contains` trait to access the `contains()` methods. These are now inherited in public methods on the `IpNet`, `Ipv4Net`, and `Ipv6Net` types so are always available.
* The implementations of `IpAdd<u32>` and `IpSub<u32>` for IpAddr have been removed.
* The implementations of `IpAdd<u32>` and `IpSub<u32>` for `Ipv6Addr` have been removed.
## Version 1.2.1 (2018-06-06)
* Fix to resolve an issue with the optional serde support, where compact binary formats were not properly supported. See issue #10.
## Version 1.2.0 (2018-04-17)
* The previous release (1.1.0) introduced serde support using the feature name `with-serde`, but the Rust API Guidelines recommend using `serde` as the name of the feature. This release changes the feature name from `with-serde` to `serde`, but it is backwards compatible for those that already started using the `with-serde` feature name. The 1.1.0 release was yanked on crates.io to discourage further use of this feature name. See pull request #7.
## Version 1.1.0 (2018-04-13)
* Adds serde support. See pull request #6.
# Releases
## Version 2.3.0 (2020-03-15)
* Merge @imp's `Default` implementation. See #18. `Ipv4Net` and `Ipv6Net` now default to 0.0.0.0/0 and ::/0 respectively. `IpNet` defaults to the 0/0 `Ipv4Net`.
* Add `#[allow(arithmetic_overflow)]` for `Ipv4AddrRange::count()` and `Ipv6AddrRange::count()`. Since 1.43.0-nightly it gives a build error but this panic behavior is desired. In future it may be replaced with explicit use of `panic!`. See #21.
## Version 2.2.0 (2020-02-02)
* Implement `From<IpAddr>`, `From<Ipv4Addr>`, and `From<Ipv6Addr>` for `IpNet`, `Ipv4Net`, and `Ipv6Net` respectively.
## Version 2.1.0 (2019-11-08)
* Implement `FusedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`, `IpSubnets`, `Ipv4Subnets`, and `Ipv6Subnets`.
* Implement `DoubleEndedIterator` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`.
* Implement custom `count()`, `last()`, `max()`, `min()`, `nth()`, and `size_hint()` for `IpAddrRange`, `Ipv4AddrRange`, `Ipv6AddrRange`.
## Version 2.0.1 (2019-10-12)
* Fix bug where IpAddrRange never ends when start and end are both 0 #11
* Fix warning about missing 'dyn'
## Version 2.0.0 (2018-08-21)
* The `Emu128` module has been removed. This provided an emulated 128-bit integer for supporting IPv6 addresses. As of Rust 1.26 the built-in 128-bit integers have been marked stable and this library has been updated to use these instead of `Emu128`.
* The `with-serde` feature name shim has been removed. The `serde` feature should now be used using the bare `serde` feature name per the Rust API Guidelines.
* The `Deref` on `Ipv4Net` and `Ipv6Net` has been removed. This dereferenced to the `Ipv4Addr` and `Ipv6Addr` contained in the type. To use these methods call them directly on the contained IP address of interest, which may be accessed using the `addr()` or `network()` methods.
* In prior versions it was necessary to use the `Contains` trait to access the `contains()` methods. These are now inherited in public methods on the `IpNet`, `Ipv4Net`, and `Ipv6Net` types so are always available.
* The implementations of `IpAdd<u32>` and `IpSub<u32>` for IpAddr have been removed.
* The implementations of `IpAdd<u32>` and `IpSub<u32>` for `Ipv6Addr` have been removed.
## Version 1.2.1 (2018-06-06)
* Fix to resolve an issue with the optional serde support, where compact binary formats were not properly supported. See issue #10.
## Version 1.2.0 (2018-04-17)
* The previous release (1.1.0) introduced serde support using the feature name `with-serde`, but the Rust API Guidelines recommend using `serde` as the name of the feature. This release changes the feature name from `with-serde` to `serde`, but it is backwards compatible for those that already started using the `with-serde` feature name. The 1.1.0 release was yanked on crates.io to discourage further use of this feature name. See pull request #7.
## Version 1.1.0 (2018-04-13)
* Adds serde support. See pull request #6.
+965 -965
View File
File diff suppressed because it is too large Load Diff
+1744 -1744
View File
File diff suppressed because it is too large Load Diff
+348 -348
View File
@@ -1,349 +1,349 @@
//! A private parser implementation of IPv4 and IPv6 network addresses.
//!
//! The existing `std::net::parser` module cannot be extended because it
//! is private. It is copied and extended here with methods for parsing
//! IP network addresses.
use std::error::Error;
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
pub struct Parser<'a> {
// parsing as ASCII, so can use byte array
s: &'a [u8],
pos: usize,
}
impl<'a> Parser<'a> {
fn new(s: &'a str) -> Parser<'a> {
Parser {
s: s.as_bytes(),
pos: 0,
}
}
fn is_eof(&self) -> bool {
self.pos == self.s.len()
}
// Commit only if parser returns Some
fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
F: FnOnce(&mut Parser) -> Option<T>,
{
let pos = self.pos;
let r = cb(self);
if r.is_none() {
self.pos = pos;
}
r
}
// Commit only if parser read till EOF
fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
F: FnOnce(&mut Parser) -> Option<T>,
{
self.read_atomically(move |p| {
match cb(p) {
Some(x) => if p.is_eof() {Some(x)} else {None},
None => None,
}
})
}
// Return result of first successful parser
fn read_or<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser) -> Option<T> + 'static>])
-> Option<T> {
for pf in parsers {
if let Some(r) = self.read_atomically(|p: &mut Parser| pf(p)) {
return Some(r);
}
}
None
}
// Apply 3 parsers sequentially
fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
pa: PA,
pb: PB,
pc: PC)
-> Option<(A, B, C)> where
PA: FnOnce(&mut Parser) -> Option<A>,
PB: FnOnce(&mut Parser) -> Option<B>,
PC: FnOnce(&mut Parser) -> Option<C>,
{
self.read_atomically(move |p| {
let a = pa(p);
let b = if a.is_some() { pb(p) } else { None };
let c = if b.is_some() { pc(p) } else { None };
match (a, b, c) {
(Some(a), Some(b), Some(c)) => Some((a, b, c)),
_ => None
}
})
}
// Read next char
fn read_char(&mut self) -> Option<char> {
if self.is_eof() {
None
} else {
let r = self.s[self.pos] as char;
self.pos += 1;
Some(r)
}
}
// Return char and advance iff next char is equal to requested
fn read_given_char(&mut self, c: char) -> Option<char> {
self.read_atomically(|p| {
match p.read_char() {
Some(next) if next == c => Some(next),
_ => None,
}
})
}
// Read digit
fn read_digit(&mut self, radix: u8) -> Option<u8> {
fn parse_digit(c: char, radix: u8) -> Option<u8> {
let c = c as u8;
// assuming radix is either 10 or 16
if c >= b'0' && c <= b'9' {
Some(c - b'0')
} else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) {
Some(c - b'a' + 10)
} else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) {
Some(c - b'A' + 10)
} else {
None
}
}
self.read_atomically(|p| {
p.read_char().and_then(|c| parse_digit(c, radix))
})
}
fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
let mut r = 0;
let mut digit_count = 0;
loop {
match self.read_digit(radix) {
Some(d) => {
r = r * (radix as u32) + (d as u32);
digit_count += 1;
if digit_count > max_digits || r >= upto {
return None
}
}
None => {
if digit_count == 0 {
return None
} else {
return Some(r)
}
}
};
}
}
// Read number, failing if max_digits of number value exceeded
fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto))
}
fn read_ipv4_addr_impl(&mut self) -> Option<Ipv4Addr> {
let mut bs = [0; 4];
let mut i = 0;
while i < 4 {
if i != 0 && self.read_given_char('.').is_none() {
return None;
}
let octet = self.read_number(10, 3, 0x100).map(|n| n as u8);
match octet {
Some(d) => bs[i] = d,
None => return None,
};
i += 1;
}
Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3]))
}
// Read IPv4 address
fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
self.read_atomically(|p| p.read_ipv4_addr_impl())
}
fn read_ipv6_addr_impl(&mut self) -> Option<Ipv6Addr> {
fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
assert!(head.len() + tail.len() <= 8);
let mut gs = [0; 8];
gs[..head.len()].copy_from_slice(head);
gs[(8 - tail.len()) .. 8].copy_from_slice(tail);
Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
}
fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize)
-> (usize, bool) {
let mut i = 0;
while i < limit {
if i < limit - 1 {
let ipv4 = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() {
p.read_ipv4_addr()
} else {
None
}
});
if let Some(v4_addr) = ipv4 {
let octets = v4_addr.octets();
groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16);
groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16);
return (i + 2, true);
}
}
let group = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() {
p.read_number(16, 4, 0x10000).map(|n| n as u16)
} else {
None
}
});
match group {
Some(g) => groups[i] = g,
None => return (i, false)
}
i += 1;
}
(i, false)
}
let mut head = [0; 8];
let (head_size, head_ipv4) = read_groups(self, &mut head, 8);
if head_size == 8 {
return Some(Ipv6Addr::new(
head[0], head[1], head[2], head[3],
head[4], head[5], head[6], head[7]))
}
// IPv4 part is not allowed before `::`
if head_ipv4 {
return None
}
// read `::` if previous code parsed less than 8 groups
if !self.read_given_char(':').is_some() || !self.read_given_char(':').is_some() {
return None;
}
let mut tail = [0; 8];
let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size);
Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size]))
}
fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
self.read_atomically(|p| p.read_ipv6_addr_impl())
}
/* Additions for IpNet below. */
// Read IPv4 network
fn read_ipv4_net(&mut self) -> Option<Ipv4Net> {
let ip_addr = |p: &mut Parser| p.read_ipv4_addr();
let slash = |p: &mut Parser| p.read_given_char('/');
let prefix_len = |p: &mut Parser| {
p.read_number(10, 2, 33).map(|n| n as u8)
};
self.read_seq_3(ip_addr, slash, prefix_len).map(|t| {
let (ip, _, prefix_len): (Ipv4Addr, char, u8) = t;
Ipv4Net::new(ip, prefix_len).unwrap()
})
}
// Read Ipv6 network
fn read_ipv6_net(&mut self) -> Option<Ipv6Net> {
let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
let slash = |p: &mut Parser| p.read_given_char('/');
let prefix_len = |p: &mut Parser| {
p.read_number(10, 3, 129).map(|n| n as u8)
};
self.read_seq_3(ip_addr, slash, prefix_len).map(|t| {
let (ip, _, prefix_len): (Ipv6Addr, char, u8) = t;
Ipv6Net::new(ip, prefix_len).unwrap()
})
}
fn read_ip_net(&mut self) -> Option<IpNet> {
let ipv4_net = |p: &mut Parser| p.read_ipv4_net().map(IpNet::V4);
let ipv6_net = |p: &mut Parser| p.read_ipv6_net().map(IpNet::V6);
self.read_or(&mut [Box::new(ipv4_net), Box::new(ipv6_net)])
}
/* Additions for IpNet above. */
}
/* Additions for IpNet below. */
impl FromStr for IpNet {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<IpNet, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ip_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
impl FromStr for Ipv4Net {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv4Net, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ipv4_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
impl FromStr for Ipv6Net {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv6Net, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ipv6_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
/* Additions for IpNet above. */
/// An error which can be returned when parsing an IP network address.
///
/// This error is used as the error type for the [`FromStr`] implementation for
/// [`IpNet`], [`Ipv4Net`], and [`Ipv6Net`].
///
/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
/// [`IpNet`]: enum.IpNet.html
/// [`Ipv4Net`]: struct.Ipv4Net.html
/// [`Ipv6Net`]: struct.Ipv6Net.html
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddrParseError(());
impl fmt::Display for AddrParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(self.description())
}
}
impl Error for AddrParseError {
fn description(&self) -> &str {
"invalid IP address syntax"
}
//! A private parser implementation of IPv4 and IPv6 network addresses.
//!
//! The existing `std::net::parser` module cannot be extended because it
//! is private. It is copied and extended here with methods for parsing
//! IP network addresses.
use std::error::Error;
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
pub struct Parser<'a> {
// parsing as ASCII, so can use byte array
s: &'a [u8],
pos: usize,
}
impl<'a> Parser<'a> {
fn new(s: &'a str) -> Parser<'a> {
Parser {
s: s.as_bytes(),
pos: 0,
}
}
fn is_eof(&self) -> bool {
self.pos == self.s.len()
}
// Commit only if parser returns Some
fn read_atomically<T, F>(&mut self, cb: F) -> Option<T> where
F: FnOnce(&mut Parser) -> Option<T>,
{
let pos = self.pos;
let r = cb(self);
if r.is_none() {
self.pos = pos;
}
r
}
// Commit only if parser read till EOF
fn read_till_eof<T, F>(&mut self, cb: F) -> Option<T> where
F: FnOnce(&mut Parser) -> Option<T>,
{
self.read_atomically(move |p| {
match cb(p) {
Some(x) => if p.is_eof() {Some(x)} else {None},
None => None,
}
})
}
// Return result of first successful parser
fn read_or<T>(&mut self, parsers: &mut [Box<dyn FnMut(&mut Parser) -> Option<T> + 'static>])
-> Option<T> {
for pf in parsers {
if let Some(r) = self.read_atomically(|p: &mut Parser| pf(p)) {
return Some(r);
}
}
None
}
// Apply 3 parsers sequentially
fn read_seq_3<A, B, C, PA, PB, PC>(&mut self,
pa: PA,
pb: PB,
pc: PC)
-> Option<(A, B, C)> where
PA: FnOnce(&mut Parser) -> Option<A>,
PB: FnOnce(&mut Parser) -> Option<B>,
PC: FnOnce(&mut Parser) -> Option<C>,
{
self.read_atomically(move |p| {
let a = pa(p);
let b = if a.is_some() { pb(p) } else { None };
let c = if b.is_some() { pc(p) } else { None };
match (a, b, c) {
(Some(a), Some(b), Some(c)) => Some((a, b, c)),
_ => None
}
})
}
// Read next char
fn read_char(&mut self) -> Option<char> {
if self.is_eof() {
None
} else {
let r = self.s[self.pos] as char;
self.pos += 1;
Some(r)
}
}
// Return char and advance iff next char is equal to requested
fn read_given_char(&mut self, c: char) -> Option<char> {
self.read_atomically(|p| {
match p.read_char() {
Some(next) if next == c => Some(next),
_ => None,
}
})
}
// Read digit
fn read_digit(&mut self, radix: u8) -> Option<u8> {
fn parse_digit(c: char, radix: u8) -> Option<u8> {
let c = c as u8;
// assuming radix is either 10 or 16
if c >= b'0' && c <= b'9' {
Some(c - b'0')
} else if radix > 10 && c >= b'a' && c < b'a' + (radix - 10) {
Some(c - b'a' + 10)
} else if radix > 10 && c >= b'A' && c < b'A' + (radix - 10) {
Some(c - b'A' + 10)
} else {
None
}
}
self.read_atomically(|p| {
p.read_char().and_then(|c| parse_digit(c, radix))
})
}
fn read_number_impl(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
let mut r = 0;
let mut digit_count = 0;
loop {
match self.read_digit(radix) {
Some(d) => {
r = r * (radix as u32) + (d as u32);
digit_count += 1;
if digit_count > max_digits || r >= upto {
return None
}
}
None => {
if digit_count == 0 {
return None
} else {
return Some(r)
}
}
};
}
}
// Read number, failing if max_digits of number value exceeded
fn read_number(&mut self, radix: u8, max_digits: u32, upto: u32) -> Option<u32> {
self.read_atomically(|p| p.read_number_impl(radix, max_digits, upto))
}
fn read_ipv4_addr_impl(&mut self) -> Option<Ipv4Addr> {
let mut bs = [0; 4];
let mut i = 0;
while i < 4 {
if i != 0 && self.read_given_char('.').is_none() {
return None;
}
let octet = self.read_number(10, 3, 0x100).map(|n| n as u8);
match octet {
Some(d) => bs[i] = d,
None => return None,
};
i += 1;
}
Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3]))
}
// Read IPv4 address
fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
self.read_atomically(|p| p.read_ipv4_addr_impl())
}
fn read_ipv6_addr_impl(&mut self) -> Option<Ipv6Addr> {
fn ipv6_addr_from_head_tail(head: &[u16], tail: &[u16]) -> Ipv6Addr {
assert!(head.len() + tail.len() <= 8);
let mut gs = [0; 8];
gs[..head.len()].copy_from_slice(head);
gs[(8 - tail.len()) .. 8].copy_from_slice(tail);
Ipv6Addr::new(gs[0], gs[1], gs[2], gs[3], gs[4], gs[5], gs[6], gs[7])
}
fn read_groups(p: &mut Parser, groups: &mut [u16; 8], limit: usize)
-> (usize, bool) {
let mut i = 0;
while i < limit {
if i < limit - 1 {
let ipv4 = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() {
p.read_ipv4_addr()
} else {
None
}
});
if let Some(v4_addr) = ipv4 {
let octets = v4_addr.octets();
groups[i + 0] = ((octets[0] as u16) << 8) | (octets[1] as u16);
groups[i + 1] = ((octets[2] as u16) << 8) | (octets[3] as u16);
return (i + 2, true);
}
}
let group = p.read_atomically(|p| {
if i == 0 || p.read_given_char(':').is_some() {
p.read_number(16, 4, 0x10000).map(|n| n as u16)
} else {
None
}
});
match group {
Some(g) => groups[i] = g,
None => return (i, false)
}
i += 1;
}
(i, false)
}
let mut head = [0; 8];
let (head_size, head_ipv4) = read_groups(self, &mut head, 8);
if head_size == 8 {
return Some(Ipv6Addr::new(
head[0], head[1], head[2], head[3],
head[4], head[5], head[6], head[7]))
}
// IPv4 part is not allowed before `::`
if head_ipv4 {
return None
}
// read `::` if previous code parsed less than 8 groups
if !self.read_given_char(':').is_some() || !self.read_given_char(':').is_some() {
return None;
}
let mut tail = [0; 8];
let (tail_size, _) = read_groups(self, &mut tail, 8 - head_size);
Some(ipv6_addr_from_head_tail(&head[..head_size], &tail[..tail_size]))
}
fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
self.read_atomically(|p| p.read_ipv6_addr_impl())
}
/* Additions for IpNet below. */
// Read IPv4 network
fn read_ipv4_net(&mut self) -> Option<Ipv4Net> {
let ip_addr = |p: &mut Parser| p.read_ipv4_addr();
let slash = |p: &mut Parser| p.read_given_char('/');
let prefix_len = |p: &mut Parser| {
p.read_number(10, 2, 33).map(|n| n as u8)
};
self.read_seq_3(ip_addr, slash, prefix_len).map(|t| {
let (ip, _, prefix_len): (Ipv4Addr, char, u8) = t;
Ipv4Net::new(ip, prefix_len).unwrap()
})
}
// Read Ipv6 network
fn read_ipv6_net(&mut self) -> Option<Ipv6Net> {
let ip_addr = |p: &mut Parser| p.read_ipv6_addr();
let slash = |p: &mut Parser| p.read_given_char('/');
let prefix_len = |p: &mut Parser| {
p.read_number(10, 3, 129).map(|n| n as u8)
};
self.read_seq_3(ip_addr, slash, prefix_len).map(|t| {
let (ip, _, prefix_len): (Ipv6Addr, char, u8) = t;
Ipv6Net::new(ip, prefix_len).unwrap()
})
}
fn read_ip_net(&mut self) -> Option<IpNet> {
let ipv4_net = |p: &mut Parser| p.read_ipv4_net().map(IpNet::V4);
let ipv6_net = |p: &mut Parser| p.read_ipv6_net().map(IpNet::V6);
self.read_or(&mut [Box::new(ipv4_net), Box::new(ipv6_net)])
}
/* Additions for IpNet above. */
}
/* Additions for IpNet below. */
impl FromStr for IpNet {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<IpNet, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ip_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
impl FromStr for Ipv4Net {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv4Net, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ipv4_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
impl FromStr for Ipv6Net {
type Err = AddrParseError;
fn from_str(s: &str) -> Result<Ipv6Net, AddrParseError> {
match Parser::new(s).read_till_eof(|p| p.read_ipv6_net()) {
Some(s) => Ok(s),
None => Err(AddrParseError(()))
}
}
}
/* Additions for IpNet above. */
/// An error which can be returned when parsing an IP network address.
///
/// This error is used as the error type for the [`FromStr`] implementation for
/// [`IpNet`], [`Ipv4Net`], and [`Ipv6Net`].
///
/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
/// [`IpNet`]: enum.IpNet.html
/// [`Ipv4Net`]: struct.Ipv4Net.html
/// [`Ipv6Net`]: struct.Ipv6Net.html
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddrParseError(());
impl fmt::Display for AddrParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(self.description())
}
}
impl Error for AddrParseError {
fn description(&self) -> &str {
"invalid IP address syntax"
}
}