Skip to content

Commit

Permalink
Fix Windows clippy issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Wumpf committed Jan 8, 2025
1 parent f0d7c74 commit ed865f1
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions crates/eframe/src/native/file_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,34 @@ fn roaming_appdata() -> Option<PathBuf> {
extern "C" {
fn wcslen(buf: *const u16) -> usize;
}
unsafe {
let mut path = ptr::null_mut();
match SHGetKnownFolderPath(
let mut path_raw = ptr::null_mut();

// SAFETY: SHGetKnownFolderPath allocates for us, we don't pass any pointers to it.
// See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath
let result = unsafe {
SHGetKnownFolderPath(
&FOLDERID_RoamingAppData,
KF_FLAG_DONT_VERIFY as u32,
std::ptr::null_mut(),
&mut path,
) {
S_OK => {
let path_slice = slice::from_raw_parts(path, wcslen(path));
let s = OsString::from_wide(&path_slice);
CoTaskMemFree(path.cast());
Some(PathBuf::from(s))
}
_ => {
// Free any allocated memory even on failure. A null ptr is a no-op for `CoTaskMemFree`.
CoTaskMemFree(path.cast());
None
}
}
}
&mut path_raw,
)
};

let path = if result == S_OK {
// SAFETY: SHGetKnownFolderPath indicated success and is supposed to allocate a nullterminated string for us.
let path_slice = unsafe { slice::from_raw_parts(path_raw, wcslen(path_raw)) };
Some(PathBuf::from(OsString::from_wide(path_slice)))
} else {
None
};

// SAFETY:
// This memory got allocated by SHGetKnownFolderPath, we didn't touch anything in the process.
// A null ptr is a no-op for `CoTaskMemFree`, so in case this failed we're still good.
// https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cotaskmemfree
unsafe { CoTaskMemFree(path_raw.cast()) };

path
}

#[cfg(any(not(windows), target_vendor = "uwp"))]
Expand Down

0 comments on commit ed865f1

Please sign in to comment.