-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.Types.Optional.pas
More file actions
109 lines (92 loc) · 2.35 KB
/
Copy pathAPI.Types.Optional.pas
File metadata and controls
109 lines (92 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
unit API.Types.Optional;
interface
uses
System.SysUtils,
System.Rtti,
System.Variants,
System.TypInfo;
type
TOptional<T> = record
private
FHasValue: Boolean;
FValue: T;
public
class function Create(const AValue: T): TOptional<T>; static;
class function Empty: TOptional<T>; static;
function HasValue: Boolean;
function GetValue: T;
function ValueOrNull: Variant;
class operator Implicit(const AValue: T): TOptional<T>;
class operator Implicit(const AOptional: TOptional<T>): T;
end;
implementation
{ TOptional<T> }
class function TOptional<T>.Create(const AValue: T): TOptional<T>;
var
ctx: TRttiContext;
rttiType: TRttiType;
begin
Result.FValue := AValue;
Result.FHasValue := True;
ctx := TRttiContext.Create;
try
rttiType := ctx.GetType(TypeInfo(T));
if rttiType.TypeKind = tkInteger then
begin
if TValue.From<T>(AValue).AsInteger = 0 then
Result.FHasValue := False;
end
else if rttiType.TypeKind = tkFloat then
begin
if TValue.From<T>(AValue).AsExtended = 0 then
Result.FHasValue := False;
end
else if rttiType.TypeKind = tkUString then
begin
if TValue.From<T>(AValue).AsString = '' then
Result.FHasValue := False;
end
else if rttiType.TypeKind in [tkChar, tkWChar, tkString] then
begin
if TValue.From<T>(AValue).AsString = '' then
Result.FHasValue := False;
end
else if rttiType.TypeKind = tkEnumeration then
begin
if (rttiType.Handle = TypeInfo(Boolean)) and (TValue.From<T>(AValue).AsBoolean = False) then
Result.FHasValue := False;
end;
finally
ctx.Free;
end;
end;
class function TOptional<T>.Empty: TOptional<T>;
begin
Result.FHasValue := False;
end;
function TOptional<T>.GetValue: T;
begin
if not FHasValue then
raise Exception.Create('TOptional: Valor não definido');
Result := FValue;
end;
function TOptional<T>.HasValue: Boolean;
begin
Result := FHasValue;
end;
class operator TOptional<T>.Implicit(const AValue: T): TOptional<T>;
begin
Result := TOptional<T>.Create(AValue);
end;
class operator TOptional<T>.Implicit(const AOptional: TOptional<T>): T;
begin
Result := AOptional.GetValue;
end;
function TOptional<T>.ValueOrNull: Variant;
begin
if not FHasValue then
Result := Null
else
Result := TValue.From<T>(FValue).AsVariant;
end;
end.