From 1339639706228dfbf8955f9b171b82af699688d1 Mon Sep 17 00:00:00 2001 From: Andreas Reich Date: Sat, 11 Jan 2025 18:05:57 +0100 Subject: [PATCH] Fix Windows clippy issues (#5593) These have been a lil bit annoying when running `cargo clippy --all-features --all-targets` on windows --- crates/eframe/src/native/file_storage.rs | 43 ++++++++++++++---------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/crates/eframe/src/native/file_storage.rs b/crates/eframe/src/native/file_storage.rs index 346c46b4254..3cb338517f4 100644 --- a/crates/eframe/src/native/file_storage.rs +++ b/crates/eframe/src/native/file_storage.rs @@ -58,27 +58,34 @@ fn roaming_appdata() -> Option { 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"))]