forked from VSoftTechnologies/DUnitX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDUnitX.WeakReference.pas
364 lines (323 loc) · 10.2 KB
/
DUnitX.WeakReference.pas
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.WeakReference;
(*
The idea behind this unit is provide a similar lifecycle to reference counted objects
in delphi as WeakReference does in .NET.
Reference counted objects in delphi have some limitations when it comes to circular references,
where for example TParent references it's children (via IChild), and TChild references it's parent
(via IParent). If we remove any external references to our IParent and IChild instances without first
getting the child to remove it's reference to IParent, we would end up with orphaned objects. This
is because our IChild and IParent instances are holding references to each other, and thus they never
get released.
This unit was borrowed from FinalBuilder 7(with permission), it has been extensively used with
Delphi 2010 and has so far proven to be very reliable.
*)
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Generics.Collections;
{$ELSE}
Generics.Collections;
{$ENDIF}
type
/// Implemented by our weak referenced object base class
IWeakReferenceableObject = interface
['{3D7F9CB5-27F2-41BF-8C5F-F6195C578755}']
procedure AddWeakRef(value : Pointer);
procedure RemoveWeakRef(value : Pointer);
function GetRefCount : integer;
end;
/// This is our base class for any object that can have a weak reference to
/// it. It implements IInterface so the object can also be used just like
/// any normal reference counted objects in Delphi.
TWeakReferencedObject = class(TObject, IInterface, IWeakReferenceableObject)
private const
objDestroyingFlag = Integer($80000000);
protected
{$IFNDEF AUTOREFCOUNT}
FRefCount: Integer;
{$ENDIF}
FWeakReferences : TList<Pointer>;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure AddWeakRef(value : Pointer);
procedure RemoveWeakRef(value : Pointer);
function GetRefCount : integer; inline;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
{$IFDEF NEXTGEN}[Result: Unsafe]{$ENDIF} class function NewInstance: TObject; override;
{$IFNDEF AUTOREFCOUNT}
property RefCount: Integer read GetRefCount;
{$ENDIF}
end;
// This is our generic WeakReference interface
IWeakReference<T : IInterface> = interface
function IsAlive : boolean;
function Data : T;
end;
//The actual WeakReference implementation.
TWeakReference<T: IInterface> = class(TInterfacedObject, IWeakReference<T>)
private
FData : Pointer;
protected
function IsAlive : boolean;
function Data : T;
public
constructor Create(const data : T);
destructor Destroy;override;
end;
//only here to work around compiler limitation.
function SafeMonitorTryEnter(const AObject: TObject): Boolean;
implementation
uses
DUnitX.ResStrs,
{$IFDEF USE_NS}
System.TypInfo,
System.Classes,
System.Sysutils,
System.SyncObjs;
{$ELSE}
TypInfo,
classes,
SysUtils,
SyncObjs;
{$ENDIF}
{$IFNDEF DELPHI_XE2_UP}
type
TInterlocked = class
public
class function Increment(var Target: Integer): Integer; static; inline;
class function Decrement(var Target: Integer): Integer; static; inline;
class function Add(var Target: Integer; Increment: Integer): Integer;static;
class function CompareExchange(var Target: Integer; Value, Comparand: Integer): Integer; static;
end;
class function TInterlocked.Decrement(var Target: Integer): Integer;
begin
result := Add(Target,-1);
end;
class function TInterlocked.Increment(var Target: Integer): Integer;
begin
result := Add(Target,1);
end;
class function TInterlocked.Add(var Target: Integer; Increment: Integer): Integer;
{$IFNDEF CPUX86}
asm
.NOFRAME
MOV EAX,EDX
LOCK XADD [RCX].Integer,EAX
ADD EAX,EDX
end;
{$ELSE CPUX86}
asm
MOV ECX,EDX
XCHG EAX,EDX
LOCK XADD [EDX],EAX
ADD EAX,ECX
end;
{$ENDIF}
class function TInterlocked.CompareExchange(var Target: Integer; Value, Comparand: Integer): Integer;
asm
XCHG EAX,EDX
XCHG EAX,ECX
LOCK CMPXCHG [EDX],ECX
end;
{$ENDIF DELPHI_XE2_UPE2}
//MonitorTryEnter doesn't do a nil check!
function SafeMonitorTryEnter(const AObject: TObject): Boolean;
begin
if AObject <> nil then
Result := TMonitor.TryEnter(AObject)
else
result := False;
end;
constructor TWeakReference<T>.Create(const data: T);
var
target : IWeakReferenceableObject;
begin
if data = nil then
raise Exception.Create(format('[%s] passed to TWeakReference was nil', [PTypeInfo(TypeInfo(T)).Name]));
inherited Create;
if Supports(IInterface(data),IWeakReferenceableObject,target) then
begin
FData := IInterface(data) as TObject;
target.AddWeakRef(@FData);
end
else
raise Exception.Create(SWeakReferenceError);
end;
function TWeakReference<T>.Data: T;
begin
result := Default(T); /// can't assign nil to T
if FData <> nil then
begin
//Make sure that the object supports the interface which is our generic type if we
//simply pass in the interface base type, the method table doesn't work correctly
if Supports(FData, GetTypeData(TypeInfo(T))^.Guid, result) then
//if Supports(FData, IInterface, result) then
result := T(result);
end;
end;
destructor TWeakReference<T>.Destroy;
var
target : IWeakReferenceableObject;
begin
if FData <> nil then
begin
if SafeMonitorTryEnter(FData) then //FData could become nil
begin
//get a strong reference to the target
if Supports(FData,IWeakReferenceableObject,target) then
begin
target.RemoveWeakRef(@FData);
target := nil; //release the reference asap.
end;
MonitorExit(FData);
end;
FData := nil;
end;
inherited;
end;
function TWeakReference<T>.IsAlive: boolean;
begin
result := FData <> nil;
end;
{ TWeakReferencedObject }
procedure TWeakReferencedObject.AddWeakRef(value: Pointer);
begin
MonitorEnter(Self);
try
if FWeakReferences = nil then
FWeakReferences := TList<Pointer>.Create;
FWeakReferences.Add(value);
finally
MonitorExit(Self);
end;
end;
procedure TWeakReferencedObject.RemoveWeakRef(value: Pointer);
begin
MonitorEnter(Self);
try
if FWeakReferences = nil then // should never happen
{$IFDEF DEBUG}
raise Exception.Create('FWeakReferences = nil');
{$ELSE}
exit;
{$ENDIF}
FWeakReferences.Remove(value);
if FWeakReferences.Count = 0 then
FreeAndNil(FWeakReferences);
finally
MonitorExit(Self);
end;
end;
procedure TWeakReferencedObject.AfterConstruction;
begin
{$IFNDEF AUTOREFCOUNT}
TInterlocked.Decrement(FRefCount);
{$ENDIF}
end;
procedure TWeakReferencedObject.BeforeDestruction;
var
value : PPointer;
i: Integer;
begin
{$IFNDEF AUTOREFCOUNT}
if RefCount <> 0 then
System.Error(reInvalidPtr);
{$ELSE}
inherited BeforeDestruction;
{$ENDIF}
MonitorEnter(Self);
try
if FWeakReferences <> nil then
begin
for i := 0 to FWeakReferences.Count -1 do
begin
value := FWeakReferences.Items[i];
value^ := nil;
end;
FreeAndNil(FWeakReferences);
end;
finally
MonitorExit(Self);
end;
end;
function TWeakReferencedObject.GetRefCount: integer;
begin
Result := FRefCount and not objDestroyingFlag;
end;
class function TWeakReferencedObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
{$IFNDEF AUTOREFCOUNT}
// Set an implicit refcount so that refcounting
// during construction won't destroy the object.
TWeakReferencedObject(Result).FRefCount := 1;
{$ENDIF}
end;
function TWeakReferencedObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TWeakReferencedObject._AddRef: Integer;
begin
{$IFNDEF AUTOREFCOUNT}
Result := TInterlocked.Increment(FRefCount);
{$ELSE}
Result := __ObjAddRef;
{$ENDIF}
end;
function TWeakReferencedObject._Release: Integer;
{$IFNDEF AUTOREFCOUNT}
procedure __MarkDestroying(const Obj);
var
LRef: Integer;
begin
repeat
LRef := TWeakReferencedObject(Obj).FRefCount;
until TInterlocked.CompareExchange(TWeakReferencedObject(Obj).FRefCount, LRef or objDestroyingFlag, LRef) = LRef;
end;
{$ENDIF}
begin
{$IFNDEF AUTOREFCOUNT}
Result := TInterlocked.Decrement(FRefCount);
if Result = 0 then
begin
__MarkDestroying(Self);
Destroy;
end;
{$ELSE}
Result := __ObjRelease;
{$ENDIF}
end;
end.