@@ -10,6 +10,7 @@ use crate::cmp::Ordering;
10
10
use crate :: fmt:: { self , Write as FmtWrite } ;
11
11
use crate :: hash;
12
12
use crate :: io:: Write as IoWrite ;
13
+ use crate :: mem:: transmute;
13
14
use crate :: sys:: net:: netc as c;
14
15
use crate :: sys_common:: { AsInner , FromInner } ;
15
16
@@ -1045,27 +1046,23 @@ impl Ipv6Addr {
1045
1046
/// ```
1046
1047
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1047
1048
#[ rustc_const_stable( feature = "const_ipv6" , since = "1.32.0" ) ]
1049
+ #[ allow_internal_unstable( const_fn_transmute) ]
1048
1050
pub const fn new ( a : u16 , b : u16 , c : u16 , d : u16 , e : u16 , f : u16 , g : u16 , h : u16 ) -> Ipv6Addr {
1051
+ let addr16 = [
1052
+ a. to_be ( ) ,
1053
+ b. to_be ( ) ,
1054
+ c. to_be ( ) ,
1055
+ d. to_be ( ) ,
1056
+ e. to_be ( ) ,
1057
+ f. to_be ( ) ,
1058
+ g. to_be ( ) ,
1059
+ h. to_be ( ) ,
1060
+ ] ;
1049
1061
Ipv6Addr {
1050
1062
inner : c:: in6_addr {
1051
- s6_addr : [
1052
- ( a >> 8 ) as u8 ,
1053
- a as u8 ,
1054
- ( b >> 8 ) as u8 ,
1055
- b as u8 ,
1056
- ( c >> 8 ) as u8 ,
1057
- c as u8 ,
1058
- ( d >> 8 ) as u8 ,
1059
- d as u8 ,
1060
- ( e >> 8 ) as u8 ,
1061
- e as u8 ,
1062
- ( f >> 8 ) as u8 ,
1063
- f as u8 ,
1064
- ( g >> 8 ) as u8 ,
1065
- g as u8 ,
1066
- ( h >> 8 ) as u8 ,
1067
- h as u8 ,
1068
- ] ,
1063
+ // All elements in `addr16` are big endian.
1064
+ // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1065
+ s6_addr : unsafe { transmute :: < _ , [ u8 ; 16 ] > ( addr16) } ,
1069
1066
} ,
1070
1067
}
1071
1068
}
@@ -1108,16 +1105,19 @@ impl Ipv6Addr {
1108
1105
/// ```
1109
1106
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1110
1107
pub fn segments ( & self ) -> [ u16 ; 8 ] {
1111
- let arr = & self . inner . s6_addr ;
1108
+ // All elements in `s6_addr` must be big endian.
1109
+ // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1110
+ let [ a, b, c, d, e, f, g, h] = unsafe { transmute :: < _ , [ u16 ; 8 ] > ( self . inner . s6_addr ) } ;
1111
+ // We want native endian u16
1112
1112
[
1113
- u16:: from_be_bytes ( [ arr [ 0 ] , arr [ 1 ] ] ) ,
1114
- u16:: from_be_bytes ( [ arr [ 2 ] , arr [ 3 ] ] ) ,
1115
- u16:: from_be_bytes ( [ arr [ 4 ] , arr [ 5 ] ] ) ,
1116
- u16:: from_be_bytes ( [ arr [ 6 ] , arr [ 7 ] ] ) ,
1117
- u16:: from_be_bytes ( [ arr [ 8 ] , arr [ 9 ] ] ) ,
1118
- u16:: from_be_bytes ( [ arr [ 10 ] , arr [ 11 ] ] ) ,
1119
- u16:: from_be_bytes ( [ arr [ 12 ] , arr [ 13 ] ] ) ,
1120
- u16:: from_be_bytes ( [ arr [ 14 ] , arr [ 15 ] ] ) ,
1113
+ u16:: from_be ( a ) ,
1114
+ u16:: from_be ( b ) ,
1115
+ u16:: from_be ( c ) ,
1116
+ u16:: from_be ( d ) ,
1117
+ u16:: from_be ( e ) ,
1118
+ u16:: from_be ( f ) ,
1119
+ u16:: from_be ( g ) ,
1120
+ u16:: from_be ( h ) ,
1121
1121
]
1122
1122
}
1123
1123
0 commit comments