@@ -7,7 +7,6 @@ use rdma_sys::{ibv_get_device_guid, ibv_get_device_name};
77
88use std:: ffi:: CStr ;
99use std:: io;
10- use std:: mem:: MaybeUninit ;
1110use std:: ops:: Deref ;
1211use std:: os:: raw:: c_int;
1312use std:: ptr:: NonNull ;
@@ -181,35 +180,36 @@ impl fmt::Debug for Guid {
181180}
182181
183182/// Encodes a guid to a hex string and process it
184- fn guid_to_hex < R > ( guid : Guid , case : hex_simd :: AsciiCase , f : impl FnOnce ( & str ) -> R ) -> R {
183+ fn guid_to_hex < R > ( guid : Guid , uppercase : bool , f : impl FnOnce ( & str ) -> R ) -> R {
185184 let src: & [ u8 ; 8 ] = guid. as_bytes ( ) ;
186- let mut buf: MaybeUninit < [ u8 ; 16 ] > = MaybeUninit :: uninit ( ) ;
187- let ans = {
188- // SAFETY: uninit project
189- let bytes = unsafe { slice:: from_raw_parts_mut ( buf. as_mut_ptr ( ) . cast ( ) , 16 ) } ;
190- let dst = hex_simd:: OutBuf :: from_uninit_mut ( bytes) ;
191- let result = hex_simd:: encode_as_str ( src, dst, case) ;
192- // SAFETY: the encoding never fails
193- unsafe { result. unwrap_unchecked ( ) }
185+ let mut buf: [ u8 ; 16 ] = [ 0 ; 16 ] ;
186+ // SAFETY: The buf is two times of src, which is required by hex::encode_to_slice.
187+ // Therefore, the unwrap_unchecked on hex::encode_to_slice is safe.
188+ // After the hex encoding, the bytes in buf are valid UTF-8, because hex::encode_to_slice
189+ // only produces bytes in the ASCII range (0x00 - 0x7F), which are valid UTF-8.
190+ // Therefore, the unwrap_unchecked on std::str::from_utf8 is also safe.
191+ let ans = unsafe {
192+ hex:: encode_to_slice ( src, & mut buf) . unwrap_unchecked ( ) ;
193+ if uppercase {
194+ std:: str:: from_utf8 ( & buf) . unwrap_unchecked ( ) . to_uppercase ( )
195+ } else {
196+ std:: str:: from_utf8 ( & buf) . unwrap_unchecked ( ) . to_lowercase ( )
197+ }
194198 } ;
195- f ( ans)
199+ f ( & ans)
196200}
197201
198202impl fmt:: LowerHex for Guid {
199203 #[ inline]
200204 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
201- guid_to_hex ( * self , hex_simd:: AsciiCase :: Lower , |s| {
202- <str as fmt:: Display >:: fmt ( s, f)
203- } )
205+ guid_to_hex ( * self , false , |s| <str as fmt:: Display >:: fmt ( s, f) )
204206 }
205207}
206208
207209impl fmt:: UpperHex for Guid {
208210 #[ inline]
209211 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
210- guid_to_hex ( * self , hex_simd:: AsciiCase :: Upper , |s| {
211- <str as fmt:: Display >:: fmt ( s, f)
212- } )
212+ guid_to_hex ( * self , true , |s| <str as fmt:: Display >:: fmt ( s, f) )
213213 }
214214}
215215
0 commit comments