forked from CPsoftBE/BackupOfCromis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cromis.Hashing.pas
1264 lines (1082 loc) · 36.4 KB
/
Cromis.Hashing.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(*
* This software is distributed under BSD license.
*
* Copyright (c) 2010-2014 Iztok Kacin, Cromis ([email protected]).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* - Neither the name of the Iztok Kacin nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* =============================================================================
* Hash related classes (Tables, hashing functions etc...)
* =============================================================================
* 24/08/2010 (1.0.0)
* - Initial implementation
* 19/06/2011 (2.0.0)
* - Complete rewrite that uses TAnyValue and very fast hashing functions
* 06/07/2012 (2.0.1)
* - Fixed hash calculation of actual implememented hash tables
* - Custom hash is abstract and never implemented
* 17/07/2012 (2.1.0)
* - Added EnumerateKeys overload that uses anonymous function as parameter
* - Added EnumerateKeys overload that takes TEnumerateKeyExCallback
* - Use Hash_SuperFastHash as string hash function
* 28/02/2013 (2.2.0)
* - Added support for node manager where deleted nodes are not disposed
* - Use PAnyValue where appropriate internally to avoid record copies
* 06/10/2013 (2.2.1)
* - Enumeration support for easier enumeration of hash members
* 06/10/2013 (2.2.2)
* - GetRaw added to allow direct access to hash members
* 30/12/2013 (2.3.0)
* - ThreadSafe hash table implementation added
* - MurmurHash2 function added to hash functions
* 03/01/2014 (2.4.0)
* - Open Addressing table implementation added
* - MurmurHash3 function added to hash functions
* - FNV1a function added to hash functions
* 14/01/2014 (2.5.0)
* - User can provide its own key comparer function
* 14/01/2014 (2.6.0)
* - Redesigned threading units by content and added generics support
* ============================================================================
*)
unit Cromis.Hashing;
interface
uses
Windows, SysUtils, IniFiles, Classes, Math,
// Cromis units
Cromis.Hashing.Common, Cromis.AnyValue, Cromis.Threading.Sync, Cromis.Threading.TS;
type
PPHashItem = ^PHashItem;
PHashItem = ^THashItem;
THashItem = record
Value: TAnyValue;
Next: PHashItem;
Key: TAnyValue;
end;
TBuckets = array of PHashItem;
PArrayItem = ^TArrayItem;
TArrayItem = record
Value: TAnyValue;
Key: TAnyValue;
Taken: Boolean;
end;
TOAArray = array of TArrayItem;
// function and procedure definitons
TEnumerateKeyExCallback = procedure(const Key, Value: PAnyValue; const Data: Pointer) of object;
THashFunctionInstance = function(const Key: PAnyValue; const Size: Cardinal): Cardinal;
TEnumerateKeyCallback = procedure(const Key, Value: PAnyValue) of object;
THashFunction = function(Data: Pointer; const Length: Cardinal): Cardinal;
TKeyComparer = function(const Key1, Key2: PAnyValue): Boolean;
{$IF CompilerVersion >= 20}
TEnumerateKeyAnonProc = reference to procedure(const Key: TAnyValue; const Value: TAnyValue);
{$IFEND}
IHashElement = Interface(IInterface)
['{94A8F32F-5972-4A9F-BD88-F8677AF1E18F}']
function GetKey: PAnyValue;
function GetValue: PAnyValue;
property Key: PAnyValue read GetKey;
property Value: PAnyValue read GetValue;
end;
IHashEnumerator = Interface(IInterface)
['{4D7E00D3-BFA9-4E3B-82F9-E590DAE74DE7}']
// getters and setters
function _GetCurrent: IHashElement;
// iterator function and procedures
function MoveNext: Boolean;
property Current: IHashElement read _GetCurrent;
end;
THashTableBase = class
strict protected
FSize: Cardinal;
FCount: Integer;
FOwnsObjects: Boolean;
FMaxCountBeforeResize: Integer;
FKeyComparerInstance: TKeyComparer;
FHashFunctionInstance: THashFunctionInstance;
function GetItem(const Key: TAnyValue): TAnyValue; virtual; abstract;
procedure OnEnumKeys(const Key, Value: PAnyValue; const Data: Pointer);
procedure OnEnumValues(const Key, Value: PAnyValue; const Data: Pointer);
procedure SetItem(const Key: TAnyValue; const Value: TAnyValue); virtual; abstract;
public
constructor Create(const HashFunction: THashFunctionInstance; const KeyComparer: TKeyComparer; const Size: Cardinal = cDefaultHashSize); virtual;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer); overload; virtual; abstract;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyCallback); overload; virtual; abstract;
{$IF CompilerVersion >= 20}
procedure EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc); overload; virtual; abstract;
{$IFEND}
function Keys: IAnyArray;
function Values: IAnyArray;
function GetEnumerator: IHashEnumerator; virtual;
function GetRaw(const Key: TAnyValue): PAnyValue; virtual;
function ContainsKey(const Key: TAnyValue): Boolean; virtual; abstract;
procedure Add(const Key: TAnyValue; const Value: TAnyValue); virtual; abstract;
procedure Remove(const Key: TAnyValue); virtual; abstract;
procedure Clear; virtual; abstract;
property Item[const Key: TAnyValue]: TAnyValue read GetItem write SetItem;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
property Count: Integer read FCount;
end;
THashTableBase_Chaining = class(THashTableBase)
strict private
function CheckHashTableSize: Boolean;
procedure Resize(const NewSize: Cardinal);
strict protected
FBuckets: TBuckets;
function AcquireNewBucket: PHashItem; virtual; abstract;
procedure InternalClear(const Buckets: TBuckets); virtual;
procedure ReleaseOldBucket(const Bucket: PHashItem); virtual; abstract;
procedure InternalRemove(const Key: PAnyValue; const KeyHash: Cardinal); virtual;
function Find(const Key: PAnyValue; const KeyHash: Cardinal): PPHashItem; inline;
procedure InternalAdd(const Key: PAnyValue; const Value: PAnyValue; KeyHash: Cardinal); inline;
public
constructor Create(const HashFunction: THashFunctionInstance; const KeyComparer: TKeyComparer; const Size: Cardinal = cDefaultHashSize); override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer); overload; override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyCallback); overload; override;
{$IF CompilerVersion >= 20}
procedure EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc); overload; override;
{$IFEND}
end;
THashTableBase_Open = class(THashTableBase)
strict private
FCollision: Integer;
procedure Resize(const NewSize: Cardinal);
strict protected
FItemArray: TOAArray;
procedure InternalClear(const ItemArray: TOAArray); virtual;
procedure InternalRemove(const Key: PAnyValue; const KeyHash: Cardinal); virtual;
procedure InternalAdd(const Key, Value: PAnyValue; ArrayItem: PArrayItem); virtual;
function Find(const Key: PAnyValue; const KeyHash: Cardinal): PArrayItem; inline;
public
constructor Create(const HashFunction: THashFunctionInstance; const KeyComparer: TKeyComparer; const Size: Cardinal = cDefaultHashSize); override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer); overload; override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyCallback); overload; override;
{$IF CompilerVersion >= 20}
procedure EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc); overload; override;
{$IFEND}
property Collision: Integer read FCollision;
end;
TCustomHashTable_Chaining = class(THashTableBase_Chaining)
private
FDeleted: PHashItem;
procedure ClearDeletedBuckets; inline;
procedure InitializeDeletedItems(const Size: Cardinal);
protected
function AcquireNewBucket: PHashItem; override;
function GetItem(const Key: TAnyValue): TAnyValue; override;
procedure ReleaseOldBucket(const Bucket: PHashItem); override;
procedure SetItem(const Key: TAnyValue; const Value: TAnyValue); override;
public
constructor Create(const HashFunction: THashFunctionInstance; const KeyComparer: TKeyComparer; const Size: Cardinal = cDefaultHashSize); override;
destructor Destroy; override;
function ContainsKey(const Key: TAnyValue): Boolean; override;
procedure Add(const Key: TAnyValue; const Value: TAnyValue); override;
function GetRaw(const Key: TAnyValue): PAnyValue; override;
procedure Remove(const Key: TAnyValue); override;
procedure Clear; override;
end;
TCustomThreadSafeHashTable_Chaining = class(THashTableBase_Chaining)
private
FSRWLock: TSRWLock;
{$IFDEF Threading_NoLockFreeStack}
FDeleted: TThreadSafeQueue;
{$ELSE}
FDeleted: TLockFreeStack;
{$ENDIF}
procedure ClearDeletedBuckets;
protected
function AcquireNewBucket: PHashItem; override;
function GetItem(const Key: TAnyValue): TAnyValue; override;
procedure ReleaseOldBucket(const Bucket: PHashItem); override;
procedure SetItem(const Key: TAnyValue; const Value: TAnyValue); override;
public
constructor Create(const HashFunction: THashFunctionInstance; const KeyComparer: TKeyComparer; const Size: Cardinal = cDefaultHashSize); override;
destructor Destroy; override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer); override;
procedure EnumerateKeys(const EnumProc: TEnumerateKeyCallback); override;
{$IF CompilerVersion >= 20}
procedure EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc); override;
{$IFEND}
function ContainsKey(const Key: TAnyValue): Boolean; override;
procedure Add(const Key: TAnyValue; const Value: TAnyValue); override;
procedure Remove(const Key: TAnyValue); override;
procedure Clear; override;
end;
TCustomHashTable_Open = class(THashTableBase_Open)
protected
function GetItem(const Key: TAnyValue): TAnyValue; override;
procedure SetItem(const Key: TAnyValue; const Value: TAnyValue); override;
public
function ContainsKey(const Key: TAnyValue): Boolean; override;
procedure Add(const Key: TAnyValue; const Value: TAnyValue); override;
function GetRaw(const Key: TAnyValue): PAnyValue; override;
procedure Remove(const Key: TAnyValue); override;
procedure Clear; override;
end;
// hash table that uses integers as keys
TCardinalHashTable = class(TCustomHashTable_Chaining)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
// hash table that uses strings as keys
TStringHashTable = class(TCustomHashTable_Chaining)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
// thread safe hash table that uses integers as keys
TCardinalThreadSafeHashTable = class(TCustomThreadSafeHashTable_Chaining)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
// thread safe hash table that uses strings as keys
TStringThreadSafeHashTable = class(TCustomThreadSafeHashTable_Chaining)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
// thread safe hash table that uses integers as keys
TCardinalHashTableOpen = class(TCustomHashTable_Open)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
// hash table that uses strings as keys
TStringHashTableOpen = class(TCustomHashTable_Open)
public
constructor Create(const Size: Cardinal = cDefaultHashSize); reintroduce;
end;
implementation
type
TCardinalArray = array[0..(MaxInt div SizeOf(Cardinal)) - 1] of Cardinal;
PCardinalArray = ^TCardinalArray;
(* =============================================================================*)
(* Enumeration support. It enumarates as Interface elements. *)
(* This allows for sipmle element auto-memory release after usage *)
(* =============================================================================*)
type
THashElement = class(TInterfacedObject, IHashElement)
private
FKey: PAnyValue;
FValue: PAnyValue;
function GetKey: PAnyValue;
function GetValue: PAnyValue;
public
constructor Create(const Key, Value: PAnyValue);
property Key: PAnyValue read GetKey;
property Value: PAnyValue read GetValue;
end;
THashEnumerator = class(TInterfacedObject, IHashEnumerator)
private
FIndex: Integer;
FActualCount: Integer;
FElementList: array of IHashElement;
FCurrentElement: IHashElement;
function _GetCurrent: IHashElement;
procedure InitializeEnum(const Key, Value: PAnyValue);
public
constructor Create(const HashTable: THashTableBase);
property Current: IHashElement read _GetCurrent;
function MoveNext: Boolean;
end;
(* =============================================================================*)
(* Hashing implementation function stub *)
(* Implement this to pass to constructor and thus have your own hash function *)
(* =============================================================================*)
function CalculateHash_String_SuperFastHash(const Key: PAnyValue; const Size: Cardinal): Cardinal;
begin
Result := Hash_SuperFastHash(PChar(Key.AsPointer), Key.ValueSize) mod Size;
end;
function CalculateHash_Cardinal_SuperFastHash(const Key: PAnyValue; const Size: Cardinal): Cardinal;
var
KeyData: Cardinal;
begin
KeyData := Key.AsCardinal;
Result := Hash_SuperFastHash(@KeyData, SizeOf(Cardinal)) mod Size;
end;
(* =============================================================================*)
(* Key comparer functions *)
(* =============================================================================*)
function KeyComparer_String_Relaxed(const Key1, Key2: PAnyValue): Boolean; inline;
begin
Result := Key1.AsString = Key2.AsString;
end;
function KeyComparer_Cardinal_Relaxed(const Key1, Key2: PAnyValue): Boolean; inline;
begin
Result := Key1.AsCardinal = Key2.AsCardinal;
end;
function KeyComparer_General_Strict(const Key1, Key2: PAnyValue): Boolean; inline;
begin
Result := Key1.Equal(Key2);
end;
{ TCustomHashTable_Chaining }
constructor TCustomHashTable_Chaining.Create(const HashFunction: THashFunctionInstance;
const KeyComparer: TKeyComparer;
const Size: Cardinal);
begin
inherited;
InitializeDeletedItems(FSize div 10);
end;
destructor TCustomHashTable_Chaining.Destroy;
begin
InternalClear(FBuckets);
ClearDeletedBuckets;
inherited;
end;
procedure TCustomHashTable_Chaining.SetItem(const Key: TAnyValue; const Value: TAnyValue);
var
KeyHash: Cardinal;
HashItem: PHashItem;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
HashItem := Find(@Key, KeyHash)^;
if HashItem <> nil then
CopyAnyValue(@HashItem.Value, @Value)
else
InternalAdd(@Key, @Value, KeyHash);
end;
function TCustomHashTable_Chaining.GetItem(const Key: TAnyValue): TAnyValue;
var
HashItem: PHashItem;
begin
HashItem := Find(@Key, FHashFunctionInstance(@Key, FSize))^;
if HashItem <> nil then
CopyAnyValue(@Result, @HashItem.Value)
else
Result.Clear;
end;
function TCustomHashTable_Chaining.GetRaw(const Key: TAnyValue): PAnyValue;
var
HashItem: PHashItem;
begin
HashItem := Find(@Key, FHashFunctionInstance(@Key, FSize))^;
if HashItem <> nil then
Result := @HashItem.Value
else
Result := nil;
end;
function TCustomHashTable_Chaining.ContainsKey(const Key: TAnyValue): Boolean;
begin
Result := Find(@Key, FHashFunctionInstance(@Key, FSize))^ <> nil;
end;
procedure TCustomHashTable_Chaining.InitializeDeletedItems(const Size: Cardinal);
var
I: Integer;
Bucket: PHashItem;
begin
for I := 1 to Size do
begin
New(Bucket);
Bucket.Next := FDeleted;
FDeleted := Bucket;
end;
end;
procedure TCustomHashTable_Chaining.Clear;
begin
InternalClear(FBuckets);
FCount := 0;
end;
procedure TCustomHashTable_Chaining.ClearDeletedBuckets;
var
P, N: PHashItem;
begin
P := FDeleted;
while P <> nil do
begin
N := P^.Next;
Dispose(P);
P := N;
end;
end;
function TCustomHashTable_Chaining.AcquireNewBucket: PHashItem;
begin
if FDeleted <> nil then
begin
Result := FDeleted;
FDeleted := FDeleted.Next;
Result.Next := nil;
end
else
begin
New(Result);
Result^.Next := nil;
end;
end;
procedure TCustomHashTable_Chaining.Add(const Key: TAnyValue; const Value: TAnyValue);
var
KeyHash: Cardinal;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
if Find(@Key, KeyHash)^ <> nil then
raise Exception.CreateFmt('Key "%s" already exists in hash table.', [Key.AsString]);
InternalAdd(@Key, @Value, KeyHash);
end;
procedure TCustomHashTable_Chaining.ReleaseOldBucket(const Bucket: PHashItem);
begin
Bucket.Next := FDeleted;
FDeleted := Bucket;
if FOwnsObjects then
begin
if Bucket.Key.GetValueType = avtObject then
Bucket.Key.AsObject.Free;
if Bucket.Value.GetValueType = avtObject then
Bucket.Value.AsObject.Free;
end;
// clear value and key
Bucket.Value.Clear;
Bucket.Key.Clear;
end;
procedure TCustomHashTable_Chaining.Remove(const Key: TAnyValue);
begin
InternalRemove(@Key, FHashFunctionInstance(@Key, FSize));
end;
{ TCardinalHashTable }
constructor TCardinalHashTable.Create(const Size: Cardinal);
begin
inherited Create(CalculateHash_Cardinal_SuperFastHash, KeyComparer_Cardinal_Relaxed, Size);
end;
{ TStringHashTable }
constructor TStringHashTable.Create(const Size: Cardinal);
begin
inherited Create(CalculateHash_String_SuperFastHash, KeyComparer_String_Relaxed, Size);
end;
{ THashElement }
constructor THashElement.Create(const Key, Value: PAnyValue);
begin
FKey := Key;
FValue := Value;
end;
function THashElement.GetKey: PAnyValue;
begin
Result := FKey;
end;
function THashElement.GetValue: PAnyValue;
begin
Result := FValue;
end;
{ THashEnumerator }
constructor THashEnumerator.Create(const HashTable: THashTableBase);
begin
FIndex := 0;
try
FActualCount := 0;
SetLength(FElementList, HashTable.Count);
HashTable.EnumerateKeys(InitializeEnum);
finally
FCurrentElement := nil;
FIndex := 0;
end;
end;
procedure THashEnumerator.InitializeEnum(const Key, Value: PAnyValue);
var
NewLength: Integer;
begin
if FActualCount >= Length(FElementList) then
begin
NewLength := Max(Round(Length(FElementList) * 1.2), 100);
SetLength(FElementList, NewLength);
end;
FElementList[FIndex] := IHashElement(THashElement.Create(Key, Value));
Inc(FActualCount);
Inc(FIndex);
end;
function THashEnumerator.MoveNext: Boolean;
begin
Result := False;
if FIndex < FActualCount then
begin
FCurrentElement := IHashElement(FElementList[FIndex]);
Result := True;
Inc(FIndex);
end;
end;
function THashEnumerator._GetCurrent: IHashElement;
begin
Result := FCurrentElement;
end;
{ TCustomThreadSafeHashTable_Chaining }
function TCustomThreadSafeHashTable_Chaining.AcquireNewBucket: PHashItem;
var
Item: TAnyValue;
begin
{$IFDEF Threading_NoLockFreeStack}
FDeleted.Dequeue(Item);
{$ELSE}
FDeleted.Pop(Item);
{$ENDIF}
if Item.IsEmpty then
begin
New(Result);
Result^.Next := nil;
end
else
begin
Result := PHashItem(Item.AsPointer);
Result^.Next := nil;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.Add(const Key, Value: TAnyValue);
var
KeyHash: Cardinal;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
FSRWLock.AcquireExclusive;
try
if Find(@Key, KeyHash)^ <> nil then
raise Exception.CreateFmt('Key "%s" already exists in hash table.', [Key.AsString]);
InternalAdd(@Key, @Value, KeyHash);
finally
FSRWLock.ReleaseExclusive;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.Clear;
begin
FSRWLock.AcquireExclusive;
try
InternalClear(FBuckets);
finally
FSRWLock.ReleaseExclusive;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.ClearDeletedBuckets;
var
P: TAnyValue;
Empty: Boolean;
begin
repeat
Empty := True;
{$IFDEF Threading_NoLockFreeStack}
FDeleted.Dequeue(P);
{$ELSE}
FDeleted.Pop(P);
{$ENDIF}
if not P.IsEmpty then
begin
Empty := False;
Dispose(PHashItem(P.AsPointer));
end;
until Empty = True;
end;
function TCustomThreadSafeHashTable_Chaining.ContainsKey(const Key: TAnyValue): Boolean;
var
KeyHash: Cardinal;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
FSRWLock.AcquireShared;
try
Result := Find(@Key, KeyHash)^ <> nil;
finally
FSRWLock.ReleaseShared;
end;
end;
constructor TCustomThreadSafeHashTable_Chaining.Create(const HashFunction: THashFunctionInstance;
const KeyComparer: TKeyComparer;
const Size: Cardinal);
begin
inherited;
FSRWLock.Initialize;
{$IFDEF Threading_NoLockFreeStack}
FDeleted := TThreadSafeQueue.Create(0, False);
{$ELSE}
FDeleted := TLockFreeStack.Create(0, False);
{$ENDIF}
end;
destructor TCustomThreadSafeHashTable_Chaining.Destroy;
begin
InternalClear(FBuckets);
ClearDeletedBuckets;
FreeAndNil(FDeleted);
inherited;
end;
procedure TCustomThreadSafeHashTable_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyCallback);
begin
FSRWLock.AcquireShared;
try
inherited EnumerateKeys(EnumProc);
finally
FSRWLock.ReleaseShared;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer);
begin
FSRWLock.AcquireShared;
try
inherited EnumerateKeys(EnumProc, Data);
finally
FSRWLock.ReleaseShared;
end;
end;
{$IF CompilerVersion >= 20}
procedure TCustomThreadSafeHashTable_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc);
begin
FSRWLock.AcquireShared;
try
inherited EnumerateKeys(EnumProc);
finally
FSRWLock.ReleaseShared;
end;
end;
{$IFEND}
function TCustomThreadSafeHashTable_Chaining.GetItem(const Key: TAnyValue): TAnyValue;
var
KeyHash: Cardinal;
HashItem: PHashItem;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
FSRWLock.AcquireShared;
try
HashItem := Find(@Key, KeyHash)^;
if HashItem <> nil then
CopyAnyValue(@Result, @HashItem^.Value)
else
Result.Clear;
finally
FSRWLock.ReleaseShared;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.ReleaseOldBucket(const Bucket: PHashItem);
begin
{$IFDEF Threading_NoLockFreeStack}
FDeleted.Enqueue(Bucket);
{$ELSE}
FDeleted.Push(Bucket);
{$ENDIF}
if FOwnsObjects then
begin
if Bucket^.Key.GetValueType = avtObject then
Bucket^.Key.AsObject.Free;
if Bucket^.Value.GetValueType = avtObject then
Bucket^.Value.AsObject.Free;
end;
// clear value and key
Bucket^.Value.Clear;
Bucket^.Key.Clear;
end;
procedure TCustomThreadSafeHashTable_Chaining.Remove(const Key: TAnyValue);
var
KeyHash: Cardinal;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
FSRWLock.AcquireExclusive;
try
InternalRemove(@Key, KeyHash);
finally
FSRWLock.ReleaseExclusive;
end;
end;
procedure TCustomThreadSafeHashTable_Chaining.SetItem(const Key, Value: TAnyValue);
var
KeyHash: Cardinal;
HashItem: PHashItem;
begin
KeyHash := FHashFunctionInstance(@Key, FSize);
FSRWLock.AcquireExclusive;
try
HashItem := Find(@Key, KeyHash)^;
if HashItem <> nil then
CopyAnyValue(@HashItem^.Value, @Value)
else
InternalAdd(@Key, @Value, KeyHash);
finally
FSRWLock.ReleaseExclusive;
end;
end;
{ THashTableBase_Chaining }
function THashTableBase_Chaining.CheckHashTableSize: Boolean;
begin
Result := False;
if FCount = FMaxCountBeforeResize then
begin
Resize(2 * FSize);
Result := True;
end;
end;
constructor THashTableBase_Chaining.Create(const HashFunction: THashFunctionInstance;
const KeyComparer: TKeyComparer;
const Size: Cardinal);
begin
inherited;
SetLength(FBuckets, FSize);
// calculate max items before resize
FMaxCountBeforeResize := CalculateMaxItemsBeforeResize(FSize);
end;
procedure THashTableBase_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyExCallback; const Data: Pointer);
var
I: Integer;
Item: PHashItem;
begin
for I := Low(FBuckets) to High(FBuckets) do
begin
Item := FBuckets[I];
while Item <> nil do
begin
EnumProc(@Item.Key, @Item.Value, Data);
Item := Item.Next;
end;
end;
end;
procedure THashTableBase_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyCallback);
var
I: Integer;
Item: PHashItem;
begin
for I := Low(FBuckets) to High(FBuckets) do
begin
Item := FBuckets[I];
while Item <> nil do
begin
EnumProc(@Item.Key, @Item.Value);
Item := Item.Next;
end;
end;
end;
{$IF CompilerVersion >= 20}
procedure THashTableBase_Chaining.EnumerateKeys(const EnumProc: TEnumerateKeyAnonProc);
var
I: Integer;
Item: PHashItem;
begin
for I := Low(FBuckets) to High(FBuckets) do
begin
Item := FBuckets[I];
while Item <> nil do
begin
EnumProc(@Item.Key, @Item.Value);
Item := Item.Next;
end;
end;
end;
{$IFEND}
function THashTableBase_Chaining.Find(const Key: PAnyValue; const KeyHash: Cardinal): PPHashItem;
begin
Result := @FBuckets[KeyHash];
while Result^ <> nil do
begin
if FKeyComparerInstance(@Result^.Key, Key) then
Exit
else
Result := @Result^.Next;
end;
end;
procedure THashTableBase_Chaining.InternalAdd(const Key, Value: PAnyValue; KeyHash: Cardinal);
var
Bucket: PHashItem;
begin
if CheckHashTableSize then
KeyHash := FHashFunctionInstance(Key, FSize);
Bucket := AcquireNewBucket;
CopyAnyValue(@Bucket.Key, Key);
CopyAnyValue(@Bucket.Value, Value);
Bucket.Next := FBuckets[KeyHash];
FBuckets[KeyHash] := Bucket;
Inc(FCount);
end;
procedure THashTableBase_Chaining.InternalClear(const Buckets: TBuckets);
var
I: Integer;
P, N: PHashItem;
begin
for I := Low(Buckets) to High(Buckets) do
begin
P := Buckets[I];
while P <> nil do
begin
N := P^.Next;
ReleaseOldBucket(P);
P := N;
end;
Buckets[I] := nil;
end;
end;
procedure THashTableBase_Chaining.InternalRemove(const Key: PAnyValue; const KeyHash: Cardinal);
var
P: PHashItem;
Prev: PPHashItem;
begin
Prev := Find(Key, KeyHash);
P := Prev^;
if P <> nil then
begin
Prev^ := P.Next;
Dec(FCount);
// return P to deleted
ReleaseOldBucket(P);
end;
end;
procedure THashTableBase_Chaining.Resize(const NewSize: Cardinal);
var
OldBuckets: TBuckets;
BucketIndex: Integer;
HashItem: PHashItem;
begin
FSize := GetGoodHashSize(NewSize);
FMaxCountBeforeResize := CalculateMaxItemsBeforeResize(FSize);
OldBuckets := FBuckets;
FBuckets := nil;
SetLength(FBuckets, FSize);
FCount := 0;
for BucketIndex := Low(OldBuckets) to High(OldBuckets) do
begin
HashItem := OldBuckets[BucketIndex];
while HashItem <> nil do
begin
InternalAdd(@HashItem.Key, @HashItem.Value, FHashFunctionInstance(@HashItem.Key, FSize));
HashItem := HashItem^.Next;
end;
end;
InternalClear(OldBuckets);
end;
{ TCardinalThreadSafeHashTable }
constructor TCardinalThreadSafeHashTable.Create(const Size: Cardinal);
begin
inherited Create(CalculateHash_Cardinal_SuperFastHash, KeyComparer_Cardinal_Relaxed, Size);
end;
{ TStringThreadSafeHashTable }
constructor TStringThreadSafeHashTable.Create(const Size: Cardinal);
begin
inherited Create(CalculateHash_String_SuperFastHash, KeyComparer_String_Relaxed, Size);
end;
{ THashTableBase }
constructor THashTableBase.Create(const HashFunction: THashFunctionInstance;
const KeyComparer: TKeyComparer;
const Size: Cardinal);
begin
FSize := GetGoodHashSize(Size);
FKeyComparerInstance := KeyComparer;
FHashFunctionInstance := HashFunction;
end;