Browse Source

Add TRedir<T> which can be used to remove all the duplicate redir code. Once done TPreviousFsRedirectionState, DisableFsRedirectionIf and RestoreFsRedirection should be removed from the interface section which is why I grouped them there now.

Martijn Laan 3 months ago
parent
commit
57f92f0737
1 changed files with 33 additions and 2 deletions
  1. 33 2
      Projects/Src/SetupLdrAndSetup.RedirFunc.pas

+ 33 - 2
Projects/Src/SetupLdrAndSetup.RedirFunc.pas

@@ -18,13 +18,19 @@ interface
 uses
 uses
   Windows, SysUtils, Shared.FileClass, Shared.VerInfoFunc;
   Windows, SysUtils, Shared.FileClass, Shared.VerInfoFunc;
 
 
+type
+  TRedir<T> = class
+    class function RedirIf(const Disable: Boolean; const FailResult: T; const Func: TFunc<T>): T; overload;
+    class function RedirIf(const Disable: Boolean; const Func: TFunc<T>): T; overload;
+  end;
+
+function AreFsRedirectionFunctionsAvailable: Boolean;
+
 type
 type
   TPreviousFsRedirectionState = record
   TPreviousFsRedirectionState = record
     DidDisable: Boolean;
     DidDisable: Boolean;
     OldValue: Pointer;
     OldValue: Pointer;
   end;
   end;
-
-function AreFsRedirectionFunctionsAvailable: Boolean;
 function DisableFsRedirectionIf(const Disable: Boolean;
 function DisableFsRedirectionIf(const Disable: Boolean;
   var PreviousState: TPreviousFsRedirectionState): Boolean;
   var PreviousState: TPreviousFsRedirectionState): Boolean;
 procedure RestoreFsRedirection(const PreviousState: TPreviousFsRedirectionState);
 procedure RestoreFsRedirection(const PreviousState: TPreviousFsRedirectionState);
@@ -159,6 +165,31 @@ begin
     Wow64RevertWow64FsRedirectionFunc(PreviousState.OldValue);
     Wow64RevertWow64FsRedirectionFunc(PreviousState.OldValue);
 end;
 end;
 
 
+{ TRedir<T> }
+
+class function TRedir<T>.RedirIf(const Disable: Boolean; const FailResult: T; const Func: TFunc<T>): T;
+begin
+  var PrevState: TPreviousFsRedirectionState;
+  var ErrorCode: DWORD;
+  if not DisableFsRedirectionIf(Disable, PrevState) then begin
+    Result := FailResult;
+    Exit;
+  end;
+  try
+    Result := Func;
+    ErrorCode := GetLastError;
+  finally
+    RestoreFsRedirection(PrevState);
+  end;
+  SetLastError(ErrorCode)
+end;
+
+class function TRedir<T>.RedirIf(const Disable: Boolean;
+  const Func: TFunc<T>): T;
+begin
+  Result := RedirIf(Disable, Default(T), Func);
+end;
+
 { *Redir functions }
 { *Redir functions }
 
 
 function CreateFileRedir(const DisableFsRedir: Boolean; const FileName: String;
 function CreateFileRedir(const DisableFsRedir: Boolean; const FileName: String;