Browse Source

Adding pointer access to nullable

Frederic Kehrein 10 months ago
parent
commit
6ff63107a6
2 changed files with 31 additions and 0 deletions
  1. 12 0
      packages/rtl-objpas/src/inc/nullable.pp
  2. 19 0
      tests/test/units/nullable/tnull.pp

+ 12 - 0
packages/rtl-objpas/src/inc/nullable.pp

@@ -34,9 +34,12 @@ Type
   { TNullable }
   { TNullable }
 
 
   generic TNullable<T> = record
   generic TNullable<T> = record
+  public type
+    PT = ^T;
   private
   private
     FValue: T;
     FValue: T;
     FHasValue: Boolean; // Default False
     FHasValue: Boolean; // Default False
+    function InitAndGetPtr: PT;
     function GetIsNull: Boolean;
     function GetIsNull: Boolean;
     function GetValue: T;
     function GetValue: T;
     function GetValueOrDefault: T;
     function GetValueOrDefault: T;
@@ -58,6 +61,8 @@ Type
     property IsNull: Boolean read GetIsNull;
     property IsNull: Boolean read GetIsNull;
     // return the value.
     // return the value.
     property Value: T read GetValue write SetValue;
     property Value: T read GetValue write SetValue;
+    // Initializes the value if not exists and gets the pointer
+    property Ptr: PT read InitAndGetPtr;
     // If a value is present, return it, otherwise return the default.
     // If a value is present, return it, otherwise return the default.
     property ValueOrDefault: T read GetValueOrDefault;
     property ValueOrDefault: T read GetValueOrDefault;
     // Return an empty value
     // Return an empty value
@@ -88,6 +93,13 @@ uses rtlconsts,typinfo;
 
 
 { TNullable }
 { TNullable }
 
 
+function TNullable.InitAndGetPtr:PT;
+begin
+  if not HasValue then
+    SetValue(Default(T));
+  Result := @FValue;
+end;
+
 function TNullable.GetIsNull: Boolean;
 function TNullable.GetIsNull: Boolean;
 begin
 begin
   Result:=Not HasValue;
   Result:=Not HasValue;

+ 19 - 0
tests/test/units/nullable/tnull.pp

@@ -253,6 +253,24 @@ begin
     Exit('ValueOr not correct');
     Exit('ValueOr not correct');
 end;
 end;
 
 
+Function TestPtrAccess : string;
+
+Var
+  A : specialize TNullable<String>;
+begin
+  Result:='';
+  A.Value:=Val1;
+  If Not (A.Ptr^=Val1) then
+    Exit('Pointer to initialized not correct');
+  A.Clear;
+  If Not (A.Ptr^='') then
+    Exit('Pointer to uninitialized not correct');
+  A.Clear;
+  A.Ptr^:=Val1;
+  If Not (A.HasValue And (A.Value=Val1)) then
+    Exit('Setting value through PTR access not correct');
+end;
+
 Procedure DoTest(aTest,aResult : String);
 Procedure DoTest(aTest,aResult : String);
 
 
 begin
 begin
@@ -282,5 +300,6 @@ begin
   DoTest('TestBoolCheck',TestBoolCheck);
   DoTest('TestBoolCheck',TestBoolCheck);
   DoTest('TestUnpack',TestUnpack);
   DoTest('TestUnpack',TestUnpack);
   DoTest('TestValueOr',TestValueOr);
   DoTest('TestValueOr',TestValueOr);
+  DoTest('TestPtrAccess',TestPtrAccess);
 end.
 end.