-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
BitVector.pas
1917 lines (1706 loc) · 59.7 KB
/
BitVector.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/.
-------------------------------------------------------------------------------}
{===============================================================================
BitVector
Provides classes that can be used to access individual bits of memory in
a list-like manner.
Version 1.4.3 (2024-04-14)
Last change 2024-04-14
©2015-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.BitVector
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
BitOps - github.com/TheLazyTomcat/Lib.BitOps
StrRect - github.com/TheLazyTomcat/Lib.StrRect
Library AuxExceptions is required only when rebasing local exception classes
(see symbol BitVector_UseAuxExceptions for details).
BinaryStreamingLite can be replaced by full BinaryStreaming.
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit BitVector;
{
BitVector_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
BitVector_UseAuxExceptions to achieve this.
}
{$IF Defined(BitVector_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH DuplicateLocals+}
{$MODESWITCH ClassicProcVars+}
{$INLINE ON}
{$DEFINE CanInline}
{$ELSE}
{$IF CompilerVersion >= 17} // Delphi 2005+
{$DEFINE CanInline}
{$ELSE}
{$UNDEF CanInline}
{$IFEND}
{$ENDIF}
{$H+}
interface
uses
SysUtils, Classes,
AuxTypes, AuxClasses{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
EBVException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
EBVIndexOutOfBounds = class(EBVException);
EBVNonReallocatableMemory = class(EBVException);
EBVInvalidValue = class(EBVException);
{===============================================================================
--------------------------------------------------------------------------------
TBitVector
--------------------------------------------------------------------------------
===============================================================================}
type
TBVOperations = record
BoolOperation: Function(A,B: Boolean): Boolean;
ByteOperation: Function(A,B: Byte): Byte;
WordOperation: Function(A,B: NativeUInt): NativeUInt;
end;
{===============================================================================
TBitVector - class declaration
===============================================================================}
type
TBitVector = class(TCustomListObject)
protected
fConstructorSetup: Boolean; // to allow SetCount and SetCapacity in static vectors
fOwnsMemory: Boolean;
fMemSize: TMemSize;
fMemory: Pointer;
fCount: Integer;
fPopCount: Integer;
fStatic: Boolean; // when true, the memory cannot be reallocated, but can be written into
fChangeCounter: Integer;
fChanged: Boolean;
fOnChangeEvent: TNotifyEvent;
fOnChangeCallback: TNotifyCallback;
// following four methods do not check index for validity
Function GetBytePtrBitIdx(BitIndex: Integer): PByte; virtual;
Function GetBytePtrByteIdx(ByteIndex: Integer): PByte; virtual;
Function GetBit_LL(Index: Integer): Boolean; virtual;
Function SetBit_LL(Index: Integer; Value: Boolean): Boolean; virtual; // returns old value
Function GetBit(Index: Integer): Boolean; virtual;
procedure SetBit(Index: Integer; Value: Boolean); virtual;
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
Function MemoryCanBeReallocated: Boolean; virtual;
procedure ShiftDown(Idx1,Idx2: Integer); virtual;
procedure ShiftUp(Idx1,Idx2: Integer); virtual;
procedure ScanForPopCount; virtual;
procedure CombineInternal(Memory: Pointer; Count: Integer; Operations: TBVOperations); virtual;
procedure Initialize; virtual;
procedure Finalize; virtual;
procedure DoChange; virtual;
public
constructor Create(Memory: Pointer; Count: Integer); overload; virtual;
constructor Create(InitialCount: Integer = 0; InitialValue: Boolean = False); overload; virtual;
destructor Destroy; override;
procedure BeginChanging;
Function EndChanging: Integer;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function First: Boolean; virtual;
Function Last: Boolean; virtual;
Function Add(Value: Boolean): Integer; virtual;
procedure Insert(Index: Integer; Value: Boolean); virtual;
procedure Exchange(Index1, Index2: Integer); virtual;
procedure Move(SrcIdx, DstIdx: Integer); virtual;
procedure Delete(Index: Integer); virtual;
procedure Clear; virtual;
procedure Assign(Memory: Pointer; Count: Integer); overload; virtual;
procedure Assign(Vector: TBitVector); overload; virtual;
procedure Append(Memory: Pointer; Count: Integer); overload; virtual;
procedure Append(Vector: TBitVector); overload; virtual;
procedure Put(Index: Integer; Memory: Pointer; Count: Integer); overload; virtual;
procedure Put(Index: Integer; Vector: TBitVector); overload; virtual;
procedure Fill(FromIdx,ToIdx: Integer; Value: Boolean); overload; virtual;
procedure Fill(Value: Boolean); overload; virtual;
procedure Complement(FromIdx,ToIdx: Integer); overload; virtual;
procedure Complement; overload; virtual;
procedure Reverse; virtual;
procedure Combine(Memory: Pointer; Count: Integer; Operations: TBVOperations); overload; virtual;
procedure Combine(Vector: TBitVector; Operations: TBVOperations); overload; virtual;
procedure CombineAND(Memory: Pointer; Count: Integer); overload; virtual;
procedure CombineAND(Vector: TBitVector); overload; virtual;
procedure CombineOR(Memory: Pointer; Count: Integer); overload; virtual;
procedure CombineOR(Vector: TBitVector); overload; virtual;
procedure CombineXOR(Memory: Pointer; Count: Integer); overload; virtual;
procedure CombineXOR(Vector: TBitVector); overload; virtual;
Function IsEmpty: Boolean; virtual;
Function IsFull: Boolean; virtual;
Function IsEqual(Vector: TBitVector): Boolean; virtual;
Function FirstSet: Integer; virtual;
Function FirstClean: Integer; virtual;
Function LastSet: Integer; virtual;
Function LastClean: Integer; virtual;
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;
property Bits[Index: Integer]: Boolean read GetBit write SetBit; default;
property OwnsMemory: Boolean read fOwnsMemory;
property MemorySize: TMemSize read fMemSize;
property Memory: Pointer read fMemory;
property PopCount: Integer read fPopCount;
property Static: Boolean read fStatic;
property OnChange: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
property OnChangeEvent: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
property OnChangeCallback: TNotifyCallback read fOnChangeCallback write fOnChangeCallback;
end;
{===============================================================================
--------------------------------------------------------------------------------
TBitVectorStatic
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TBitVectorStatic - class declaration
===============================================================================}
type
TBitVectorStatic = class(TBitVector)
protected
procedure Initialize; override;
end;
{===============================================================================
--------------------------------------------------------------------------------
TBitVectorStatic32
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TBitVectorStatic32 - class declaration
===============================================================================}
type
TBitVectorStatic32 = class(TBitVectorStatic)
public
constructor Create(Memory: Pointer; Count: Integer); overload; override;
constructor Create(InitialCount: Integer = 0; InitialValue: Boolean = False); overload; override;
Function FirstSet: Integer; override;
Function FirstClean: Integer; override;
Function LastSet: Integer; override;
Function LastClean: Integer; override;
end;
implementation
uses
Math,
BitOps, StrRect, BinaryStreamingLite;
{===============================================================================
--------------------------------------------------------------------------------
TBitVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TBitVector - auxiliaty types, constants and functions
===============================================================================}
const
BV_ALLOCDELTA_BITS = 128; // allocation granularity
BV_ALLOCDELTA_BYTES = BV_ALLOCDELTA_BITS div 8;
{$IF SizeOf(NativeUInt) = 8}
BV_NATINT_BYTES = 8;
BV_NATINT_BITS = 64;
BV_NATINT_MAX = NativeUInt($FFFFFFFFFFFFFFFF);
{$ELSEIF SizeOf(NativeUInt) = 4}
BV_NATINT_BYTES = 4;
BV_NATINT_BITS = 32;
BV_NATINT_MAX = NativeUInt($FFFFFFFF);
{$ELSE}
{$MESSAGE FATAL 'Unsupported architecture.'}
{$IFEND}
//==============================================================================
Function BoolFillValue(Value: Boolean): NativeUInt;
begin
If Value then
Result := BV_NATINT_MAX
else
Result := 0;
end;
//------------------------------------------------------------------------------
Function BoolOperation_AND(A,B: Boolean): Boolean;
begin
Result := A and B;
end;
//------------------------------------------------------------------------------
Function BoolOperation_OR(A,B: Boolean): Boolean;
begin
Result := A or B;
end;
//------------------------------------------------------------------------------
Function BoolOperation_XOR(A,B: Boolean): Boolean;
begin
Result := A xor B;
end;
//------------------------------------------------------------------------------
Function ByteOperation_AND(A,B: Byte): Byte;
begin
Result := A and B;
end;
//------------------------------------------------------------------------------
Function ByteOperation_OR(A,B: Byte): Byte;
begin
Result := A or B;
end;
//------------------------------------------------------------------------------
Function ByteOperation_XOR(A,B: Byte): Byte;
begin
Result := A xor B;
end;
//------------------------------------------------------------------------------
Function WordOperation_AND(A,B: NativeUInt): NativeUInt;
begin
Result := A and B;
end;
//------------------------------------------------------------------------------
Function WordOperation_OR(A,B: NativeUInt): NativeUInt;
begin
Result := A or B;
end;
//------------------------------------------------------------------------------
Function WordOperation_XOR(A,B: NativeUInt): NativeUInt;
begin
Result := A xor B;
end;
//==============================================================================
const
AndOps: TBVOperations = (
BoolOperation: BoolOperation_AND;
ByteOperation: ByteOperation_AND;
WordOperation: WordOperation_AND);
OrOps: TBVOperations = (
BoolOperation: BoolOperation_OR;
ByteOperation: ByteOperation_OR;
WordOperation: WordOperation_OR);
XorOps: TBVOperations = (
BoolOperation: BoolOperation_XOR;
ByteOperation: ByteOperation_XOR;
WordOperation: WordOperation_XOR);
//==============================================================================
// endianness correction
Function EndCor32(Value: UInt32): UInt32; {$IFDEF CanInline} inline;{$ENDIF}
begin
{$IFDEF ENDIAN_BIG}
Result := EndianSwap(Value);
{$ELSE}
Result := Value;
{$ENDIF}
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function EndCor(Value: NativeUInt): NativeUInt; {$IFDEF CanInline} inline;{$ENDIF}
begin
{$IFDEF ENDIAN_BIG}
Result := EndianSwap(Value);
{$ELSE}
Result := Value;
{$ENDIF}
end;
{===============================================================================
TBitVector - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TBitVector - protected methods
-------------------------------------------------------------------------------}
Function TBitVector.GetBytePtrBitIdx(BitIndex: Integer): PByte;
begin
Result := PByte(PtrAdvance(fMemory,PtrInt(BitIndex shr 3)));
end;
//------------------------------------------------------------------------------
Function TBitVector.GetBytePtrByteIdx(ByteIndex: Integer): PByte;
begin
Result := PByte(PtrAdvance(fMemory,PtrInt(ByteIndex)));
end;
//------------------------------------------------------------------------------
Function TBitVector.GetBit_LL(Index: Integer): Boolean;
begin
Result := BT(GetBytePtrBitIdx(Index)^,Index and 7);
end;
//------------------------------------------------------------------------------
Function TBitVector.SetBit_LL(Index: Integer; Value: Boolean): Boolean;
begin
Result := BitSetTo(GetBytePtrBitIdx(Index)^,Index and 7,Value);
end;
//------------------------------------------------------------------------------
Function TBitVector.GetBit(Index: Integer): Boolean;
begin
If CheckIndex(Index) then
Result := GetBit_LL(Index)
else
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.GetBit: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TBitVector.SetBit(Index: Integer; Value: Boolean);
begin
If CheckIndex(Index) then
begin
If Value <> SetBit_LL(Index,Value) then
begin
If Value then
Inc(fPopCount)
else
Dec(fPopCount);
DoChange;
end;
end
else raise EBVIndexOutOfBounds.CreateFmt('TBitVector.SetBit: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TBitVector.GetCapacity: Integer;
begin
Result := Integer(fMemSize shl 3);
end;
//------------------------------------------------------------------------------
procedure TBitVector.SetCapacity(Value: Integer);
var
NewMemSize: TMemSize;
begin
If MemoryCanBeReallocated then
begin
If Value >= 0 then
begin
NewMemSize := Ceil(Value / BV_ALLOCDELTA_BITS) * BV_ALLOCDELTA_BYTES;
If fMemSize <> NewMemSize then
begin
ReallocMem(fMemory,NewMemSize);
fMemSize := NewMemSize;
// adjust count if capacity gets below it
If Capacity < fCount then
begin
fCount := Capacity;
ScanForPopCount;
DoChange;
end;
end;
end
else raise EBVInvalidValue.CreateFmt('TBitVector.SetCapacity: Invalid capacity (%d).',[Value]);
end
else raise EBVNonReallocatableMemory.Create('TBitVector.SetCapacity: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
Function TBitVector.GetCount: Integer;
begin
Result := fCount;
end;
//------------------------------------------------------------------------------
procedure TBitVector.SetCount(Value: Integer);
var
i: Integer;
begin
If MemoryCanBeReallocated then
begin
If Value >= 0 then
begin
If Value <> fCount then
begin
BeginChanging;
try
If Value > Capacity then
SetCapacity(Value); // alloc new capacity
If Value > fCount then
begin
// add new bits, and reset them (pop count is not changed)
// partial byte...
If (fCount and 7) <> 0 then
SetBitsValue(GetBytePtrBitIdx(Pred(fCount))^,0,fCount and 7,7,False);
// full bytes...
For i := ((fCount + 7) shr 3) to (Pred(Value) shr 3) do
GetBytePtrByteIdx(i)^ := 0;
fCount := Value;
end
else
begin
// remove existing bits
fCount := Value;
ScanForPopCount;
end;
DoChange;
finally
EndChanging;
end;
end;
end
else raise EBVInvalidValue.CreateFmt('TBitVector.SetCount: Invalid count (%d).',[Value]);;
end
else raise EBVNonReallocatableMemory.Create('TBitVector.SetCount: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
Function TBitVector.MemoryCanBeReallocated: Boolean;
begin
Result := (fOwnsMemory and not fStatic) or fConstructorSetup;
end;
//------------------------------------------------------------------------------
procedure TBitVector.ShiftDown(Idx1,Idx2: Integer);
var
ByteCount: Integer;
Carry: Boolean;
MovingPtr: Pointer;
begin
If Idx2 > Idx1 then
begin
If (Idx1 shr 3) <> (Idx2 shr 3) then
begin
// shift is done across at least one byte boundary
ByteCount := Pred((Idx2 shr 3) - (Idx1 shr 3));
MovingPtr := GetBytePtrBitIdx(Idx2);
// shift last byte and preserve shifted-out bit
Carry := GetBit_LL(Idx2 and not 7); // bit 0 of last byte
SetBitsValue(PByte(MovingPtr)^,PByte(MovingPtr)^ shr 1,0,Idx2 and 7,False);
// shift native words
while ByteCount >= BV_NATINT_BYTES do
begin
Dec(PNativeUInt(MovingPtr));
Dec(ByteCount,BV_NATINT_BYTES);
PNativeUInt(MovingPtr)^ := EndCor(RCRCarry(EndCor(PNativeUInt(MovingPtr)^),1,Carry));
end;
// shift whole bytes
while ByteCount > 0 do
begin
Dec(PByte(MovingPtr));
Dec(ByteCount);
RCRValueCarry(PByte(MovingPtr)^,1,Carry);
end;
// shift first byte and store carry
Dec(PByte(MovingPtr));
SetBitsValue(PByte(MovingPtr)^,PByte(MovingPtr)^ shr 1,Idx1 and 7,7,False);
SetBit_LL(Idx1 or 7,Carry);
end
// shift is done within a single byte
else SetBitsValue(GetBytePtrBitIdx(Idx1)^,GetBytePtrBitIdx(Idx1)^ shr 1,Idx1 and 7,Idx2 and 7,False);
end
else raise EBVInvalidValue.CreateFmt('TBitVector.ShiftDown: Invalid indices (%d, %d).',[Idx1,Idx2]);
end;
//------------------------------------------------------------------------------
procedure TBitVector.ShiftUp(Idx1,Idx2: Integer);
var
ByteCount: Integer;
Carry: Boolean;
MovingPtr: Pointer;
begin
If Idx2 > Idx1 then
begin
If (Idx1 shr 3) <> (Idx2 shr 3) then
begin
// shift is done across at least one byte boundary
ByteCount := Pred((Idx2 shr 3) - (Idx1 shr 3));
MovingPtr := GetBytePtrBitIdx(Idx1);
// shift first byte and preserve shifted-out bit
Carry := GetBit_LL(Idx1 or 7);
SetBitsValue(PByte(MovingPtr)^,Byte(PByte(MovingPtr)^ shl 1),Idx1 and 7,7,False);
Inc(PByte(MovingPtr));
// shift native words
while ByteCount >= BV_NATINT_BYTES do
begin
PNativeUInt(MovingPtr)^ := EndCor(RCLCarry(EndCor(PNativeUInt(MovingPtr)^),1,Carry));
Inc(PNativeUInt(MovingPtr));
Dec(ByteCount,BV_NATINT_BYTES);
end;
// shift whole bytes
while ByteCount > 0 do
begin
RCLValueCarry(PByte(MovingPtr)^,1,Carry);
Inc(PByte(MovingPtr));
Dec(ByteCount);
end;
// shift last byte and store carry
SetBitsValue(PByte(MovingPtr)^,Byte(PByte(MovingPtr)^ shl 1),0,Idx2 and 7,False);
SetBit_LL(Idx2 and not 7,Carry);
end
// shift is done inside of one byte
else SetBitsValue(GetBytePtrBitIdx(Idx1)^,Byte(GetBytePtrBitIdx(Idx1)^ shl 1),Idx1 and 7,Idx2 and 7,False);
end
else raise EBVInvalidValue.CreateFmt('TBitVector.ShiftUp: Invalid indices (%d, %d).',[Idx1,Idx2]);
end;
//------------------------------------------------------------------------------
procedure TBitVector.ScanForPopCount;
var
BitCount: Integer;
MovingPtr: Pointer;
begin
fPopCount := 0;
BitCount := fCount;
If BitCount > 0 then
begin
MovingPtr := fMemory;
// full natives...
while BitCount >= BV_NATINT_BITS do
begin
Inc(fPopCount,BitOps.PopCount(PNativeUInt(MovingPtr)^));
Dec(BitCount,BV_NATINT_BITS);
Inc(PNativeUInt(MovingPtr));
end;
// full bytes...
while BitCount >= 8 do
begin
Inc(fPopCount,BitOps.PopCount(PByte(MovingPtr)^));
Dec(BitCount,8);
Inc(PByte(MovingPtr));
end;
// partial byte...
If BitCount > 0 then
Inc(fPopCount,BitOps.PopCount(Byte(PByte(MovingPtr)^ and ($FF shr (8 - (BitCount and 7))))));
end;
end;
//------------------------------------------------------------------------------
procedure TBitVector.CombineInternal(Memory: Pointer; Count: Integer; Operations: TBVOperations);
var
MovingPtr: Pointer;
TempA: Byte;
TempB: Byte;
TempR: Byte;
i: Integer;
begin
If Count > 0 then
begin
If Count > fCount then
Count := fCount;
MovingPtr := fMemory;
// combine whole natives
while Count >= BV_NATINT_BITS do
begin
PNativeUInt(MovingPtr)^ := Operations.WordOperation(PNativeUInt(MovingPtr)^,PNativeUInt(Memory)^);
Inc(PNativeUInt(Memory));
Inc(PNativeUInt(MovingPtr));
Dec(Count,BV_NATINT_BITS);
end;
// combine whole bytes
while Count >= 8 do
begin
PByte(MovingPtr)^ := Operations.ByteOperation(PByte(MovingPtr)^,PByte(Memory)^);
Inc(PByte(Memory));
Inc(PByte(MovingPtr));
Dec(Count,8);
end;
// combine remaining bits
If Count > 0 then
begin
TempA := PByte(MovingPtr)^;
TempB := PByte(Memory)^;
TempR := 0;
For i := 0 to Pred(Count) do
TempR := TempR or Byte(IfThen(Operations.BoolOperation(
((TempA shr i) and 1) <> 0,((TempB shr i) and 1) <> 0),1,0) shl i);
SetBitsValue(PByte(MovingPtr)^,TempR,0,Pred(Count and 7),False);
end;
ScanForPopCount;
DoChange;
end;
end;
//------------------------------------------------------------------------------
procedure TBitVector.Initialize;
begin
fConstructorSetup := False;
fOwnsMemory := True;
fMemSize := 0;
fMemory := nil;
fCount := 0;
fPopCount := 0;
fStatic := False;
fChangeCounter := 0;
fChanged := False;
fOnChangeEvent := nil;
fOnChangeCallback := nil;
end;
//------------------------------------------------------------------------------
procedure TBitVector.Finalize;
begin
If fOwnsMemory then
FreeMem(fMemory,fMemSize);
end;
//------------------------------------------------------------------------------
procedure TBitVector.DoChange;
begin
fChanged := True;
If (fChangeCounter <= 0) then
begin
If Assigned(fOnChangeEvent) then
fOnChangeEvent(Self)
else If Assigned(fOnChangeCallback) then
fOnChangeCallback(Self);
end;
end;
{-------------------------------------------------------------------------------
TBitVector - public methods
-------------------------------------------------------------------------------}
constructor TBitVector.Create(Memory: Pointer; Count: Integer);
begin
inherited Create;
Initialize;
fOwnsMemory := False;
fMemSize := (Count + 7) shr 3;
fMemory := Memory;
fCount := Count;
ScanForPopCount;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
constructor TBitVector.Create(InitialCount: Integer = 0; InitialValue: Boolean = False);
begin
inherited Create;
Initialize;
fOwnsMemory := True;
fConstructorSetup := True;
try
SetCount(InitialCount); // sets capacity and therefore also fMemSize and fMemory
finally
fConstructorSetup := False;
end;
{
No need to call Fill when InitialValue is false since the memory was
implicitly cleared in a call to SetCount.
}
If InitialValue then
Fill(True);
end;
//------------------------------------------------------------------------------
destructor TBitVector.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
procedure TBitVector.BeginChanging;
begin
If fChangeCounter <= 0 then
fChanged := False;
Inc(fChangeCounter);
end;
//------------------------------------------------------------------------------
Function TBitVector.EndChanging: Integer;
begin
Dec(fChangeCounter);
If fChangeCounter <= 0 then
begin
fChangeCounter := 0;
If fChanged then
DoChange;
end;
Result := fChangeCounter;
end;
//------------------------------------------------------------------------------
Function TBitVector.LowIndex: Integer;
begin
Result := 0;
end;
//------------------------------------------------------------------------------
Function TBitVector.HighIndex: Integer;
begin
Result := Pred(fCount);
end;
//------------------------------------------------------------------------------
Function TBitVector.First: Boolean;
begin
Result := GetBit(LowIndex);
end;
//------------------------------------------------------------------------------
Function TBitVector.Last: Boolean;
begin
Result := GetBit(HighIndex);
end;
//------------------------------------------------------------------------------
Function TBitVector.Add(Value: Boolean): Integer;
begin
If MemoryCanBeReallocated then
begin
Grow;
Inc(fCount);
SetBit_LL(HighIndex,Value);
If Value then
Inc(fPopCount);
Result := HighIndex;
DoChange;
end
else raise EBVNonReallocatableMemory.Create('TBitVector.Add: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
procedure TBitVector.Insert(Index: Integer; Value: Boolean);
begin
If MemoryCanBeReallocated then
begin
If CheckIndex(Index) then
begin
Grow;
Inc(fCount); // must be here because of shifting
ShiftUp(Index,HighIndex);
SetBit_LL(Index,Value);
If Value then
Inc(fPopCount);
DoChange;
end
else If Index = fCount then
Add(Value)
else
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Insert: Index (%d) out of bounds.',[Index]);
end
else raise EBVNonReallocatableMemory.Create('TBitVector.Insert: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
procedure TBitVector.Exchange(Index1,Index2: Integer);
begin
If Index1 <> Index2 then
begin
If not CheckIndex(Index1) then
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Exchange: Index #1 (%d) out of bounds.',[Index1]);
If not CheckIndex(Index2) then
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Exchange: Index #2 (%d) out of bounds.',[Index2]);
SetBit_LL(Index2,SetBit_LL(Index1,GetBit_LL(Index2)));
DoChange;
end;
end;
//------------------------------------------------------------------------------
procedure TBitVector.Move(SrcIdx, DstIdx: Integer);
var
Temp: Boolean;
begin
If SrcIdx <> DstIdx then
begin
If not CheckIndex(SrcIdx) then
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Exchange: Source index (%d) out of bounds.',[SrcIdx]);
If not CheckIndex(DstIdx) then
raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Exchange: Destination index (%d) out of bounds.',[DstIdx]);
Temp := GetBit_LL(SrcIdx);
If SrcIdx < DstIdx then
ShiftDown(SrcIdx,DstIdx)
else
ShiftUp(DstIdx,SrcIdx);
SetBit_LL(DstIdx,Temp);
DoChange;
end;
end;
//------------------------------------------------------------------------------
procedure TBitVector.Delete(Index: Integer);
begin
If MemoryCanBeReallocated then
begin
If CheckIndex(Index) then
begin
If GetBit_LL(Index) then
Dec(fPopCount);
If Index < HighIndex then
ShiftDown(Index,HighIndex);
Dec(fCount);
Shrink;
DoChange;
end
else raise EBVIndexOutOfBounds.CreateFmt('TBitVector.Delete: Index (%d) out of bounds.',[Index]);
end
else raise EBVNonReallocatableMemory.Create('TBitVector.Delete: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
procedure TBitVector.Clear;
begin
If MemoryCanBeReallocated then
begin
fCount := 0;
fPopCount := 0;
Shrink;
DoChange;
end
else raise EBVNonReallocatableMemory.Create('TBitVector.Clear: Memory cannot be reallocated.');
end;
//------------------------------------------------------------------------------
procedure TBitVector.Assign(Memory: Pointer; Count: Integer);
begin
If MemoryCanBeReallocated or (Count = fCount) then
begin
BeginChanging;
try
If Count <> fCount then
SetCount(Count); // also sets fCount
// whole bytes
System.Move(Memory^,fMemory^,Count shr 3);
// remaining bits
If (Count and 7) <> 0 then
SetBitsValue(GetBytePtrByteIdx(Count shr 3)^,
PByte(PtrAdvance(Memory,PtrInt(Count shr 3)))^,
0,Pred(Count and 7),False);
ScanForPopCount;
DoChange;
finally
EndChanging;
end;
end
else raise EBVNonReallocatableMemory.Create('TBitVector.Assign: Memory cannot be reallocated.');
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TBitVector.Assign(Vector: TBitVector);
begin
Assign(Vector.Memory,Vector.Count);
end;
//------------------------------------------------------------------------------
procedure TBitVector.Append(Memory: Pointer; Count: Integer);
var
BytesCount: Integer;
RShift: Integer;
LShift: Integer;
MovingPtr: Pointer;
NextBytePtr: Pointer;
begin
If MemoryCanBeReallocated then
begin
If Count > 0 then