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
}
@@ -111,19 +122,15 @@ impl Debug for IpAddress {
111
122
112
123
impl Default for IpAddress {
113
124
fn default ( ) -> Self {
114
- Self { addr : [ 0u32 ; 4 ] }
125
+ Self :: ZERO
115
126
}
116
127
}
117
128
118
129
impl From < core:: net:: IpAddr > for IpAddress {
119
130
fn from ( t : core:: net:: IpAddr ) -> Self {
120
131
match t {
121
- core:: net:: IpAddr :: V4 ( ip) => Self {
122
- v4 : Ipv4Address :: from ( ip) ,
123
- } ,
124
- core:: net:: IpAddr :: V6 ( ip) => Self {
125
- v6 : Ipv6Address :: from ( ip) ,
126
- } ,
132
+ core:: net:: IpAddr :: V4 ( ip) => Self :: new_v4 ( ip. octets ( ) ) ,
133
+ core:: net:: IpAddr :: V6 ( ip) => Self :: new_v6 ( ip. octets ( ) ) ,
127
134
}
128
135
}
129
136
}
0 commit comments