|
8 | 8 | //! - [`Ipv4Address`]
|
9 | 9 | //! - [`Ipv6Address`]
|
10 | 10 |
|
11 |
| -use core::fmt; |
12 |
| -use core::fmt::{Debug, Formatter}; |
| 11 | +use core::fmt::{self, Debug, Formatter}; |
13 | 12 |
|
14 | 13 | /// An IPv4 internet protocol address.
|
15 | 14 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
@@ -83,19 +82,31 @@ pub union IpAddress {
|
83 | 82 | }
|
84 | 83 |
|
85 | 84 | impl IpAddress {
|
| 85 | + /// Zeroed variant where all bytes are guaranteed to be initialized to zero. |
| 86 | + pub const ZERO: Self = Self { addr: [0; 4] }; |
| 87 | + |
86 | 88 | /// Construct a new IPv4 address.
|
| 89 | + /// |
| 90 | + /// The type won't know that it is an IPv6 address and additional context |
| 91 | + /// is needed. |
| 92 | + /// |
| 93 | + /// # Safety |
| 94 | + /// The constructor only initializes the bytes needed for IPv4 addresses. |
87 | 95 | #[must_use]
|
88 |
| - pub const fn new_v4(ip_addr: [u8; 4]) -> Self { |
| 96 | + pub const fn new_v4(octets: [u8; 4]) -> Self { |
89 | 97 | Self {
|
90 |
| - v4: Ipv4Address(ip_addr), |
| 98 | + v4: Ipv4Address(octets), |
91 | 99 | }
|
92 | 100 | }
|
93 | 101 |
|
94 | 102 | /// Construct a new IPv6 address.
|
| 103 | + /// |
| 104 | + /// The type won't know that it is an IPv6 address and additional context |
| 105 | + /// is needed. |
95 | 106 | #[must_use]
|
96 |
| - pub const fn new_v6(ip_addr: [u8; 16]) -> Self { |
| 107 | + pub const fn new_v6(octets: [u8; 16]) -> Self { |
97 | 108 | Self {
|
98 |
| - v6: Ipv6Address(ip_addr), |
| 109 | + v6: Ipv6Address(octets), |
99 | 110 | }
|
100 | 111 | }
|
101 | 112 |
|
@@ -132,19 +143,15 @@ impl Debug for IpAddress {
|
132 | 143 |
|
133 | 144 | impl Default for IpAddress {
|
134 | 145 | fn default() -> Self {
|
135 |
| - Self { addr: [0u32; 4] } |
| 146 | + Self::ZERO |
136 | 147 | }
|
137 | 148 | }
|
138 | 149 |
|
139 | 150 | impl From<core::net::IpAddr> for IpAddress {
|
140 | 151 | fn from(t: core::net::IpAddr) -> Self {
|
141 | 152 | match t {
|
142 |
| - core::net::IpAddr::V4(ip) => Self { |
143 |
| - v4: Ipv4Address::from(ip), |
144 |
| - }, |
145 |
| - core::net::IpAddr::V6(ip) => Self { |
146 |
| - v6: Ipv6Address::from(ip), |
147 |
| - }, |
| 153 | + core::net::IpAddr::V4(ip) => Self::new_v4(ip.octets()), |
| 154 | + core::net::IpAddr::V6(ip) => Self::new_v6(ip.octets()), |
148 | 155 | }
|
149 | 156 | }
|
150 | 157 | }
|
|
0 commit comments