-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
MemVector.pas
1436 lines (1210 loc) · 44.7 KB
/
MemVector.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 Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Memory vector
This library provides base class for implementing memory vectors - that is,
a contiguous memory containing an array of items.
Most of the functinonality is the same as for normal dynamic arrays or
lists, but it provides some more advanced features like item initialization
and finalization and provides better memory locality (everything is
together). The most important feature is, that the items are truly
contiguous in the memory, there is no padding or other potential issues
lists or arrays can have (memory fragmentation, problematic reallocation).
Although the base class (TMemVector) can be used directly, it is intended
to be inherited from in a descendant class that implements vector for a
specific item type. An integer vector is implemented as an example.
Version 1.2.4 (2024-05-02)
Last change 2024-10-04
©2016-2024 František Milt
Contacts:
František Milt: [email protected]
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.MemVector
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
* BinaryStreamingLite - github.com/TheLazyTomcat/Lib.BinaryStreamingLite
ListSorters - github.com/TheLazyTomcat/Lib.ListSorters
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol MemVector_UseAuxExceptions for details).
BinaryStreamingLite can be replaced by full BinaryStreaming.
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
(*******************************************************************************
Not implemented as a generic class mainly because of backward compatibility.
To create a derived/specialized class from base class, replace @ClassName@
with a class identifier and @Type@ with identifier of used type in the
following template. Also remember to implement proper comparison function
for a chosen type.
Optional methods are not required to be implemented, but they might be usefull
in some instances (eg. when item contains reference-counted types, pointers
or object references).
== Declaration ===============================================================
--------------------------------------------------------------------------------
@ClassName@ = class(TMemVector)
protected
Function GetItem(Index: Integer): @Type@; virtual;
procedure SetItem(Index: Integer; Value: @Type@); virtual;
//procedure ItemInit(Item: Pointer); override;
//procedure ItemFinal(Item: Pointer); override;
//procedure ItemCopy(SrcItem,DstItem: Pointer); override;
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
//Function ItemEquals(Item1,Item2: Pointer): Boolean; override;
//procedure ItemWrite(Item: Pointer; Stream: TStream); override;
//procedure ItemRead(Item: Pointer; Stream: TStream); override;
public
constructor Create; overload;
constructor Create(Memory: Pointer; Count: Integer); overload;
Function First: @Type@; reintroduce;
Function Last: @Type@; reintroduce;
Function IndexOf(Item: @Type@): Integer; reintroduce;
Function Find(Item: @Type@; out Index: Integer): Boolean; reintroduce;
Function Add(Item: @Type@): Integer; reintroduce;
procedure Insert(Index: Integer; Item: @Type@); reintroduce;
Function Remove(Item: @Type@): Integer; reintroduce;
Function Extract(Item: @Type@): @Type@; reintroduce;
property Items[Index: Integer]: @Type@ read GetItem write SetItem; default;
end;
== Implementation ============================================================
--------------------------------------------------------------------------------
Function @[email protected](Index: Integer): @Type@;
begin
Result := @Type@(GetItemPtr(Index)^);
end;
//------------------------------------------------------------------------------
procedure @[email protected](Index: Integer; Value: @Type@);
begin
SetItemPtr(Index,@Value);
end;
//------------------------------------------------------------------------------
// Method called for each item that is implicitly (eg. when changing the Count
// property to a higher number) added to the vector.
// Item is filled with zeroes in default implementation.
//procedure @[email protected](Item: Pointer);
//begin
//{$MESSAGE WARN 'Implement item initialization to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Method called for each item that is implicitly (e.g. when changing the Count
// property to a lower number) removed from the vector.
// No default behavior.
//procedure @[email protected](Item: Pointer);
//begin
//{$MESSAGE WARN 'Implement item finalization to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Called when an item is copied to the vector from an external source and
// ManagedCopy is set to true. Called only by methods that has parameter
// ManagedCopy.
// Item is copied without any further processing in default implementation.
//procedure @[email protected](SrcItem,DstItem: Pointer);
//begin
//{$MESSAGE WARN 'Implement item copy to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// This method is called when there is a need to compare two items, for example
// when sorting the vector.
// Must return positive number when Item1 is higher/larger than Item2, zero when
// they are equal and negative number when Item1 is lower/smaller than Item2.
// No default implementation.
// This method must be implemented in derived classes!
Function @[email protected](Item1,Item2: Pointer): Integer;
begin
{$MESSAGE WARN 'Implement comparison to suit actual type.'}
end;
//------------------------------------------------------------------------------
// Called when two items are compared for equality (e.g. when searching for a
// particular item).
// In default implementation, it calls ItemCompare and when it returns zero,
// items are considered to be equal.
//Function @[email protected](Item1,Item2: Pointer): Boolean;
//begin
//{$MESSAGE WARN 'Implement equality comparison to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Method called for each item being written to the stream.
// Default implementation direcly writes ItemSize bytes from the item memory
// to the stream, with no further processing.
//procedure @[email protected](Item: Pointer; Stream: TStream);
//begin
//{$MESSAGE WARN 'Implement item write to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Method called for each item being read from the stream.
// Default implementation reads ItemSize bytes directly to the item memory with
// no further processing.
//procedure @[email protected](Item: Pointer; Stream: TStream);
//begin
//{$MESSAGE WARN 'Implement item read to suit actual type.'}
//end;
//==============================================================================
constructor @[email protected];
begin
inherited Create(SizeOf(@Type@));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor @[email protected](Memory: Pointer; Count: Integer);
begin
inherited Create(Memory,Count,SizeOf(@Type@));
end;
//------------------------------------------------------------------------------
Function @[email protected]: @Type@;
begin
Result := @Type@(inherited First^);
end;
//------------------------------------------------------------------------------
Function @[email protected]: @Type@;
begin
Result := @Type@(inherited Last^);
end;
//------------------------------------------------------------------------------
Function @[email protected](Item: @Type@): Integer;
begin
Result := inherited IndexOf(@Item);
end;
//------------------------------------------------------------------------------
Function @[email protected](Item: @Type@; out Index: Integer): Boolean;
begin
Result := inherited Find(@Item,Index);
end;
//------------------------------------------------------------------------------
Function @[email protected](Item: @Type@): Integer;
begin
Result := inherited Add(@Item);
end;
//------------------------------------------------------------------------------
procedure @[email protected](Index: Integer; Item: @Type@);
begin
inherited Insert(Index,@Item);
end;
//------------------------------------------------------------------------------
Function @[email protected](Item: @Type@): Integer;
begin
Result := inherited Remove(@Item);
end;
//------------------------------------------------------------------------------
Function @[email protected](Item: @Type@): @Type@;
var
TempPtr: Pointer;
begin
TempPtr := inherited Extract(@Item);
If Assigned(TempPtr) then
Result := @Type@(TempPtr^)
else
Result := {$MESSAGE WARN 'Set to some invalid value (eg. 0, nil, '''', ...).'};
end;
*******************************************************************************)
unit MemVector;
{
MemVector_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
MemVector_UseAuxExceptions to achieve this.
}
{$IF Defined(MemVector_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH ClassicProcVars+}
{$MODESWITCH DuplicateLocals+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
interface
uses
SysUtils, Classes,
AuxTypes, AuxClasses{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
EMVException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
EMVIndexOutOfBounds = class(EMVException);
EMVForeignMemory = class(EMVException);
EMVInvalidValue = class(EMVException);
EMVIncompatibleClass = class(EMVException);
{===============================================================================
--------------------------------------------------------------------------------
TMemVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMemVector - class declaration
===============================================================================}
type
TMemVector = class(TCustomListObject)
protected
fItemSize: TMemSize;
fOwnsMemory: Boolean;
fMemory: Pointer;
fCapacity: Integer;
fCount: Integer;
fUpdateCounter: Integer;
fChanged: Boolean;
fOnChangeEvent: TNotifyEvent;
fOnChangeCallback: TNotifyCallback;
fTempItem: Pointer;
fLoading: Boolean;
// getters, setters
Function GetItemPtr(Index: Integer): Pointer; virtual;
procedure SetItemPtr(Index: Integer; Value: Pointer); virtual;
Function GetSize: TMemSize; virtual;
Function GetAllocatedSize: TMemSize; virtual;
// inherited list methods
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
// item management
procedure ItemInit(Item: Pointer); virtual;
procedure ItemFinal(Item: Pointer); virtual;
procedure ItemCopy(SrcItem,DstItem: Pointer); virtual;
Function ItemCompare(Item1,Item2: Pointer): Integer; virtual;
Function ItemEquals(Item1,Item2: Pointer): Boolean; virtual;
procedure ItemWrite(Item: Pointer; Stream: TStream); virtual;
procedure ItemRead(Item: Pointer; Stream: TStream); virtual;
// utility and macro methods
Function CheckIndexAndRaise(Index: Integer; CallingMethod: String = 'CheckIndexAndRaise'): Boolean; virtual;
Function GetNextItemPtr(ItemPtr: Pointer): Pointer; virtual;
Function CompareItems(Index1,Index2: Integer): Integer; virtual;
procedure FinalizeAllItems; virtual;
procedure DoChange; virtual;
procedure ReadFromStreamInternal(Stream: TStream); virtual;
public
constructor Create(ItemSize: TMemSize); overload;
constructor Create(Memory: Pointer; Count: Integer; ItemSize: TMemSize); overload;
destructor Destroy; override;
// updates
procedure BeginUpdate; virtual;
Function EndUpdate: Integer; virtual;
// first/last
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function First: Pointer; virtual;
Function Last: Pointer; virtual;
// list methods
Function IndexOf(Item: Pointer): Integer; virtual;
Function Find(Item: Pointer; out Index: Integer): Boolean; virtual;
Function Add(Item: Pointer): Integer; virtual;
procedure Insert(Index: Integer; Item: Pointer); virtual;
procedure Move(SrcIndex,DstIndex: Integer); virtual;
procedure Exchange(Index1,Index2: Integer); virtual;
Function Extract(Item: Pointer): Pointer; virtual; // does not call ItemFinal
Function Remove(Item: Pointer): Integer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
// list manipulation
procedure Reverse; virtual;
procedure Sort(Reversed: Boolean = False); virtual;
// comparations
Function IsEqual(Vector: TMemVector): Boolean; virtual;
Function IsEqualBinary(Vector: TMemVector): Boolean; virtual;
// list assigning
procedure Assign(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False); overload; virtual;
procedure Assign(Vector: TMemVector; ManagedCopy: Boolean = False); overload; virtual;
procedure Append(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False); overload; virtual;
procedure Append(Vector: TMemVector; ManagedCopy: Boolean = False); overload; virtual;
// streaming
{
Write* methods write only the vector data, whereas Save* methods first
write item count and then the data.
NOTE - count is saved as a 32bit signed integer with little endianness.
When calling Read* method, current count (property Count) of items is read.
When Load* is called, the count is read first, the vector is reallocated to
that count and then the data are read.
}
procedure WriteToStream(Stream: TStream); virtual;
procedure ReadFromStream(Stream: TStream); virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure WriteToFile(const FileName: String); virtual;
procedure ReadFromFile(const FileName: String); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
// properties
property ItemSize: TMemSize read fItemSize;
property OwnsMemory: Boolean read fOwnsMemory write fOwnsMemory;
property Memory: Pointer read fMemory;
property Size: TMemSize read GetSize;
property AllocatedSize: TMemSize read GetAllocatedSize;
property Pointers[Index: Integer]: Pointer read GetItemPtr;
property OnChange: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
property OnChangeEvent: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
property OnChangeCallback: TNotifyCallback read fOnChangeCallback write fOnChangeCallback;
end;
{===============================================================================
--------------------------------------------------------------------------------
TIntegerVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TIntegerVector - class declaration
===============================================================================}
type
TIntegerVector = class(TMemVector)
protected
Function GetItem(Index: Integer): Integer; virtual;
procedure SetItem(Index: Integer; Value: Integer); virtual;
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
procedure ItemWrite(Item: Pointer; Stream: TStream); override;
procedure ItemRead(Item: Pointer; Stream: TStream); override;
public
constructor Create; overload;
constructor Create(Memory: Pointer; Count: Integer); overload;
Function First: Integer; reintroduce;
Function Last: Integer; reintroduce;
Function IndexOf(Item: Integer): Integer; reintroduce;
Function Find(Item: Integer; out Index: Integer): Boolean; reintroduce;
Function Add(Item: Integer): Integer; reintroduce;
procedure Insert(Index: Integer; Item: Integer); reintroduce;
Function Remove(Item: Integer): Integer; reintroduce;
Function Extract(Item: Integer): Integer; reintroduce;
property Items[Index: Integer]: Integer read GetItem write SetItem; default;
end;
implementation
uses
StrRect, ListSorters, BinaryStreamingLite;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TMemVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMemVector - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TMemVector - protected methods
-------------------------------------------------------------------------------}
Function TMemVector.GetItemPtr(Index: Integer): Pointer;
begin
If CheckIndexAndRaise(Index,'GetItemPtr') then
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Result := Pointer(PtrUInt(fMemory) + PtrUInt(TMemSize(Index) * fItemSize))
else
Result := nil;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TMemVector.SetItemPtr(Index: Integer; Value: Pointer);
var
ItemPtr: Pointer;
begin
If CheckIndexAndRaise(Index,'SetItemPtr') then
begin
ItemPtr := GetItemPtr(Index);
System.Move(ItemPtr^,fTempItem^,fItemSize);
System.Move(Value^,ItemPtr^,fItemSize);
If not ItemEquals(fTempItem,Value) then
DoChange;
end;
end;
//------------------------------------------------------------------------------
Function TMemVector.GetSize: TMemSize;
begin
Result := TMemSize(fCount) * fItemSize;
end;
//------------------------------------------------------------------------------
Function TMemVector.GetAllocatedSize: TMemSize;
begin
Result := TMemSize(fCapacity) * fItemSize;
end;
//------------------------------------------------------------------------------
Function TmemVector.GetCapacity: Integer;
begin
Result := fCapacity;
end;
//------------------------------------------------------------------------------
procedure TMemVector.SetCapacity(Value: Integer);
var
i: Integer;
begin
If fOwnsMemory then
begin
If (Value <> fCapacity) and (Value >= 0) then
begin
If (Value < fCount) and not fLoading then
For i := Value to HighIndex do
ItemFinal(GetItemPtr(i));
If fCount <= 0 then
begin
// there is no item, so we do not need to copy existing data
FreeMem(fMemory,TMemSize(fCapacity) * fItemSize);
fMemory := AllocMem(TMemSize(Value) * fItemSize);
end
else ReallocMem(fMemory,TMemSize(Value) * fItemSize);
fCapacity := Value;
If Value < fCount then
begin
fCount := Value;
DoChange;
end;
end;
end
else raise EMVForeignMemory.Create('TMemVector.SetCapacity: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
Function TmemVector.GetCount: Integer;
begin
Result := fCount;
end;
//------------------------------------------------------------------------------
procedure TMemVector.SetCount(Value: Integer);
var
OldCount: Integer;
i: Integer;
begin
If fOwnsMemory then
begin
If (Value <> fCount) and (Value >= 0) then
begin
BeginUpdate;
try
If Value > fCapacity then
SetCapacity(Value);
If Value > fCount then
begin
OldCount := fCount;
fCount := Value;
If not fLoading then
For i := OldCount to HighIndex do
ItemInit(GetItemPtr(i));
end
else
begin
If not fLoading then
For i := HighIndex downto Value do
ItemFinal(GetItemPtr(i));
fCount := Value;
end;
DoChange;
finally
EndUpdate;
end;
end;
end
else raise EMVForeignMemory.Create('TMemVector.SetCount: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.ItemInit(Item: Pointer);
begin
FillChar(Item^,fItemSize,0);
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TMemVector.ItemFinal(Item: Pointer);
begin
// nothing to do here
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TMemVector.ItemCopy(SrcItem,DstItem: Pointer);
begin
System.Move(SrcItem^,DstItem^,fItemSize);
end;
//------------------------------------------------------------------------------
Function TMemVector.ItemCompare(Item1,Item2: Pointer): Integer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
If PtrUInt(Item1) < PtrUInt(Item2) then
Result := -1
else If PtrUInt(Item1) > PtrUInt(Item2) then
Result := +1
else
Result := 0;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
Function TMemVector.ItemEquals(Item1,Item2: Pointer): Boolean;
begin
Result := ItemCompare(Item1,Item2) = 0;
end;
//------------------------------------------------------------------------------
procedure TMemVector.ItemWrite(Item: Pointer; Stream: TStream);
begin
Stream.WriteBuffer(Item^,fItemSize);
end;
//------------------------------------------------------------------------------
procedure TMemVector.ItemRead(Item: Pointer; Stream: TStream);
begin
Stream.ReadBuffer(Item^,fItemSize);
end;
//------------------------------------------------------------------------------
Function TMemVector.CheckIndexAndRaise(Index: Integer; CallingMethod: String = 'CheckIndexAndRaise'): Boolean;
begin
Result := CheckIndex(Index);
If not Result then
raise EMVIndexOutOfBounds.CreateFmt('TMemVector.%s: Index (%d) out of bounds.',[CallingMethod,Index]);
end;
//------------------------------------------------------------------------------
Function TMemVector.GetNextItemPtr(ItemPtr: Pointer): Pointer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Result := Pointer(PtrUInt(ItemPtr) + PtrUInt(fItemSize));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
Function TMemVector.CompareItems(Index1,Index2: Integer): Integer;
begin
Result := ItemCompare(GetItemPtr(Index1),GetItemPtr(Index2));
end;
//------------------------------------------------------------------------------
procedure TMemVector.FinalizeAllItems;
var
i: Integer;
begin
For i := LowIndex to HighIndex do
ItemFinal(GetItemPtr(i));
end;
//------------------------------------------------------------------------------
procedure TMemVector.DoChange;
begin
fChanged := True;
If (fUpdateCounter <= 0) then
begin
If Assigned(fOnChangeEvent) then
fOnChangeEvent(Self)
else If Assigned(fOnChangeCallback) then
fOnChangeCallback(Self);
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.ReadFromStreamInternal(Stream: TStream);
var
i: Integer;
begin
For i := LowIndex to HighIndex do
ItemRead(GetItemPtr(i),Stream);
DoChange;
end;
{-------------------------------------------------------------------------------
TMemVector - public methods
-------------------------------------------------------------------------------}
constructor TMemVector.Create(ItemSize: TMemSize);
begin
inherited Create;
If ItemSize > 0 then
begin
fItemSize := ItemSize;
fOwnsMemory := True;
fMemory := nil;
fCapacity := 0;
fCount := 0;
fUpdateCounter := 0;
fChanged := False;
fOnChangeEvent := nil;
fOnChangeCallback := nil;
GetMem(fTempItem,fItemSize);
fLoading := False;
end
else raise EMVInvalidValue.CreateFmt('TMemVector.Create: Invalid item size (%d).',[ItemSize]);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMemVector.Create(Memory: Pointer; Count: Integer; ItemSize: TMemSize);
begin
Create(ItemSize);
If Assigned(Memory) then
begin
If Count >= 0 then
begin
fOwnsMemory := False;
fMemory := Memory;
fCapacity := Count;
fCount := Count;
end
else raise EMVInvalidValue.CreateFmt('TMemVector.Create: Invalid item count (%d).',[Count]);
end
else raise EMVInvalidValue.Create('TMemVector.Create: Nil memory not allowed.');
end;
//------------------------------------------------------------------------------
destructor TMemVector.Destroy;
begin
FinalizeAllItems;
FreeMem(fTempItem,fItemSize);
If fOwnsMemory then
FreeMem(fMemory,TMemSize(fCapacity) * fItemSize);
inherited;
end;
//------------------------------------------------------------------------------
procedure TMemVector.BeginUpdate;
begin
If fUpdateCounter <= 0 then
fChanged := False;
Inc(fUpdateCounter);
end;
//------------------------------------------------------------------------------
Function TMemVector.EndUpdate: Integer;
begin
Dec(fUpdateCounter);
If fUpdateCounter <= 0 then
begin
fUpdateCounter := 0;
If fChanged then
DoChange;
fChanged := False;
end;
Result := fUpdateCounter;
end;
//------------------------------------------------------------------------------
Function TMemVector.LowIndex: Integer;
begin
Result := 0;
end;
//------------------------------------------------------------------------------
Function TMemVector.HighIndex: Integer;
begin
Result := Pred(fCount);
end;
//------------------------------------------------------------------------------
Function TMemVector.First: Pointer;
begin
Result := GetItemPtr(LowIndex);
end;
//------------------------------------------------------------------------------
Function TMemVector.Last: Pointer;
begin
Result := GetItemPtr(HighIndex);
end;
//------------------------------------------------------------------------------
Function TMemVector.IndexOf(Item: Pointer): Integer;
var
i: Integer;
begin
Result := -1;
For i := LowIndex to HighIndex do
If ItemEquals(Item,GetItemPtr(i)) then
begin
Result := i;
Exit;
end;
end;
//------------------------------------------------------------------------------
Function TMemVector.Find(Item: Pointer; out Index: Integer): Boolean;
begin
Index := IndexOf(Item);
Result := CheckIndex(Index);
end;
//------------------------------------------------------------------------------
Function TMemVector.Add(Item: Pointer): Integer;
begin
If fOwnsMemory then
begin
Grow;
Result := fCount;
Inc(fCount);
System.Move(Item^,GetItemPtr(Result)^,fItemSize);
DoChange;
end
else raise EMVForeignMemory.Create('TMemVector.Add: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Insert(Index: Integer; Item: Pointer);
var
InsertPtr: Pointer;
begin
If fOwnsMemory then
begin
If CheckIndex(Index) then
begin
Grow;
InsertPtr := GetItemPtr(Index);
System.Move(InsertPtr^,GetNextItemPtr(InsertPtr)^,fItemSize * TMemSize(fCount - Index));
System.Move(Item^,InsertPtr^,fItemSize);
Inc(fCount);
DoChange;
end
else If Index = fCount then
Add(Item)
else
raise EMVIndexOutOfBounds.CreateFmt('TMemVector.Insert: Index (%d) out of bounds.',[Index]);
end
else raise EMVForeignMemory.Create('TMemVector.Insert: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Move(SrcIndex,DstIndex: Integer);
var
SrcPtr: Pointer;
DstPtr: Pointer;
begin
If CheckIndexAndRaise(SrcIndex,'Move') and CheckIndexAndRaise(DstIndex,'Move') then
If SrcIndex <> DstIndex then
begin
SrcPtr := GetItemPtr(SrcIndex);
DstPtr := GetItemPtr(DstIndex);
System.Move(SrcPtr^,fTempItem^,fItemSize);
If SrcIndex < DstIndex then
System.Move(GetNextItemPtr(SrcPtr)^,SrcPtr^,fItemSize * TMemSize(DstIndex - SrcIndex))
else
System.Move(DstPtr^,GetNextItemPtr(DstPtr)^,fItemSize * TMemSize(SrcIndex - DstIndex));
System.Move(fTempItem^,DstPtr^,fItemSize);
DoChange;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Exchange(Index1,Index2: Integer);
var
Idx1Ptr: Pointer;
Idx2Ptr: Pointer;
begin
If CheckIndexAndRaise(Index1,'Exchange') and CheckIndexAndRaise(Index2,'Exchange') then
If Index1 <> Index2 then
begin
Idx1Ptr := GetItemPtr(Index1);
Idx2Ptr := GetItemPtr(Index2);
System.Move(Idx1Ptr^,fTempItem^,fItemSize);
System.Move(Idx2Ptr^,Idx1Ptr^,fItemSize);
System.Move(fTempItem^,Idx2Ptr^,fItemSize);
DoChange;
end;
end;
//------------------------------------------------------------------------------
Function TMemVector.Extract(Item: Pointer): Pointer;
var
Index: Integer;
ItemPtr: Pointer;
begin
If fOwnsMemory then
begin
Index := IndexOf(Item);
If CheckIndex(Index) then
begin
ItemPtr := GetItemPtr(Index);
// move the item to temp so it is valid after its removal from the vector
System.Move(ItemPtr^,fTempItem^,fItemSize);
Result := fTempItem;
// delete the item
If Index < HighIndex then
System.Move(GetNextItemPtr(ItemPtr)^,ItemPtr^,fItemSize * TMemSize(Pred(fCount - Index)));
Dec(fCount);
Shrink;
DoChange;
end
else Result := nil;
end
else raise EMVForeignMemory.Create('TMemVector.Extract: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
Function TMemVector.Remove(Item: Pointer): Integer;
begin
If fOwnsMemory then
begin
Result := IndexOf(Item);
If CheckIndex(Result) then
Delete(Result);
end
else raise EMVForeignMemory.Create('TMemVector.Remove: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Delete(Index: Integer);
var
DeletePtr: Pointer;
begin
If fOwnsMemory then
begin
If CheckIndexAndRaise(Index,'Delete') then
begin
DeletePtr := GetItemPtr(Index);
ItemFinal(DeletePtr);
If Index < HighIndex then
System.Move(GetNextItemPtr(DeletePtr)^,DeletePtr^,fItemSize * TMemSize(Pred(fCount - Index)));
Dec(fCount);
Shrink;
DoChange;
end;
end
else raise EMVForeignMemory.Create('TMemVector.Delete: Operation not alloved on foreign memory.');
end;
//------------------------------------------------------------------------------