Debian Codegraph @

.cargo/vendor/home/src/windows.rs

raw
1 use std::env;
2 use std::ffi::OsString;
3 use std::os::windows::ffi::OsStringExt;
4 use std::path::PathBuf;
5 use std::ptr;
6 use std::slice;
7
8 use windows_sys::Win32::Foundation::S_OK;
9 use windows_sys::Win32::System::Com::CoTaskMemFree;
10 use windows_sys::Win32::UI::Shell::{FOLDERID_Profile, SHGetKnownFolderPath, KF_FLAG_DONT_VERIFY};
11
12 pub fn home_dir_inner() -> Option<PathBuf> {
13 env::var_os("USERPROFILE")
14 .filter(|s| !s.is_empty())
15 .map(PathBuf::from)
16 .or_else(home_dir_crt)
17 }
18
19 #[cfg(not(target_vendor = "uwp"))]
20 fn home_dir_crt() -> Option<PathBuf> {
21 unsafe {
22 let mut path = ptr::null_mut();
23 match SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DONT_VERIFY as u32, 0, &mut path) {
24 S_OK => {
25 let path_slice = slice::from_raw_parts(path, wcslen(path));
26 let s = OsString::from_wide(&path_slice);
27 CoTaskMemFree(path.cast());
28 Some(PathBuf::from(s))
29 }
30 _ => {
31 // Free any allocated memory even on failure. A null ptr is a no-op for `CoTaskMemFree`.
32 CoTaskMemFree(path.cast());
33 None
34 }
35 }
36 }
37 }
38
39 #[cfg(target_vendor = "uwp")]
40 fn home_dir_crt() -> Option<PathBuf> {
41 None
42 }
43
44 extern "C" {
45 fn wcslen(buf: *const u16) -> usize;
46 }
47
48 #[cfg(not(target_vendor = "uwp"))]
49 #[cfg(test)]
50 mod tests {
51 use super::home_dir_inner;
52 use std::env;
53 use std::ops::Deref;
54 use std::path::{Path, PathBuf};
55
56 #[test]
57 fn test_with_without() {
58 let olduserprofile = env::var_os("USERPROFILE").unwrap();
59
60 env::remove_var("HOME");
61 env::remove_var("USERPROFILE");
62
63 assert_eq!(home_dir_inner(), Some(PathBuf::from(olduserprofile)));
64
65 let home = Path::new(r"C:\Users\foo tar baz");
66
67 env::set_var("HOME", home.as_os_str());
68 assert_ne!(home_dir_inner().as_ref().map(Deref::deref), Some(home));
69
70 env::set_var("USERPROFILE", home.as_os_str());
71 assert_eq!(home_dir_inner().as_ref().map(Deref::deref), Some(home));
72 }
73 }