-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcocinasync.collections.pas
660 lines (581 loc) · 14.7 KB
/
cocinasync.collections.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
unit cocinasync.collections;
interface
uses System.SysUtils, System.Classes, System.SyncObjs, System.Generics.Defaults,
System.TypInfo;
resourcestring
S_ARRAYISFULL = 'The queue is full';
S_ARRAYISEMPTY = 'The queue is empty';
type
TInterlockedHelper = class helper for TInterlocked
public
class function CompareExchange(var Target: Pointer; Value: Pointer; Comparand: Pointer; out Succeeded: Boolean): Pointer; overload;
class function CompareExchange(var Target: UInt64; Value: UInt64; Comparand: UInt64; out Succeeded: Boolean): UInt64; overload;
class function Exchange<T>(var Target: T; Value: T): T; overload;
end;
EQueueSizeException = class(Exception)
end;
EKeyExists<K> = class(Exception)
public
constructor Create(Key : K); reintroduce; virtual;
end;
TQueue<T> = class(TObject)
strict private
FData : System.TArray<T>;
FSize : integer;
FWriteIndex : integer;
FReadIndex : integer;
FReadIndexMax : integer;
function IndexOf(idx : integer) : integer; inline;
function GetItems(idx: integer): T; inline;
function GetCount: integer; inline;
public
constructor Create(Size : Integer); reintroduce; virtual;
destructor Destroy; override;
procedure Enqueue(Value : T); inline;
function Dequeue : T; inline;
procedure Clear; inline;
property Items[idx : integer] : T read GetItems; default;
property Count : integer read GetCount;
end;
TStack<T> = class(TObject)
strict private type
PStackPointer = ^TStackPointer;
TStackPointer = record
FData : T;
FPrior : Pointer;
end;
strict private
FTop : Pointer;
FDisposeQueue : TQueue<PStackPointer>;
public
constructor Create; reintroduce; virtual;
destructor Destroy; override;
procedure Push(const Value: T); inline;
function Pop: T; overload; inline;
procedure Clear; inline;
end;
TVisitorProc<K,V> = reference to procedure(const Key : K; var Value : V; var Delete : Boolean);
THash<K,V> = class(TObject)
strict private
type
PValue = ^V;
PItem = ^TItem;
TItem = record
Key: K;
Value: V;
Next: Pointer;
Visiting : integer;
Removed : integer;
end;
TItemArray = system.TArray<Pointer>;
strict private
FMemSize: Cardinal;
FItems: TItemArray;
FComparer : IEqualityComparer<K>;
FKeyType: PTypeInfo;
procedure GetMapPointer(Key: K; HashIdx : integer; var Prior, Current : PItem; var Depth : Integer); inline;
function GetMap(Key: K): V; inline;
procedure SetMap(Key: K; const Value: V; NewItem : PItem; const wait : TSpinWait; AllowOverwrite : boolean); overload; inline;
procedure SetMap(Key: K; const Value: V; AllowOverwrite : boolean); overload; inline;
procedure SetMap(Key: K; const Value: V); overload; inline;
function GetHas(Key: K): boolean; inline;
function GetHashIndex(Key : K) : Integer; inline;
function CalcDepth(item: PItem): integer; inline;
function Remove(const Key : K; const wait : TSpinWait) : V; overload; inline;
public
type
TDepth = record
EmptyCnt : Cardinal;
MaxDepth : Cardinal;
Average : Cardinal;
AvgFilled : Cardinal;
Size : Cardinal;
end;
public
constructor Create(EstimatedItemCount : Cardinal = 1024); reintroduce; virtual;
destructor Destroy; override;
function DebugDepth : TDepth;
function Remove(const Key : K) : V; overload; inline;
procedure AddOrSetValue(const Key : K; const Value : V); inline;
procedure Add(const Key : K; const Value : V); inline;
property Has[Key : K] : boolean read GetHas;
property Map[Key : K] : V read GetMap write SetMap; default;
procedure Visit(const visitor : TVisitorProc<K,V>);
end;
implementation
uses Math, System.Generics.Collections;
{ TInterlockedHelper }
class function TInterlockedHelper.CompareExchange(var Target: Pointer; Value: Pointer; Comparand: Pointer; out Succeeded: Boolean): Pointer;
begin
Result := AtomicCmpExchange(Target, Value, Comparand, Succeeded);
end;
class function TInterlockedHelper.CompareExchange(var Target: UInt64; Value,
Comparand: UInt64; out Succeeded: Boolean): UInt64;
begin
Result := AtomicCmpExchange(Target, Value, Comparand, Succeeded);
end;
class function TInterlockedHelper.Exchange<T>(var Target: T; Value : T): T;
begin
TObject((@Result)^) := Exchange(TObject((@Target)^), TObject((@Value)^));
end;
{ TQueue<T> }
procedure TQueue<T>.Clear;
begin
repeat
Dequeue;
until IndexOf(FReadIndex) = IndexOf(FReadIndexMax);
end;
constructor TQueue<T>.Create(Size: Integer);
begin
inherited Create;
FSize := Size;
SetLength(FData, Size);
end;
function TQueue<T>.Dequeue: T;
var
iMaxRead, iRead : integer;
bSuccess : boolean;
sw : TSpinWait;
p : pointer;
begin
sw.Reset;
repeat
iRead := FReadIndex;
iMaxRead := FReadIndexMax;
if IndexOf(iRead) = IndexOf(iMaxRead) then
exit(T(nil));
Result := FData[IndexOf(iRead)];
TInterlocked.CompareExchange(FReadIndex, iRead+1, iRead, bSuccess);
if not bSuccess then
sw.SpinCycle;
until bSuccess;
if IsManagedType(T) then
begin
p := @FData[IndexOf(iRead)];
TInterlocked.CompareExchange(p,nil,@Result);
end;
end;
destructor TQueue<T>.Destroy;
begin
Clear;
inherited;
end;
procedure TQueue<T>.Enqueue(Value: T);
var
bSuccess : boolean;
iRead, iWrite : integer;
sw : TSpinWait;
begin
sw.Reset;
repeat
iWrite := FWriteIndex;
iRead := FReadIndex;
if IndexOf(iWrite + 1) = IndexOf(iRead) then
raise EQueueSizeException.Create(S_ARRAYISFULL);
TInterlocked.CompareExchange(FWriteIndex, iWrite+1, iWrite, bSuccess);
if not bSuccess then
sw.SpinCycle;
until bSuccess;
FData[IndexOf(iWrite)] := Value;
sw.Reset;
repeat
TInterlocked.CompareExchange(FReadIndexMax, iWrite+1, iWrite, bSuccess);
if not bSuccess then
sw.SpinCycle;
until (bSuccess);
end;
function TQueue<T>.GetItems(idx: integer): T;
begin
Result := FData[IndexOf(idx)];
end;
function TQueue<T>.GetCount : integer;
begin
Result := FReadIndexMax - FReadIndex;
end;
function TQueue<T>.IndexOf(idx: integer): integer;
begin
result := idx mod FSize;
end;
{ TStack<T> }
procedure TStack<T>.Clear;
begin
while FTop <> nil do
Pop;
end;
constructor TStack<T>.Create;
begin
inherited Create;
FTop := nil;
FDisposeQueue := TQueue<PStackPointer>.Create(256);
end;
destructor TStack<T>.Destroy;
var
p : PStackPointer;
begin
Clear;
repeat
p := FDisposeQueue.Dequeue;
if p <> nil then
Dispose(p);
until p = nil;
FDisposeQueue.Free;
inherited;
end;
function TStack<T>.Pop: T;
var
p : PStackPointer;
bSuccess : boolean;
wait : TSpinWait;
begin
wait.Reset;
if FTop = nil then
exit(T(nil));
repeat
p := FTop;
if p <> nil then
TInterlocked.CompareExchange(FTop,p^.FPrior, p, bSuccess)
else
exit(T(nil));
if not bSuccess then
wait.SpinCycle;
until bSuccess;
Result := p^.FData;
FDisposeQueue.Enqueue(p);
if FDisposeQueue.Count > 192 then
begin
while FDisposeQueue.Count > 128 do
begin
p := FDisposeQueue.Dequeue;
if p <> nil then
Dispose(p);
end;
end;
end;
procedure TStack<T>.Push(const Value: T);
var
pNew : PStackPointer;
wait : TSpinWait;
bSuccess : boolean;
begin
wait.Reset;
if FDisposeQueue.Count > 64 then
pNew := FDisposeQueue.Dequeue
else
New(pNew);
pNew^.FData := Value;
repeat
pNew^.FPrior := FTop;
TInterlocked.CompareExchange(FTop,pNew, pNew^.FPrior,bSuccess);
if not bSuccess then
begin
wait.SpinCycle;
end;
until bSuccess;
end;
{ THash<K, V> }
procedure THash<K, V>.Add(const Key: K; const Value: V);
begin
SetMap(Key, Value, False);
end;
procedure THash<K, V>.AddOrSetValue(const Key: K; const Value: V);
begin
SetMap(Key, Value, True);
end;
constructor THash<K, V>.Create(EstimatedItemCount : Cardinal = 1024);
var
i: Integer;
begin
inherited Create;
FMemSize := $FFFFFF;
while (EstimatedItemCount < FMemSize) and (FMemSize > $F) do
FMemSize := FMemSize shr 4;
SetLength(FItems,FMemSize+1);
FKeyType := TypeInfo(K);
FComparer := TEqualityComparer<K>.Default;
for i := Low(FItems) to High(FItems) do
FItems[i] := nil;
end;
function THash<K, V>.CalcDepth(item : PItem) : integer;
begin
Result := 1;
while (item <> nil) and (item^.Next <> nil) do
begin
inc(Result);
item := item^.Next;
end;
end;
function THash<K, V>.DebugDepth: TDepth;
var
i, iDepth : integer;
begin
Result.EmptyCnt := 0;
Result.MaxDepth := 0;
Result.Average := 0;
Result.AvgFilled := 0;
Result.Size := FMemSize+1;
for i := 0 to FMemSize do
begin
if FItems[i] <> nil then
begin
iDepth := CalcDepth(FItems[I]);
Result.MaxDepth := Max(Result.MaxDepth, iDepth);
inc(Result.Average,iDepth);
inc(Result.AvgFilled, iDepth);
end else
Inc(Result.EmptyCnt);
end;
Result.Average := Result.Average div (FMemSize+1);
if FMemSize >= Result.EmptyCnt then
Result.AvgFilled := Result.AvgFilled div ((FMemSize+1) - Result.EmptyCnt)
else
Result.AvgFilled := Result.Average;
end;
function THash<K, V>.Remove(const Key: K; const wait: TSpinWait) : V;
var
p, pPrior : PItem;
iDepth : integer;
bSuccess : boolean;
begin
GetMapPointer(Key, GetHashIndex(Key), pPrior, p, iDepth);
if p <> nil then
begin
if pPrior = nil then
TInterlocked.CompareExchange(FItems[GetHashIndex(Key)],p^.Next, p, bSuccess)
else
TInterlocked.CompareExchange(pPrior^.Next, p^.Next, p, bSuccess);
if not bSuccess then
begin
wait.SpinCycle;
Result := Remove(Key, wait);
end else
begin
Result := p^.Value;
Dispose(p);
end;
end else
Result := V(nil);
end;
function THash<K, V>.Remove(const Key: K) : V;
var
sw : TSpinWait;
begin
sw.Reset;
Result := Remove(Key, sw);
end;
destructor THash<K, V>.Destroy;
var
p, pNext : PItem;
i: Integer;
begin
for i := Low(FItems) to High(FItems) do
if FItems[i] <> nil then
begin
p := PItem(PItem(FItems[i])^.Next);
while p <> nil do
begin
pNext := p^.Next;
p^.Value := V(nil);
Dispose(PItem(p));
p := pNext;
end;
Dispose(PItem(FItems[i]));
end;
inherited;
end;
function THash<K, V>.GetHas(Key: K): boolean;
var
p, pPrior: PItem;
iDepth: integer;
begin
GetMapPointer(Key, GetHashIndex(Key), pPrior, p, iDepth);
Result := (p <> nil) and (p^.Removed = 0);
end;
function THash<K, V>.GetHashIndex(Key: K): Integer;
const Mask = not Integer($80000000);
begin
result := (Mask and ((Mask and FComparer.GetHashCode(Key)) + 1)) and (FMemSize);
end;
function THash<K, V>.GetMap(Key: K): V;
var
p, pPrior : PItem;
iDepth : integer;
begin
GetMapPointer(Key, GetHashIndex(Key), pPrior, p, iDepth);
if p <> nil then
begin
TInterlocked.Increment(p^.Visiting);
try
if p^.Removed = 0 then
Result := p^.Value
else
Result := V(nil);
finally
TInterlocked.Decrement(p^.Visiting);
end;
end else
Result := V(nil);
end;
procedure THash<K, V>.GetMapPointer(Key: K; HashIdx : integer; var Prior, Current : PItem; var Depth : Integer);
var
p : PItem;
begin
Depth := 0;
Prior := nil;
p := FItems[HashIdx];
if p <> nil then
begin
if not FComparer.Equals(p.Key, Key) then
begin
repeat
Prior := p;
p := p^.Next;
inc(Depth);
until (p = nil) or FComparer.Equals(p.Key, Key);
if p <> nil then
Current := p
else
Current := nil;
end else
Current := p;
end else
Current := nil;
end;
procedure THash<K, V>.SetMap(Key: K; const Value: V; NewItem: PItem; const wait : TSpinWait; AllowOverwrite : boolean);
var
p, pNew, pDisp, pPrior : PItem;
iDepth, idx : Integer;
bSuccess : boolean;
vValue : V;
begin
idx := GetHashIndex(Key);
pPrior := nil;
GetMapPointer(Key, idx, pPrior, p, iDepth);
if p = nil then
begin
if NewItem = nil then
begin
New(pNew);
pNew^.Key := Key;
pNew^.Value := Value;
pNew^.Visiting := 0;
pNew^.Removed := 0;
end else
pNew := NewItem;
pNew^.Next := nil;
if iDepth > 0 then
begin
// Slot occupied but key not found
pNew^.Next := p;
TInterlocked.CompareExchange(pPrior^.Next, pNew, p, bSuccess);
if not bSuccess then
begin
wait.SpinCycle;
SetMap(Key,Value, pNew, wait, AllowOverwrite);
end;
end else
begin
// Slot open, start linked list with key
TInterlocked.CompareExchange(FItems[idx],pNew,p,bSuccess);
if not bSuccess then
begin
wait.SpinCycle;
SetMap(Key,Value, pNew, wait, AllowOverwrite);
end else
if p <> nil then
Dispose(p);
end;
end else
begin
if AllowOverwrite then
TInterlocked.Exchange<V>(p^.Value,Value)
else
raise EKeyExists<K>.Create(Key);
end;
end;
procedure THash<K, V>.SetMap(Key: K; const Value: V; AllowOverwrite: boolean);
var
sw : TSpinWait;
begin
sw.Reset;
SetMap(Key, Value, nil, sw, AllowOverwrite);
end;
procedure THash<K, V>.SetMap(Key: K; const Value: V);
begin
SetMap(Key, Value, True);
end;
procedure THash<K, V>.Visit(const visitor: TVisitorProc<K,V>);
var
p : PItem;
del : boolean;
i : integer;
sw : TSpinWait;
lst : TList<PItem>;
begin
lst := TList<PItem>.Create;
try
for i := low(FItems) to High(FItems) do
begin
p := FItems[i];
if p <> nil then
begin
repeat
del := False;
TInterlocked.Increment(p^.Visiting);
try
visitor(p^.Key, p^.Value, del);
if del then
begin
TInterlocked.Increment(p^.Removed);
lst.Add(p);
sw.Reset;
while p^.Visiting <> 1 do
sw.SpinCycle;
end;
finally
TInterlocked.Decrement(p^.Visiting);
end;
p := p^.Next;
until p = nil
end;
end;
for i := 0 to lst.Count-1 do
begin
Remove(lst[i]^.Key);
end;
finally
lst.Free;
end;
end;
{ EKeyExists<K> }
constructor EKeyExists<K>.Create(Key: K);
type
PObject = ^TObject;
var
sKey : string;
pti : PTypeInfo;
begin
pti := TypeInfo(K);
case pti^.Kind of
tkInteger,
tkEnumeration:
sKey := Integer(PInteger(@Key)^).ToString;
tkInt64 :
sKey := Int64(PInt64(@Key)^).ToString;
tkFloat:
sKey := Double(PDouble(@Key)^).ToString;
tkChar,
tkString,
tkWChar,
tkLString,
tkWString,
tkUString:
sKey := String(PString(@Key)^);
tkClass,
tkClassRef :
sKey := TObject(PObject(@Key)^).ToString;
else
sKey := '';
end;
inherited Create('Value exists for key '+sKey);
end;
end.