99//! - [`Ipv6Address`]
1010
1111use core:: fmt:: { self , Debug , Formatter } ;
12+ use core:: mem;
1213use core:: net:: { IpAddr as StdIpAddr , Ipv4Addr as StdIpv4Addr , Ipv6Addr as StdIpv6Addr } ;
1314
1415/// An IPv4 internet protocol address.
@@ -83,20 +84,47 @@ pub union IpAddress {
8384}
8485
8586impl 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+
8694 /// Construct a new IPv4 address.
95+ ///
96+ /// The type won't know that it is an IPv6 address and additional context
97+ /// is needed.
8798 #[ 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
92104 }
93105
94106 /// Construct a new IPv6 address.
107+ ///
108+ /// The type won't know that it is an IPv6 address and additional context
109+ /// is needed.
95110 #[ 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 )
100128 }
101129}
102130
@@ -111,19 +139,15 @@ impl Debug for IpAddress {
111139
112140impl Default for IpAddress {
113141 fn default ( ) -> Self {
114- Self { addr : [ 0u32 ; 4 ] }
142+ Self :: new_zeroed ( )
115143 }
116144}
117145
118146impl From < StdIpAddr > for IpAddress {
119147 fn from ( t : StdIpAddr ) -> Self {
120148 match t {
121- StdIpAddr :: V4 ( ip) => Self {
122- v4 : Ipv4Address :: from ( ip) ,
123- } ,
124- StdIpAddr :: V6 ( ip) => Self {
125- v6 : Ipv6Address :: from ( ip) ,
126- } ,
149+ StdIpAddr :: V4 ( ip) => Self :: new_v4 ( ip. octets ( ) ) ,
150+ StdIpAddr :: V6 ( ip) => Self :: new_v6 ( ip. octets ( ) ) ,
127151 }
128152 }
129153}
0 commit comments