@@ -163,8 +163,9 @@ pub mod unistd;
163
163
164
164
use libc:: PATH_MAX ;
165
165
166
- use std:: result;
166
+ use std:: { ptr , result, slice } ;
167
167
use std:: ffi:: { CStr , OsStr } ;
168
+ use std:: mem:: MaybeUninit ;
168
169
use std:: os:: unix:: ffi:: OsStrExt ;
169
170
use std:: path:: { Path , PathBuf } ;
170
171
@@ -260,15 +261,22 @@ impl NixPath for [u8] {
260
261
}
261
262
262
263
fn with_nix_path < T , F > ( & self , f : F ) -> Result < T >
263
- where F : FnOnce ( & CStr ) -> T {
264
- let mut buf = [ 0u8 ; PATH_MAX as usize ] ;
265
-
264
+ where
265
+ F : FnOnce ( & CStr ) -> T ,
266
+ {
266
267
if self . len ( ) >= PATH_MAX as usize {
267
- return Err ( Errno :: ENAMETOOLONG )
268
+ return Err ( Errno :: ENAMETOOLONG ) ;
269
+ }
270
+
271
+ let mut buf = MaybeUninit :: < [ u8 ; PATH_MAX as usize ] > :: uninit ( ) ;
272
+ let buf_ptr = buf. as_mut_ptr ( ) as * mut u8 ;
273
+
274
+ unsafe {
275
+ ptr:: copy_nonoverlapping ( self . as_ptr ( ) , buf_ptr, self . len ( ) ) ;
276
+ buf_ptr. add ( self . len ( ) ) . write ( 0 ) ;
268
277
}
269
278
270
- buf[ ..self . len ( ) ] . copy_from_slice ( self ) ;
271
- match CStr :: from_bytes_with_nul ( & buf[ ..=self . len ( ) ] ) {
279
+ match CStr :: from_bytes_with_nul ( unsafe { slice:: from_raw_parts ( buf_ptr, self . len ( ) + 1 ) } ) {
272
280
Ok ( s) => Ok ( f ( s) ) ,
273
281
Err ( _) => Err ( Errno :: EINVAL ) ,
274
282
}
0 commit comments