1
1
#![ cfg( unix) ]
2
2
3
3
use std:: env;
4
- use std:: path:: PathBuf ;
5
- use std:: mem;
6
- use std:: ptr;
7
4
use std:: ffi:: CStr ;
8
5
use std:: ffi:: OsString ;
6
+ use std:: mem;
9
7
use std:: os:: unix:: ffi:: OsStringExt ;
8
+ use std:: path:: PathBuf ;
9
+ use std:: ptr;
10
10
11
11
extern crate libc;
12
12
13
13
// https://github.com/rust-lang/rust/blob/master/src/libstd/sys/unix/os.rs#L498
14
14
pub fn home_dir ( ) -> Option < PathBuf > {
15
- return env:: var_os ( "HOME" ) . and_then ( |h| { if h. is_empty ( ) { None } else { Some ( h) } } ) . or_else ( || unsafe {
16
- fallback ( )
17
- } ) . map ( PathBuf :: from) ;
15
+ return env:: var_os ( "HOME" )
16
+ . and_then ( |h| if h. is_empty ( ) { None } else { Some ( h) } )
17
+ . or_else ( || unsafe { fallback ( ) } )
18
+ . map ( PathBuf :: from) ;
18
19
19
- #[ cfg( any( target_os = "android" ,
20
- target_os = "ios" ,
21
- target_os = "emscripten" ) ) ]
22
- unsafe fn fallback ( ) -> Option < OsString > { None }
23
- #[ cfg( not( any( target_os = "android" ,
24
- target_os = "ios" ,
25
- target_os = "emscripten" ) ) ) ]
20
+ #[ cfg( any( target_os = "android" , target_os = "ios" , target_os = "emscripten" ) ) ]
21
+ unsafe fn fallback ( ) -> Option < OsString > {
22
+ None
23
+ }
24
+ #[ cfg( not( any( target_os = "android" , target_os = "ios" , target_os = "emscripten" ) ) ) ]
26
25
unsafe fn fallback ( ) -> Option < OsString > {
27
26
let amt = match libc:: sysconf ( libc:: _SC_GETPW_R_SIZE_MAX) {
28
27
n if n < 0 => 512 as usize ,
@@ -31,8 +30,13 @@ pub fn home_dir() -> Option<PathBuf> {
31
30
let mut buf = Vec :: with_capacity ( amt) ;
32
31
let mut passwd: libc:: passwd = mem:: zeroed ( ) ;
33
32
let mut result = ptr:: null_mut ( ) ;
34
- match libc:: getpwuid_r ( libc:: getuid ( ) , & mut passwd, buf. as_mut_ptr ( ) ,
35
- buf. capacity ( ) , & mut result) {
33
+ match libc:: getpwuid_r (
34
+ libc:: getuid ( ) ,
35
+ & mut passwd,
36
+ buf. as_mut_ptr ( ) ,
37
+ buf. capacity ( ) ,
38
+ & mut result,
39
+ ) {
36
40
0 if !result. is_null ( ) => {
37
41
let ptr = passwd. pw_dir as * const _ ;
38
42
let bytes = CStr :: from_ptr ( ptr) . to_bytes ( ) ;
@@ -41,9 +45,8 @@ pub fn home_dir() -> Option<PathBuf> {
41
45
} else {
42
46
Some ( OsStringExt :: from_vec ( bytes. to_vec ( ) ) )
43
47
}
44
- } ,
48
+ }
45
49
_ => None ,
46
50
}
47
51
}
48
52
}
49
-
0 commit comments