-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAssocArrays.pas
More file actions
2804 lines (2339 loc) · 85.2 KB
/
AssocArrays.pas
File metadata and controls
2804 lines (2339 loc) · 85.2 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
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
unit AssocArrays;
(*
DESCRIPTION: Associative array implementation
AUTHOR: Alexander Shostak (aka Berserker aka EtherniDee aka BerSoft)
*)
(*
The implementation uses binary tree and (in case of array with string keys) user provided hash function to store and retrieve data.
Tree is automatically rebalanced when critical search depth is met which is equal to 2X of balanced tree height.
Rebalancing is done by converting tree to linear node array and inserting nodes in empty tree.
Possible improvement: compare hash first and preprocessed key then, thus getting rid of item chains and leaving nodes only.
In this case no O(n^2) performance is possible.
*)
(***) interface (***)
uses
Math,
SysUtils,
Alg,
Crypto,
Utils;
const
LEFT_CHILD = false;
RIGHT_CHILD = true;
NO_KEY_PREPROCESS_FUNC = nil;
type
THashFunc = function (const Str: string): integer;
TKeyPreprocessFunc = function (const OrigKey: string): string;
TChildNodeSide = boolean;
PStrBinTreeItem = ^TStrBinTreeItem;
TStrBinTreeItem = record
Key: string;
{OUn}Value: pointer;
{On} NextItem: PStrBinTreeItem;
end;
PStrBinTreeNode = ^TStrBinTreeNode;
TStrBinTreeNode = record
Hash: integer;
{O} Item: PStrBinTreeItem;
ChildNodes: array [LEFT_CHILD..RIGHT_CHILD] of {On} PStrBinTreeNode;
end;
TStrBinTreeNodeArray = array of {O} PStrBinTreeNode;
TStrBinTreeLinearNodeArray = record
NodeArray: TStrBinTreeNodeArray; // Nodes are sorted by hash
NodeCount: integer;
ItemCount: integer;
end;
TStrBinTree = class (Utils.TCloneable)
(***) protected (***)
{On} fRoot: PStrBinTreeNode;
fHashFunc: THashFunc;
{n} fKeyPreprocessFunc: TKeyPreprocessFunc;
fOwnsItems: boolean;
fItemsAreObjects: boolean;
fItemGuardProc: Utils.TItemGuardProc;
{On} fItemGuard: Utils.TItemGuard;
fItemCount: integer;
fNodeCount: integer;
fIterNodes: array of {U} PStrBinTreeNode;
{U} fIterCurrItem: PStrBinTreeItem;
fIterNodeInd: integer;
fLocked: boolean;
function CloneItem (Item: PStrBinTreeItem): {O} PStrBinTreeItem;
function CloneNode ({n} Node: PStrBinTreeNode): {On} PStrBinTreeNode;
procedure FreeItemValue (Item: PStrBinTreeItem);
procedure FreeNode ({IN} var {n} Node: PStrBinTreeNode);
procedure RemoveNode ({n} ParentNode: PStrBinTreeNode; ItemNode: PStrBinTreeNode);
procedure RemoveItem
(
{n} ParentNode: PStrBinTreeNode;
ItemNode: PStrBinTreeNode;
{n} ParentItem: PStrBinTreeItem;
Item: PStrBinTreeItem
);
(*
All nodes are placed in NodeArray and disconnected from each other.
Original binary tree is emptied. Nodes are sorted by hash.
*)
procedure ConvertToLinearNodeArray (out Res: TStrBinTreeLinearNodeArray);
function FindItem
(
Hash: integer;
const Key: string;
out {ni} ParentNode: PStrBinTreeNode;
out {ni} ItemNode: PStrBinTreeNode;
out {ni} ParentItem: PStrBinTreeItem;
out {ni} Item: PStrBinTreeItem
): boolean;
(***) public (***)
constructor Create
(
HashFunc: THashFunc;
{n} KeyPreprocessFunc: TKeyPreprocessFunc;
OwnsItems: boolean;
ItemsAreObjects: boolean;
ItemGuardProc: Utils.TItemGuardProc;
{IN} var {n} ItemGuard: Utils.TItemGuard
);
destructor Destroy; override;
procedure Assign (Source: Utils.TCloneable); override;
procedure Clear;
function GetPreprocessedKey (const Key: string): string;
function IsValidValue ({n} Value: pointer): boolean;
function CalcCritDepth: integer; inline;
procedure Rebuild;
function GetValue (const Key: string): {n} pointer;
function HasKey (const Key: string): boolean;
function GetExistingValue (const Key: string; out {Un} Res: pointer): boolean;
procedure SetValue (const Key: string; {OUn} NewValue: pointer);
function DeleteItem (const Key: string): boolean;
(* Returns value with specified key and NILify it in the array *)
function TakeValue (Key: string; out {OUn} Value: pointer): boolean;
(* Returns old value *)
function ReplaceValue
(
Key: string;
{OUn} NewValue: pointer;
out {OUn} OldValue: pointer
): boolean;
procedure Merge (Source: TStrBinTree);
procedure BeginIterate;
function IterateNext (out Key: string; out {Un} Value: pointer): boolean;
procedure EndIterate;
property HashFunc: THashFunc read fHashFunc;
property KeyPreprocessFunc: TKeyPreprocessFunc read fKeyPreprocessFunc;
property OwnsItems: boolean read fOwnsItems;
property ItemsAreObjects: boolean read fItemsAreObjects;
property ItemCount: integer read fItemCount;
property ItemGuardProc: Utils.TItemGuardProc read fItemGuardProc;
property NodeCount: integer read fNodeCount;
property Locked: boolean read fLocked;
property Items[const Key: string]: pointer read {n} GetValue write {OUn} SetValue; default;
end; // .class TStrBinTree
PObjBinTreeNode = ^TObjBinTreeNode;
TObjBinTreeNode = record
Hash: integer; // Hash is encoded {U} Key: pointer
{OUn} Value: pointer;
ChildNodes: array [LEFT_CHILD..RIGHT_CHILD] of {On} PObjBinTreeNode;
end;
TObjBinTreeNodeArray = array of {O} PObjBinTreeNode;
TObjBinTreeLinearNodeArray = record
NodeArray: TObjBinTreeNodeArray; // Nodes are sorted by hash
NodeCount: integer;
end;
TObjBinTree = class (Utils.TCloneable)
(***) protected (***)
{On} fRoot: PObjBinTreeNode;
fOwnsItems: boolean;
fItemsAreObjects: boolean;
fItemGuardProc: Utils.TItemGuardProc;
{On} fItemGuard: Utils.TItemGuard;
fNodeCount: integer;
fIterNodes: array of {U} PObjBinTreeNode;
fIterNodeInd: integer;
fLocked: boolean;
function HashToKey (Hash: integer): {n} pointer;
function KeyToHash (Key: {n} pointer): integer;
procedure FreeNodeValue (Node: PObjBinTreeNode);
procedure FreeNode ({IN} var {n} Node: PObjBinTreeNode);
procedure RemoveNode ({n} ParentNode: PObjBinTreeNode; Node: PObjBinTreeNode);
function CloneNode (Node: PObjBinTreeNode): {O} PObjBinTreeNode;
(*
All nodes are placed in NodeArray and disconnected from each other.
Original binary tree is emptied. Nodes are sorted by hash.
*)
procedure ConvertToLinearNodeArray (out Res: TObjBinTreeLinearNodeArray);
function FindItem
(
{n} Key: pointer;
out {ni} ParentNode: PObjBinTreeNode;
out {ni} ItemNode: PObjBinTreeNode
): boolean;
(***) public (***)
constructor Create
(
OwnsItems: boolean;
ItemsAreObjects: boolean;
ItemGuardProc: Utils.TItemGuardProc;
{IN} var {n} ItemGuard: Utils.TItemGuard
);
destructor Destroy; override;
procedure Assign (Source: Utils.TCloneable); override;
procedure Clear;
function IsValidValue ({n} Value: pointer): boolean;
function CalcCritDepth: integer; inline;
procedure Rebuild;
function GetValue ({n} Key: pointer): {n} pointer;
function GetExistingValue ({n} Key: pointer; out {Un} Res: pointer): boolean;
procedure SetValue ({n} Key: pointer; {OUn} NewValue: pointer);
function DeleteItem ({n} Key: pointer): boolean;
(* Returns value with specified key and NILify it in the array *)
function TakeValue ({n} Key: pointer; out {OUn} Value: pointer): boolean;
{Returns old value}
function ReplaceValue
(
{n} Key: pointer;
{OUn} NewValue: pointer;
out {OUn} OldValue: pointer
): boolean;
procedure BeginIterate;
function IterateNext (out {Un} Key: pointer; out {Un} Value: pointer): boolean;
procedure EndIterate;
property OwnsItems: boolean read fOwnsItems;
property ItemsAreObjects: boolean read fItemsAreObjects;
property ItemCount: integer read fNodeCount;
property ItemGuardProc: Utils.TItemGuardProc read fItemGuardProc;
property NodeCount: integer read fNodeCount;
property Locked: boolean read fLocked;
property Items[{n} Key: pointer]: {OUn} pointer read GetValue write SetValue; default;
end; // .class TObjBinTree
PStrHashTableItem = ^TStrHashTableItem;
TStrHashTableItem = record
SearchDistance: integer; // Counts from 1. 0 means empty
Hash: integer;
PreprocessedKey: string;
Value: pointer;
Key: string;
procedure MakeEmpty; inline;
procedure Exchange (var OtherItem: TStrHashTableItem); inline;
end;
TStrHashTableItems = array of TStrHashTableItem;
TStrHashTableItemUnmanaged = array [0..sizeof(TStrHashTableItem) - 1] of byte;
TStrHashTableItemsUnmanaged = array of TStrHashTableItemUnmanaged;
TStrHashTable = class (Utils.TCloneable)
const
MIN_CAPACITY = 16; // Must be power of 2
MAX_LOAD_FACTOR = 0.85;
MIN_LOAD_FACTOR = MAX_LOAD_FACTOR / 4;
GROWTH_FACTOR = 2; // Must be power of 2
protected
fItems: TStrHashTableItems;
fCapacity: integer;
fModCapacityMask: integer; // (X and fModCapacityMask) = (X mod fCapacity)
fSize: integer;
fMinSize: integer;
fMaxSize: integer;
fOwnsItems: boolean;
fItemsAreObjects: boolean;
fHashFunc: THashFunc;
{n} fKeyPreprocessFunc: TKeyPreprocessFunc;
{On} fItemGuard: Utils.TItemGuard;
fItemGuardProc: Utils.TItemGuardProc;
fIterPos: integer;
fLocked: boolean;
function GetPreprocessedKey (const Key: string): string; inline;
procedure FreeItemValue (Item: PStrHashTableItem);
procedure FreeValues;
(* Must be called each time, the capacity is changed to maintain dependent values *)
procedure OnChangeCapacity;
(* Discards existing storage and recreates the new one. Be sure to free/move values first *)
procedure CreateNewStorage (NewCapacity: integer);
(* On failure ItemInd is index to continue checking for possible displacement *)
function FindItem (Hash: integer; const PreprocessedKey: string; var ItemInd: integer): {Un} PStrHashTableItem;
procedure AddValue (Hash: integer; const Key, PreprocessedKey: string; {OUn} NewValue: pointer; ItemInd: integer);
procedure Rehash (NewCapacity: integer);
procedure Grow;
procedure ShrinkIfReasonable;
procedure Shrink;
public
{$IFDEF INSPECT_SEARCH_DISTANCE}
TotalSearchDistance: integer; // Increased by item search distance during items search only, not on rehashing
MaxSearchDistance: integer; // Maximum search distance, met during items search
{$ENDIF}
constructor Create (HashFunc: THashFunc; {n} KeyPreprocessFunc: TKeyPreprocessFunc; OwnsItems, ItemsAreObjects: boolean; ItemGuardProc: Utils.TItemGuardProc;
{On} ItemGuard: Utils.TItemGuard);
destructor Destroy; override;
procedure Assign (Source: Utils.TCloneable); override;
procedure Clear;
function IsValidValue ({n} Value: pointer): boolean;
function GetValue (const Key: string): {n} pointer;
function HasKey (const Key: string): boolean;
function GetExistingValue (const Key: string; {out} var {Un} Res: pointer): boolean;
procedure SetValue (const Key: string; {OUn} NewValue: pointer);
function DeleteItem (const Key: string): boolean;
(* Returns value with specified key and nilify it in the array *)
function TakeValue (const Key: string; {out} var {OUn} Value: pointer): boolean;
(* Returns old value *)
function ReplaceValue (const Key: string; {OUn} NewValue: pointer; {out} var {OUn} OldValue: pointer): boolean;
procedure BeginIterate;
function IterateNext (out Key: string; out {Un} Value: pointer): boolean;
procedure EndIterate;
property HashFunc: THashFunc read fHashFunc;
property KeyPreprocessFunc: TKeyPreprocessFunc read fKeyPreprocessFunc;
property OwnsItems: boolean read fOwnsItems;
property ItemsAreObjects: boolean read fItemsAreObjects;
property ItemCount: integer read fSize;
property ItemGuardProc: Utils.TItemGuardProc read fItemGuardProc;
property Locked: boolean read fLocked;
property Items[const Key: string]: pointer read {n} GetValue write {OUn} SetValue; default;
end; // .class TStrHashTable
PObjHashTableItem = ^TObjHashTableItem;
TObjHashTableItem = record
SearchDistance: integer; // Counts from 1. 0 means empty
Hash: integer;
Value: pointer;
procedure MakeEmpty; inline;
procedure Exchange (var OtherItem: TObjHashTableItem); inline;
end;
TObjHashTableItems = array of TObjHashTableItem;
TObjHashTable = class (Utils.TCloneable)
const
MIN_CAPACITY = 16; // Must be power of 2
MAX_LOAD_FACTOR = 0.85;
MIN_LOAD_FACTOR = MAX_LOAD_FACTOR / 4;
GROWTH_FACTOR = 2; // Must be power of 2
protected
fItems: TObjHashTableItems;
fCapacity: integer;
fModCapacityMask: integer; // (X and fModCapacityMask) = (X mod fCapacity)
fSize: integer;
fMinSize: integer;
fMaxSize: integer;
fOwnsItems: boolean;
fItemsAreObjects: boolean;
{On} fItemGuard: Utils.TItemGuard;
fItemGuardProc: Utils.TItemGuardProc;
fIterPos: integer;
fLocked: boolean;
function HashToKey (Hash: integer): {n} pointer; inline;
function KeyToHash (Key: {n} pointer): integer; inline;
procedure FreeItemValue (Item: PObjHashTableItem);
procedure FreeValues;
(* Must be called each time, the capacity is changed to maintain dependent values *)
procedure OnChangeCapacity;
(* Discards existing storage and recreates the new one. Be sure to free/move values first *)
procedure CreateNewStorage (NewCapacity: integer);
(* On failure ItemInd is index to continue checking for possible displacement *)
function FindItem (Hash: integer; var ItemInd: integer): {Un} PObjHashTableItem;
procedure AddValue (Hash: integer; {OUn} NewValue: pointer; ItemInd: integer);
procedure Rehash (NewCapacity: integer);
procedure Grow;
procedure ShrinkIfReasonable;
procedure Shrink;
public
{$IFDEF INSPECT_SEARCH_DISTANCE}
TotalSearchDistance: integer; // Increased by item search distance during items search only, not on rehashing
MaxSearchDistance: integer; // Maximum search distance, met during items search
{$ENDIF}
constructor Create (OwnsItems, ItemsAreObjects: boolean; ItemGuardProc: Utils.TItemGuardProc; {On} ItemGuard: Utils.TItemGuard);
destructor Destroy; override;
procedure Assign (Source: Utils.TCloneable); override;
procedure Clear;
function IsValidValue ({n} Value: pointer): boolean;
function GetValue ({n} Key: pointer): {n} pointer;
function HasKey ({n} Key: pointer): boolean;
function GetExistingValue ({n} Key: pointer; {out} var {Un} Res: pointer): boolean;
procedure SetValue ({n} Key: pointer; {OUn} NewValue: pointer);
function DeleteItem ({n} Key: pointer): boolean;
(* Returns value with specified key and nilify it in the array *)
function TakeValue ({n} Key: pointer; {out} var {OUn} Value: pointer): boolean;
(* Returns old value *)
function ReplaceValue ({n} Key: pointer; {OUn} NewValue: pointer; {out} var {OUn} OldValue: pointer): boolean;
procedure BeginIterate;
function IterateNext (out {Un} Key: pointer; out {Un} Value: pointer): boolean;
procedure EndIterate;
property OwnsItems: boolean read fOwnsItems;
property ItemsAreObjects: boolean read fItemsAreObjects;
property ItemCount: integer read fSize;
property ItemGuardProc: Utils.TItemGuardProc read fItemGuardProc;
property Locked: boolean read fLocked;
property Items[{n} Key: pointer]: pointer read {n} GetValue write {OUn} SetValue; default;
end; // .class TObjHashTable
TAssocArray = TStrHashTable;
TObjArray = TObjHashTable;
function NewAssocArr (HashFunc: THashFunc; {n} KeyPreprocessFunc: TKeyPreprocessFunc; OwnsItems, ItemsAreObjects: boolean; ItemType: TClass; AllowNil: boolean): TAssocArray;
function NewSimpleAssocArr (HashFunc: THashFunc; {n} KeyPreprocessFunc: TKeyPreprocessFunc): TAssocArray;
function NewStrictAssocArr ({n} TypeGuard: TClass; OwnsItems: boolean = true): TAssocArray;
function NewObjArr (OwnsItems, ItemsAreObjects: boolean; ItemType: TClass; AllowNil: boolean): TObjArray;
function NewSimpleObjArr: TObjArray;
function NewStrictObjArr ({n} TypeGuard: TClass; OwnsItems: boolean = true): TObjArray;
function NewSimpleStrBinTree (HashFunc: THashFunc; {n} KeyPreprocessFunc: TKeyPreprocessFunc): TStrBinTree;
procedure MergeAssocArrays (Destination, Source: TAssocArray);
procedure MergeObjArrays (Destination, Source: TObjArray);
(***) implementation (***)
const
EMPTY_ITEM_SEARCH_DISTANCE = 0;
DEBUG_BUILD = false;
constructor TStrBinTree.Create
(
HashFunc: THashFunc;
{n} KeyPreprocessFunc: TKeyPreprocessFunc;
OwnsItems: boolean;
ItemsAreObjects: boolean;
ItemGuardProc: Utils.TItemGuardProc;
{IN} var {n} ItemGuard: Utils.TItemGuard
);
begin
{!} Assert(@HashFunc <> nil);
{!} Assert(@ItemGuardProc <> nil);
Self.fHashFunc := HashFunc;
Self.fKeyPreprocessFunc := KeyPreprocessFunc;
Self.fOwnsItems := OwnsItems;
Self.fItemsAreObjects := ItemsAreObjects;
Self.fItemGuardProc := ItemGuardProc;
Self.fItemGuard := ItemGuard;
Self.fItemCount := 0;
Self.fNodeCount := 0;
ItemGuard := nil;
end; // .constructor TStrBinTree.Create
destructor TStrBinTree.Destroy;
begin
Self.Clear;
SysUtils.FreeAndNil(Self.fItemGuard);
end; // .destructor TStrBinTree.Destroy
function TStrBinTree.CloneItem (Item: PStrBinTreeItem): {O} PStrBinTreeItem;
begin
{!} Assert(Item <> nil);
{!} Assert(Self.IsValidValue(Item.Value));
New(result);
result.Key := Item.Key;
if Item.NextItem <> nil then begin
result.NextItem := Self.CloneItem(Item.NextItem);
end else begin
result.NextItem := nil;
end;
if (Item.Value = nil) or (not Self.OwnsItems) then begin
result.Value := Item.Value;
end else begin
{!} Assert(Self.ItemsAreObjects);
{!} Assert(TObject(Item.Value) IS Utils.TCloneable);
result.Value := Utils.TCloneable(Item.Value).Clone;
end;
end; // .function TStrBinTree.CloneItem
function TStrBinTree.CloneNode ({n} Node: PStrBinTreeNode): {On} PStrBinTreeNode;
begin
if Node = nil then begin
result := nil;
end else begin
New(result);
result.Hash := Node.Hash;
result.Item := Self.CloneItem(Node.Item);
result.ChildNodes[LEFT_CHILD] := Self.CloneNode(Node.ChildNodes[LEFT_CHILD]);
result.ChildNodes[RIGHT_CHILD] := Self.CloneNode(Node.ChildNodes[RIGHT_CHILD]);
end;
end; // .function TStrBinTree.CloneNode
procedure TStrBinTree.Assign (Source: Utils.TCloneable);
var
{U} SrcArr: TStrBinTree;
begin
{!} Assert(not Self.Locked);
{!} Assert(Source <> nil);
SrcArr := Source AS TStrBinTree;
// * * * * * //
if Self <> Source then begin
Self.Clear;
Self.fHashFunc := SrcArr.HashFunc;
Self.fKeyPreprocessFunc := SrcArr.KeyPreprocessFunc;
Self.fOwnsItems := SrcArr.OwnsItems;
Self.fItemsAreObjects := SrcArr.ItemsAreObjects;
Self.fItemGuardProc := SrcArr.ItemGuardProc;
Self.fItemGuard := SrcArr.fItemGuard.Clone;
Self.fItemCount := SrcArr.ItemCount;
Self.fNodeCount := SrcArr.NodeCount;
Self.fRoot := Self.CloneNode(SrcArr.fRoot);
end; // .if
end; // .procedure TStrBinTree.Assign
procedure TStrBinTree.FreeItemValue (Item: PStrBinTreeItem);
begin
{!} Assert(Item <> nil);
if Self.OwnsItems then begin
if Self.ItemsAreObjects then begin
TObject(Item.Value).Free;
end else begin
FreeMem(Item.Value);
end;
end;
Item.Value := nil;
end; // .procedure TStrBinTree.FreeItemValue
procedure TStrBinTree.RemoveNode ({n} ParentNode: PStrBinTreeNode; ItemNode: PStrBinTreeNode);
var
{U} RightClosestNodeParent: PStrBinTreeNode;
{U} RightClosestNode: PStrBinTreeNode;
ItemNodeIsRoot: boolean;
ItemNodeSide: TChildNodeSide;
begin
{!} Assert(ItemNode <> nil);
RightClosestNodeParent := nil;
RightClosestNode := nil;
ItemNodeSide := false;
// * * * * * //
ItemNodeIsRoot := ParentNode = nil;
if Self.NodeCount = 1 then begin
{!} Assert(ItemNodeIsRoot);
{!} Assert(ItemNode = Self.fRoot);
Dispose(Self.fRoot); Self.fRoot := nil;
end else begin
if not ItemNodeIsRoot then begin
ItemNodeSide := ItemNode.Hash >= ParentNode.Hash;
end;
(* N
- -
*)
if
(ItemNode.ChildNodes[LEFT_CHILD] = nil) and
(ItemNode.ChildNodes[RIGHT_CHILD] = nil)
then begin
ParentNode.ChildNodes[ItemNodeSide] := nil;
Dispose(ItemNode); ItemNode := nil;
end // .if
(* N
- R
*)
else if ItemNode.ChildNodes[LEFT_CHILD] = nil then begin
if ItemNodeIsRoot then begin
Self.fRoot := ItemNode.ChildNodes[RIGHT_CHILD];
end else begin
ParentNode.ChildNodes[ItemNodeSide] := ItemNode.ChildNodes[RIGHT_CHILD];
end;
Dispose(ItemNode); ItemNode := nil;
end // .elseif
(* N
L -
*)
else if ItemNode.ChildNodes[RIGHT_CHILD] = nil then begin
if ItemNodeIsRoot then begin
Self.fRoot := ItemNode.ChildNodes[LEFT_CHILD];
end else begin
ParentNode.ChildNodes[ItemNodeSide] := ItemNode.ChildNodes[LEFT_CHILD];
end;
Dispose(ItemNode); ItemNode := nil;
end // .elseif
(* N
L R
*)
else begin
RightClosestNodeParent := ItemNode;
RightClosestNode := ItemNode.ChildNodes[RIGHT_CHILD];
while RightClosestNode.ChildNodes[LEFT_CHILD] <> nil do begin
RightClosestNodeParent := RightClosestNode;
RightClosestNode := RightClosestNode.ChildNodes[LEFT_CHILD];
end;
ItemNode.Item := RightClosestNode.Item; RightClosestNode.Item := nil;
ItemNode.Hash := RightClosestNode.Hash;
Self.RemoveNode(RightClosestNodeParent, RightClosestNode);
end; // .else
end; // .else
end; // .procedure TStrBinTree.RemoveNode
procedure TStrBinTree.RemoveItem
(
{n} ParentNode: PStrBinTreeNode;
ItemNode: PStrBinTreeNode;
{n} ParentItem: PStrBinTreeItem;
Item: PStrBinTreeItem
);
begin
{!} Assert(ItemNode <> nil);
{!} Assert(Item <> nil);
Self.FreeItemValue(Item);
if (ItemNode.Item = Item) and (Item.NextItem = nil) then begin
Self.RemoveNode(ParentNode, ItemNode);
(* RemoveNode is recursive procedure not affecting the counter *)
Dec(Self.fNodeCount);
end else begin
if ItemNode.Item = Item then begin
ItemNode.Item := Item.NextItem;
end else begin
{!} Assert(ParentItem <> nil);
ParentItem.NextItem := Item.NextItem;
end;
end; // .else
Dispose(Item); Item := nil;
Dec(Self.fItemCount);
end; // .procedure TStrBinTree.RemoveItem
procedure TStrBinTree.FreeNode ({IN} var {n} Node: PStrBinTreeNode);
var
{U} Item: PStrBinTreeItem;
{U} NextItem: PStrBinTreeItem;
begin
Item := nil;
NextItem := nil;
// * * * * * //
if Node <> nil then begin
Item := Node.Item;
while Item <> nil do begin
NextItem := Item.NextItem;
Self.FreeItemValue(Item);
Dispose(Item); Item := nil;
Item := NextItem;
end;
Self.FreeNode(Node.ChildNodes[LEFT_CHILD]);
Self.FreeNode(Node.ChildNodes[RIGHT_CHILD]);
Dispose(Node); Node := nil;
end; // .if
end; // .procedure TStrBinTree.FreeNode
procedure TStrBinTree.Clear;
begin
{!} Assert(not Self.Locked);
Self.FreeNode(Self.fRoot);
Self.fItemCount := 0;
Self.fNodeCount := 0;
end;
function TStrBinTree.GetPreprocessedKey (const Key: string): string;
begin
if @Self.KeyPreprocessFunc = nil then begin
result := Key;
end else begin
result := Self.KeyPreprocessFunc(Key);
end;
end;
function TStrBinTree.IsValidValue ({n} Value: pointer): boolean;
begin
result := Self.ItemGuardProc(Value, Self.ItemsAreObjects, Utils.TItemGuard(Self.fItemGuard));
end;
function TStrBinTree.CalcCritDepth: integer;
begin
result := Alg.IntLog2(Self.NodeCount + 1) shl 1;
end;
function AssocArrayCompareNodes (A, B: integer): integer;
begin
if PStrBinTreeNode(A).Hash > PStrBinTreeNode(B).Hash then begin
result := +1;
end else if PStrBinTreeNode(A).Hash < PStrBinTreeNode(B).Hash then begin
result := -1;
end else begin
result := 0;
end;
end;
procedure TStrBinTree.ConvertToLinearNodeArray (out Res: TStrBinTreeLinearNodeArray);
var
LeftInd: integer;
RightInd: integer;
RightCheckInd: integer;
NumNotProcessedNodes: integer;
{U} CurrNode: PStrBinTreeNode;
i: integer;
begin
SetLength(Res.NodeArray, Self.NodeCount);
Res.NodeCount := Self.NodeCount;
Res.ItemCount := Self.ItemCount;
if Self.NodeCount > 0 then begin
CurrNode := Self.fRoot;
LeftInd := 0;
Res.NodeArray[LeftInd] := CurrNode;
RightInd := Self.NodeCount;
RightCheckInd := RightInd - 1;
NumNotProcessedNodes := Self.NodeCount - 1;
while NumNotProcessedNodes > 0 do begin
if CurrNode.ChildNodes[RIGHT_CHILD] <> nil then begin
Dec(RightInd);
Res.NodeArray[RightInd] := CurrNode.ChildNodes[RIGHT_CHILD];
Dec(NumNotProcessedNodes);
end;
if CurrNode.ChildNodes[LEFT_CHILD] <> nil then begin
CurrNode := CurrNode.ChildNodes[LEFT_CHILD];
Inc(LeftInd);
Res.NodeArray[LeftInd] := CurrNode;
Dec(NumNotProcessedNodes);
end else begin
CurrNode := Res.NodeArray[RightCheckInd];
Dec(RightCheckInd);
end;
end; // .while
for i:=0 to Self.NodeCount - 1 do begin
Res.NodeArray[i].ChildNodes[LEFT_CHILD] := nil;
Res.NodeArray[i].ChildNodes[RIGHT_CHILD] := nil;
end;
Self.fRoot := nil;
Self.fNodeCount := 0;
Self.fItemCount := 0;
Alg.CustomQuickSort(pointer(Res.NodeArray), 0, Res.NodeCount - 1, AssocArrayCompareNodes);
end; // .if
end; // .procedure TStrBinTree.ConvertToLinearNodeArray
procedure TStrBinTree.Rebuild;
var
LinearNodeArray: TStrBinTreeLinearNodeArray;
NodeArray: TStrBinTreeNodeArray;
procedure InsertNode (InsNode: PStrBinTreeNode);
var
{U} ParentNode: PStrBinTreeNode;
{U} CurrNode: PStrBinTreeNode;
begin
{!} Assert(InsNode <> nil);
ParentNode := nil;
CurrNode := Self.fRoot;
// * * * * * //
while CurrNode <> nil do begin
ParentNode := CurrNode;
CurrNode := CurrNode.ChildNodes[InsNode.Hash >= CurrNode.Hash];
end;
ParentNode.ChildNodes[InsNode.Hash >= ParentNode.Hash] := InsNode;
end; // .procedure InsertNode
procedure InsertNodeRange (MinInd, MaxInd: integer);
var
{U} InsNode: PStrBinTreeNode;
RangeLen: integer;
MiddleInd: integer;
begin
RangeLen := MaxInd - MinInd + 1;
{!} Assert(RangeLen > 0);
{!} Assert((MinInd >= 0) and (MaxInd < Length(NodeArray)));
// * * * * * //
MiddleInd := MinInd + (MaxInd - MinInd) shr 1;
InsNode := NodeArray[MiddleInd];
if Self.fRoot = nil then begin
Self.fRoot := InsNode;
end else begin
InsertNode(InsNode);
end;
if RangeLen > 2 then begin
InsertNodeRange(MinInd, MiddleInd - 1);
InsertNodeRange(MiddleInd + 1, MaxInd);
end else if RangeLen = 2 then begin
InsertNode(NodeArray[MiddleInd + 1]);
end;
end; // .procedure InsertNodeRange
begin
{!} Assert(not Self.Locked);
if Self.NodeCount > 2 then begin
Self.ConvertToLinearNodeArray(LinearNodeArray);
Self.fNodeCount := LinearNodeArray.NodeCount;
Self.fItemCount := LinearNodeArray.ItemCount;
NodeArray := LinearNodeArray.NodeArray;
InsertNodeRange(0, Self.NodeCount - 1);
end;
end; // .procedure TStrBinTree.Rebuild
function TStrBinTree.FindItem
(
Hash: integer;
const Key: string;
out {ni} ParentNode: PStrBinTreeNode;
out {ni} ItemNode: PStrBinTreeNode;
out {ni} ParentItem: PStrBinTreeItem;
out {ni} Item: PStrBinTreeItem
): boolean;
var
SearchDepth: integer;
CritSearchDepth: integer;
begin
if DEBUG_BUILD then begin
{!} Assert(ParentNode = nil);
{!} Assert(ItemNode = nil);
{!} Assert(ParentItem = nil);
{!} Assert(Item = nil);
end;
result := false;
if Self.NodeCount > 0 then begin
CritSearchDepth := Self.CalcCritDepth;
SearchDepth := 1;
ItemNode := Self.fRoot;
while (ItemNode <> nil) and (ItemNode.Hash <> Hash) do begin
Inc(SearchDepth);
ParentNode := ItemNode;
ItemNode := ItemNode.ChildNodes[Hash >= ItemNode.Hash];
end;
if SearchDepth > CritSearchDepth then begin
Self.Rebuild;
ParentNode := nil;
ItemNode := nil;
ParentItem := nil;
Item := nil;
result := Self.FindItem(Hash, Key, ParentNode, ItemNode, ParentItem, Item);
end else if ItemNode <> nil then begin
Item := ItemNode.Item;
while (Item <> nil) and (Self.GetPreprocessedKey(Item.Key) <> Key) do begin
ParentItem := Item;
Item := Item.NextItem;
end;
result := Item <> nil;
end; // .elseif
end; // .if
end; // .function TStrBinTree.FindItem
function TStrBinTree.GetValue (const Key: string): {n} pointer;
var
{U} ItemNode: PStrBinTreeNode;
{U} ParentNode: PStrBinTreeNode;
{U} Item: PStrBinTreeItem;
{U} ParentItem: PStrBinTreeItem;
PreprocessedKey: string;
begin
ItemNode := nil;
ParentNode := nil;
Item := nil;
ParentItem := nil;
// * * * * * //
PreprocessedKey := Self.GetPreprocessedKey(Key);
result := nil;
if Self.FindItem(Self.HashFunc(PreprocessedKey), PreprocessedKey, ParentNode, ItemNode, ParentItem, Item) then begin
result := Item.Value;
end;
end; // .function TStrBinTree.GetValue
function TStrBinTree.HasKey (const Key: string): boolean;
var
{U} ItemNode: PStrBinTreeNode;
{U} ParentNode: PStrBinTreeNode;
{U} Item: PStrBinTreeItem;
{U} ParentItem: PStrBinTreeItem;
PreprocessedKey: string;
begin
ItemNode := nil;
ParentNode := nil;
Item := nil;
ParentItem := nil;
// * * * * * //
PreprocessedKey := Self.GetPreprocessedKey(Key);
result := Self.FindItem(Self.HashFunc(PreprocessedKey), PreprocessedKey, ParentNode, ItemNode, ParentItem, Item);
end;
function TStrBinTree.GetExistingValue (const Key: string; out {Un} Res: pointer): boolean;
var
{U} ItemNode: PStrBinTreeNode;
{U} ParentNode: PStrBinTreeNode;
{U} Item: PStrBinTreeItem;
{U} ParentItem: PStrBinTreeItem;
PreprocessedKey: string;
begin
{!} Assert(Res = nil);
ItemNode := nil;
ParentNode := nil;
Item := nil;
ParentItem := nil;
// * * * * * //
PreprocessedKey := Self.GetPreprocessedKey(Key);
result := Self.FindItem(Self.HashFunc(PreprocessedKey), PreprocessedKey, ParentNode, ItemNode, ParentItem, Item);
if result then begin
Res := Item.Value;
end;
end; // .function TStrBinTree.GetExistingValue
procedure TStrBinTree.SetValue (const Key: string; {OUn} NewValue: pointer);
var
{U} ItemNode: PStrBinTreeNode;
{U} ParentNode: PStrBinTreeNode;
{U} Item: PStrBinTreeItem;
{U} ParentItem: PStrBinTreeItem;
{O} NewItem: PStrBinTreeItem;
{O} NewNode: PStrBinTreeNode;
PreprocessedKey: string;
Hash: integer;
begin
ItemNode := nil;
ParentNode := nil;
Item := nil;
ParentItem := nil;
NewItem := nil;
NewNode := nil;
// * * * * * //
{!} Assert(Self.IsValidValue(NewValue));
PreprocessedKey := Self.GetPreprocessedKey(Key);
Hash := Self.HashFunc(PreprocessedKey);
if Self.FindItem(Hash, PreprocessedKey, ParentNode, ItemNode, ParentItem, Item) then begin
if Item.Value <> NewValue then begin
Self.FreeItemValue(Item);
Item.Value := NewValue;
end;
end else begin
{!} Assert(not Self.Locked);
New(NewItem);
NewItem.Key := Key;