@@ -79,12 +79,20 @@ pub fn enable_autostart(app_handle: &AppHandle) -> Result<(), String> {
7979 struct PersistFileGuard ( * mut IPersistFile ) ;
8080
8181 impl PersistFileGuard {
82- unsafe fn as_ref ( & self ) -> Option < & IPersistFile > {
82+ /// Execute a closure with the raw IPersistFile pointer if it is non-null.
83+ ///
84+ /// Returns an error if the pointer is null.
85+ unsafe fn with < F , R > ( & self , f : F ) -> Result < R , String >
86+ where
87+ F : FnOnce ( * mut IPersistFile ) -> R ,
88+ {
8389 if self . 0 . is_null ( ) {
84- None
90+ Err ( "Persist file pointer is null" . to_string ( ) )
8591 } else {
86- // SAFETY: We've checked that the pointer is not null
87- unsafe { Some ( & * self . 0 ) }
92+ // SAFETY: We've checked that the pointer is not null, and we
93+ // only pass the pointer into the provided closure without
94+ // extending its lifetime beyond this call.
95+ Ok ( f ( self . 0 ) )
8896 }
8997 }
9098 }
@@ -165,12 +173,12 @@ pub fn enable_autostart(app_handle: &AppHandle) -> Result<(), String> {
165173
166174 if !persist_file. is_null ( ) {
167175 let persist_file_guard = PersistFileGuard ( persist_file) ;
168- let persist_file_ref = persist_file_guard
169- . as_ref ( )
170- . ok_or ( "Persist file pointer is null" . to_string ( ) ) ?;
171176
172177 // Save the shortcut
173- let hr_save = persist_file_ref. Save ( wide_shortcut_path. as_ptr ( ) , 1 ) ;
178+ let hr_save = unsafe {
179+ persist_file_guard. with ( |pf| ( * pf) . Save ( wide_shortcut_path. as_ptr ( ) , 1 ) ) ?
180+ } ;
181+
174182 if !SUCCEEDED ( hr_save) {
175183 CoUninitialize ( ) ;
176184 return Err ( format ! ( "Failed to save shortcut: {hr_save:#x}" ) ) ;
0 commit comments