9
9
//! - [`Ipv6Address`]
10
10
11
11
use core:: fmt:: { self , Debug , Formatter } ;
12
+ use core:: mem;
12
13
use core:: net:: { IpAddr as StdIpAddr , Ipv4Addr as StdIpv4Addr , Ipv6Addr as StdIpv6Addr } ;
13
14
14
15
/// An IPv4 internet protocol address.
@@ -83,20 +84,47 @@ pub union IpAddress {
83
84
}
84
85
85
86
impl IpAddress {
87
+ /// Construct a new zeroed address.
88
+ #[ must_use]
89
+ pub const fn new_zeroed ( ) -> Self {
90
+ // SAFETY: All bit patterns are valid.
91
+ unsafe { mem:: zeroed ( ) }
92
+ }
93
+
86
94
/// Construct a new IPv4 address.
95
+ ///
96
+ /// The type won't know that it is an IPv6 address and additional context
97
+ /// is needed.
87
98
#[ must_use]
88
- pub const fn new_v4 ( ip_addr : [ u8 ; 4 ] ) -> Self {
89
- Self {
90
- v4 : Ipv4Address ( ip_addr) ,
91
- }
99
+ pub const fn new_v4 ( octets : [ u8 ; 4 ] ) -> Self {
100
+ // Initialize all bytes to zero first.
101
+ let mut obj = Self :: new_zeroed ( ) ;
102
+ obj. v4 = Ipv4Address ( octets) ;
103
+ obj
92
104
}
93
105
94
106
/// Construct a new IPv6 address.
107
+ ///
108
+ /// The type won't know that it is an IPv6 address and additional context
109
+ /// is needed.
95
110
#[ must_use]
96
- pub const fn new_v6 ( ip_addr : [ u8 ; 16 ] ) -> Self {
97
- Self {
98
- v6 : Ipv6Address ( ip_addr) ,
99
- }
111
+ pub const fn new_v6 ( octets : [ u8 ; 16 ] ) -> Self {
112
+ // Initialize all bytes to zero first.
113
+ let mut obj = Self :: new_zeroed ( ) ;
114
+ obj. v6 = Ipv6Address ( octets) ;
115
+ obj
116
+ }
117
+
118
+ /// Returns a raw pointer to the IP address.
119
+ #[ must_use]
120
+ pub const fn as_ptr ( & self ) -> * const Self {
121
+ core:: ptr:: addr_of!( * self )
122
+ }
123
+
124
+ /// Returns a raw mutable pointer to the IP address.
125
+ #[ must_use]
126
+ pub const fn as_ptr_mut ( & mut self ) -> * mut Self {
127
+ core:: ptr:: addr_of_mut!( * self )
100
128
}
101
129
102
130
/// Returns the octets of the union. Without additional context, it is not
@@ -121,19 +149,15 @@ impl Debug for IpAddress {
121
149
122
150
impl Default for IpAddress {
123
151
fn default ( ) -> Self {
124
- Self { addr : [ 0u32 ; 4 ] }
152
+ Self :: new_zeroed ( )
125
153
}
126
154
}
127
155
128
156
impl From < StdIpAddr > for IpAddress {
129
157
fn from ( t : StdIpAddr ) -> Self {
130
158
match t {
131
- StdIpAddr :: V4 ( ip) => Self {
132
- v4 : Ipv4Address :: from ( ip) ,
133
- } ,
134
- StdIpAddr :: V6 ( ip) => Self {
135
- v6 : Ipv6Address :: from ( ip) ,
136
- } ,
159
+ StdIpAddr :: V4 ( ip) => Self :: new_v4 ( ip. octets ( ) ) ,
160
+ StdIpAddr :: V6 ( ip) => Self :: new_v6 ( ip. octets ( ) ) ,
137
161
}
138
162
}
139
163
}
0 commit comments