-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CRC32.pas
2187 lines (1829 loc) · 73.6 KB
/
CRC32.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/.
-------------------------------------------------------------------------------}
{===============================================================================
CRC-32 calculation
This unit provides classes that can be used to calculate CRC-32 value for
any provided data (buffers, streams, strings, files, ...).
Currently, it implements classes for CRC-32 used for axample in ZIP archives
(PKZIP, polynomial 0x104C11DB7, class TCRC32Hash) and CRC-32C (Castagnoli,
polynomial 0x11EDC6F41, class TCRC32CHash).
TCRC32CHash also supports acceleration trough CRC32 CPU instruction set
extension present on modern x86(-64) processors (symbol CRC32C_Accelerated
must be defined for this feature).
There is also a class for custom calculation (TCRC32CustomHash) that offers
an option to set arbitrary polynomial, intial value and other parameters.
Along with this class, an array containing several preset CRC-32 variants
is provided.
For the sake of backward compatibility, there is a set of standalone
functions that can be used. These functions are implemented above TCRC32Hash
class and therefore are calculating CRC-32 with a polynomial of 0x104C11DB7.
Version 1.7.3 (2023-04-14)
Last change 2024-05-02
©2011-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.CRC32
Dependencies:
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
HashBase - github.com/TheLazyTomcat/Lib.HashBase
* SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
SimpleCPUID is required only when neither PurePascal nor CRC32_PurePascal
symbol is defined and symbol CRC32C_Accelerated is defined.
Library SimpleCPUID might also be required as an indirect dependency.
Indirect dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
StrRect - github.com/TheLazyTomcat/Lib.StrRect
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit CRC32;
{
CRC32_PurePascal
If you want to compile this unit without ASM, don't want to or cannot define
PurePascal for the entire project and at the same time you don't want to or
cannot make changes to this unit, define this symbol for the entire project
and this unit will be compiled in PurePascal mode.
}
{$IFDEF CRC32_PurePascal}
{$DEFINE PurePascal}
{$ENDIF}
{$IF Defined(CPUX86_64) or Defined(CPUX64)}
{$DEFINE x64}
{$ELSEIF Defined(CPU386)}
{$DEFINE x86}
{$ELSE}
{$DEFINE PurePascal}
{$IFEND}
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}{$MODESWITCH CLASSICPROCVARS+}
{$INLINE ON}
{$DEFINE CanInline}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$IFNDEF PurePascal}
{$ASMMODE Intel}
{$ENDIF}
{$ELSE}
{$IF CompilerVersion >= 17} // Delphi 2005+
{$DEFINE CanInline}
{$ELSE}
{$UNDEF CanInline}
{$IFEND}
{$ENDIF}
{$H+}
{
CRC32C_Accelerated
When defined, and when symbol PurePascal is not defined, the CRC-32C (class
TCRC32CHash) is compiled with an ability of using hardware-accelerated
calculations via CRC32 instruction (part of SSE4.2 instruction set extension).
Defined by default.
To disable/undefine this symbol in a project without changing this library,
define project-wide symbol CRC32_CRC32C_Accelerated_Off.
}
{$DEFINE CRC32C_Accelerated}
{$IFDEF CRC32_CRC32C_Accelerated_Off}
{$UNDEF CRC32C_Accelerated}
{$ENDIF}
interface
uses
Classes,
AuxTypes, BasicUIM, HashBase;
{===============================================================================
Common types and constants
===============================================================================}
{
Bytes in TCRC32 are always ordered from least significant byte to most
significant byte (little endian).
Type TCRC32Sys has no such guarantee and its endianness is system-dependent.
To convert the checksum in default ordering to a required specific ordering,
use methods CRC32ToLE for little endian and CRC32ToBE for big endian.
Note that these methods are expecting the input value to be in default
ordering, if it is not, the result will be wrong. Be carefull when using them.
}
type
TCRC32 = packed array[0..3] of UInt8;
PCRC32 = ^TCRC32;
TCRC32Sys = UInt32;
PCRC32Sys = ^TCRC32Sys;
TCRC32Table = array[Byte] of TCRC32Sys;
PCRC32Table = ^TCRC32Table;
const
{
Initial value of CRC-32.
WARNING - use only in standalone, backward compatibility functions!
}
InitialCRC32: TCRC32 = ($00,$00,$00,$00);
ZeroCRC32: TCRC32 = (0,0,0,0);
type
ECRC32Exception = class(EHashException);
ECRC32IncompatibleClass = class(ECRC32Exception);
ECRC32IndexOutOfBounds = class(ECRC32Exception);
ECRC32NoImplementation = class(ECRC32Exception);
{-------------------------------------------------------------------------------
================================================================================
TCRC32BaseHash
================================================================================
-------------------------------------------------------------------------------}
{===============================================================================
TCRC32BaseHash - class declaration
===============================================================================}
type
TCRC32BaseHash = class(TStreamHash)
protected
fImplManager: TImplementationManager;
fCRC32Value: TCRC32Sys;
fCRC32Table: PCRC32Table;
fProcessBuffer: procedure(const Buffer; Size: TMemSize) of object; register;
Function GetCRC32: TCRC32; virtual;
Function GetCRC32Poly: TCRC32Sys; virtual;
Function GetCRC32PolyRef: TCRC32Sys; virtual; abstract;
Function GetHashImplementation: THashImplementation; override;
procedure SetHashImplementation(Value: THashImplementation); override;
{$IFNDEF PurePascal}
procedure ProcessBuffer_ASM(const Buffer; Size: TMemSize); virtual; register;
{$ENDIF}
procedure ProcessBuffer_PAS(const Buffer; Size: TMemSize); virtual; register;
procedure ProcessBuffer(const Buffer; Size: TMemSize); override;
procedure InitializeTable; virtual; abstract;
procedure FinalizeTable; virtual; abstract;
procedure Initialize; override;
procedure Finalize; override;
public
class Function CRC32ToSys(CRC32: TCRC32): TCRC32Sys; virtual;
class Function CRC32FromSys(CRC32: TCRC32Sys): TCRC32; virtual;
class Function CRC32ToLE(CRC32: TCRC32): TCRC32; virtual;
class Function CRC32ToBE(CRC32: TCRC32): TCRC32; virtual;
class Function CRC32FromLE(CRC32: TCRC32): TCRC32; virtual;
class Function CRC32FromBE(CRC32: TCRC32): TCRC32; virtual;
class Function HashImplementationsAvailable: THashImplementations; override;
class Function HashImplementationsSupported: THashImplementations; override;
class Function HashSize: TMemSize; override;
class Function HashEndianness: THashEndianness; override;
class Function HashFinalization: Boolean; override;
constructor CreateAndInitFrom(Hash: THashBase); overload; override;
constructor CreateAndInitFrom(Hash: TCRC32); overload; virtual;
Function Compare(Hash: THashBase): Integer; override;
Function AsString: String; override;
procedure FromString(const Str: String); override;
procedure FromStringDef(const Str: String; const Default: TCRC32); reintroduce;
procedure SaveToStream(Stream: TStream; Endianness: THashEndianness = heDefault); override;
procedure LoadFromStream(Stream: TStream; Endianness: THashEndianness = heDefault); override;
property CRC32: TCRC32 read GetCRC32;
property CRC32Sys: TCRC32Sys read fCRC32Value;
property CRC32Poly: TCRC32Sys read GetCRC32Poly; // polynomial
property CRC32PolyRef: TCRC32Sys read GetCRC32PolyRef; // polynomial with reflected bit order
property CRC32Table: PCRC32Table read fCRC32Table;
end;
{-------------------------------------------------------------------------------
================================================================================
TCRC32Hash
================================================================================
-------------------------------------------------------------------------------}
{===============================================================================
TCRC32Hash - class declaration
===============================================================================}
type
TCRC32Hash = class(TCRC32BaseHash)
protected
Function GetCRC32PolyRef: TCRC32Sys; override;
procedure ProcessBuffer(const Buffer; Size: TMemSize); override;
procedure InitializeTable; override;
procedure FinalizeTable; override;
public
class Function HashName: String; override;
class Function HashFinalization: Boolean; override;
procedure Init; override;
end;
{-------------------------------------------------------------------------------
================================================================================
TCRC32CHash
================================================================================
-------------------------------------------------------------------------------}
{===============================================================================
TCRC32CHash - class declaration
===============================================================================}
type
TCRC32CHash = class(TCRC32BaseHash)
protected
class Function AccelerationSupported: Boolean; virtual;
Function GetCRC32PolyRef: TCRC32Sys; override;
{$IF not Defined(PurePascal) and Defined(CRC32C_Accelerated)}
procedure ProcessBuffer_ACC(const Buffer; Size: TMemSize); virtual; register;
{$IFEND}
procedure ProcessBuffer(const Buffer; Size: TMemSize); override;
procedure InitializeTable; override;
procedure FinalizeTable; override;
procedure Initialize; override;
public
class Function HashImplementationsAvailable: THashImplementations; override;
class Function HashImplementationsSupported: THashImplementations; override;
class Function HashName: String; override;
class Function HashFinalization: Boolean; override;
procedure Init; override;
end;
{-------------------------------------------------------------------------------
================================================================================
TCRC32CustomHash
================================================================================
-------------------------------------------------------------------------------}
{
Set of presets (algorithm parameters) for some of the known CRC-32 variants.
Source: reveng.sourceforge.net/crc-catalogue/17plus.htm
}
type
TCRC32CustomPreset = record
Name: String; // name assigned to this CRC-32 within this library
Aliases: String; // name aliasses, separated by comma (,)
Polynomial: TCRC32Sys; // polynomial with highest bit omitted
RefPolynomial: TCRC32Sys; // polynomial with reflected bit order and original highest bit omitted
FullPolynomial: UInt64; // full polynomial (only lower 33bits are to be observed)
InitialValue: TCRC32; // initial value of CRC register
ReflectIn: Boolean; // order in which bits are processed (false = LSB, true = MSB)
ReflectOut: Boolean; // byte-swapping of resulting CRC-32 value before presentation (affects only textual representation)
XOROutValue: TCRC32; // value XORed to the register after all processing is done
Check: TCRC32; // CRC-32 of UTF-8 encoded string "123456789" (without quotes)
Residue: TCRC32; // what is left in CRC-32 register (before final xor) after hashing of error-free data with appended CRC-32 value
Codewords: String; // datastream-crc pairs (binary, hexadecimal notation), separated by comma (,)
end;
const
CRC32_KNOWN_PRESETS: array[0..10] of TCRC32CustomPreset = (
(Name: 'CRC-32/AIXM';
Aliases: 'CRC-32Q';
Polynomial: $814141AB;
RefPolynomial: $D5828281;
FullPolynomial: $1814141AB;
InitialValue: ($00,$00,$00,$00);
ReflectIn: False;
ReflectOut: False;
XOROutValue: ($00,$00,$00,$00);
Check: ($7F,$BF,$10,$30);
Residue: ($00,$00,$00,$00);
Codewords: '3438303633374EA5A7C704,' +
'3031363334313145A1AE5741,' +
'3438303633374E3031363334313145A1BA30EE,' +
'3738326C297100,' +
'3438303633374E30313633343131453738326A259F4E,' +
'34362E37266D25C1,' +
'3438303633374E303136333431314534362E372F866D6D,' +
'3438303633374E303136333431314537383234362E375E5DC940'),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/AUTOSAR';
Aliases: '';
Polynomial: $F4ACFB13;
RefPolynomial: $C8DF352F;
FullPolynomial: $1F4ACFB13;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($6A,$D0,$97,$16);
Residue: ($BF,$DD,$4C,$90);
Codewords: '000000004022B36F,' +
'F20183251A724F,' +
'0FAA0055F82D6620,' +
'00FF55116E99D79B,' +
'332255AABBCCDDEEFF3D345AA6,' +
'926B55788A68EE,' +
'FFFFFFFFFFFFFFFF'),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/BASE91-D';
Aliases: 'CRC-32D';
Polynomial: $A833982B;
RefPolynomial: $D419CC15;
FullPolynomial: $1A833982B;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($76,$55,$31,$87);
Residue: ($51,$05,$27,$45);
Codewords: ''),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/BZIP2';
Aliases: 'CRC-32/AAL5, CRC-32/DECT-B, B-CRC-32';
Polynomial: $04C11DB7;
RefPolynomial: $EDB88320;
FullPolynomial: $104C11DB7;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: False;
ReflectOut: False;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($18,$19,$89,$FC);
Residue: ($7B,$DD,$04,$C7);
Codewords: '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000028864D7F99,' +
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000028C55E457A,' +
'0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20212223242526272800000028BF671ED0,' +
'0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20212223242526272811220028ACBA602A,' +
'6173640A86FA4F5B'),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/CD-ROM-EDC';
Aliases: '';
Polynomial: $8001801B;
RefPolynomial: $D8018001;
FullPolynomial: $18001801B;
InitialValue: ($00,$00,$00,$00);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($00,$00,$00,$00);
Check: ($C4,$ED,$C2,$6E);
Residue: ($00,$00,$00,$00);
Codewords: ''),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/CKSUM';
Aliases: 'CKSUM, CRC-32/POSIX';
Polynomial: $04C11DB7;
RefPolynomial: $EDB88320;
FullPolynomial: $104C11DB7;
InitialValue: ($00,$00,$00,$00);
ReflectIn: False;
ReflectOut: False;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($80,$76,$5E,$76);
Residue: ($7B,$DD,$04,$C7);
Codewords: ''),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/ISCSI';
Aliases: 'CRC-32/BASE91-C, CRC-32/CASTAGNOLI, CRC-32/INTERLAKEN, CRC-32C';
Polynomial: $1EDC6F41;
RefPolynomial: $82F63B78;
FullPolynomial: $11EDC6F41;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($83,$92,$06,$E3);
Residue: ($38,$B4,$98,$B7);
Codewords: '0000000000000000000000000000000000000000000000000000000000000000AA36918A,' +
'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43ABA862,' +
'000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F4E79DD46'),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/ISO-HDLC';
Aliases: 'CRC-32, CRC-32/ADCCP, CRC-32/V-42, CRC-32/XZ, PKZIP';
Polynomial: $04C11DB7;
RefPolynomial: $EDB88320;
FullPolynomial: $104C11DB7;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($FF,$FF,$FF,$FF);
Check: ($26,$39,$F4,$CB);
Residue: ($E3,$20,$BB,$DE);
Codewords: '000000001CDF4421,' +
'F20183779DAB24,' +
'0FAA005587B2C9B6,' +
'00FF55111262A032,' +
'332255AABBCCDDEEFF3D86AEB0,' +
'926B559BA2DE9C,' +
'FFFFFFFFFFFFFFFF,' +
'C008300028CFE9521D3B08EA449900E808EA449900E8300102007E649416,' +
'6173640ACEDE2D15'),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/JAMCRC';
Aliases: 'JAMCRC';
Polynomial: $04C11DB7;
RefPolynomial: $EDB88320;
FullPolynomial: $104C11DB7;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: True;
ReflectOut: True;
XOROutValue: ($00,$00,$00,$00);
Check: ($D9,$C6,$0B,$34);
Residue: ($00,$00,$00,$00);
Codewords: ''),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/MPEG-2';
Aliases: '';
Polynomial: $04C11DB7;
RefPolynomial: $EDB88320;
FullPolynomial: $104C11DB7;
InitialValue: ($FF,$FF,$FF,$FF);
ReflectIn: False;
ReflectOut: False;
XOROutValue: ($00,$00,$00,$00);
Check: ($E7,$E6,$76,$03);
Residue: ($00,$00,$00,$00);
Codewords: ''),
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Name: 'CRC-32/XFER';
Aliases: 'XFER';
Polynomial: $000000AF;
RefPolynomial: $F5000000;
FullPolynomial: $1000000AF;
InitialValue: ($00,$00,$00,$00);
ReflectIn: False;
ReflectOut: False;
XOROutValue: ($00,$00,$00,$00);
Check: ($38,$E3,$0B,$BD);
Residue: ($00,$00,$00,$00);
Codewords: ''));
const
CRC32_DEFAULT_PRESET_IDX = 7; // CRC-32/ISO-HDLC, ie. pkzip CRC-32
{===============================================================================
TCRC32CustomHash - class declaration
===============================================================================}
type
TCRC32CustomHash = class(TCRC32BaseHash)
protected
fCRC32Poly: TCRC32Sys; // actually in reflected bit order
fInitialValue: TCRC32;
fReflectIn: Boolean;
fReflectOut: Boolean;
fXOROutValue: TCRC32;
procedure SetCRC32Poly(Value: TCRC32Sys); virtual;
Function GetCRC32PolyRef: TCRC32Sys; override;
procedure SetCRC32PolyRef(Value: TCRC32Sys); virtual;
procedure SetInitialValue(Value: TCRC32); virtual;
procedure SetReflectIn(Value: Boolean); virtual;
procedure BuildTable; virtual;
procedure InitializeTable; override;
procedure FinalizeTable; override;
procedure Initialize; override;
procedure Finalize; override;
public
class Function HashName: String; override;
constructor CreateAndInitFrom(Hash: THashBase); override;
constructor CreateAndLoadPreset(Preset: TCRC32CustomPreset); overload;
constructor CreateAndLoadPreset(PresetIndex: Integer); overload;
constructor CreateAndLoadPreset(const PresetName: String); overload;
procedure LoadPreset(Preset: TCRC32CustomPreset); overload; virtual;
procedure LoadPreset(PresetIndex: Integer); overload; virtual;
procedure LoadPreset(const PresetName: String); overload; virtual;
Function SelfTest(Preset: TCRC32CustomPreset): Boolean; virtual;
procedure Init; override;
procedure Final; override;
Function AsString: String; override;
procedure FromString(const Str: String); override;
property CRC32Poly: TCRC32Sys read GetCRC32Poly write SetCRC32Poly;
property CRC32PolyRef: TCRC32Sys read GetCRC32PolyRef write SetCRC32PolyRef;
property InitialValue: TCRC32 read fInitialValue write SetInitialValue;
property ReflectIn: Boolean read fReflectIn write SetReflectIn;
property ReflectOut: Boolean read fReflectOut write fReflectOut;
property XOROutValue: TCRC32 read fXOROutValue write fXOROutValue;
end;
{===============================================================================
Backward compatibility functions
===============================================================================}
{
All following functions are implemented as simple wrappers for TCRC32Hash
class and its methods.
}
Function CRC32ToStr(CRC32: TCRC32): String;
Function StrToCRC32(const Str: String): TCRC32;
Function TryStrToCRC32(const Str: String; out CRC32: TCRC32): Boolean;
Function StrToCRC32Def(const Str: String; Default: TCRC32): TCRC32;
Function CompareCRC32(A,B: TCRC32): Integer;
Function SameCRC32(A,B: TCRC32): Boolean;
//------------------------------------------------------------------------------
Function BufferCRC32(CRC32: TCRC32; const Buffer; Size: TMemSize): TCRC32; overload;
Function BufferCRC32(const Buffer; Size: TMemSize): TCRC32; overload;
Function AnsiStringCRC32(const Str: AnsiString): TCRC32;
Function WideStringCRC32(const Str: WideString): TCRC32;
Function StringCRC32(const Str: String): TCRC32;
Function StreamCRC32(Stream: TStream; Count: Int64 = -1): TCRC32;
Function FileCRC32(const FileName: String): TCRC32;
//------------------------------------------------------------------------------
type
TCRC32Context = type Pointer;
Function CRC32_Init: TCRC32Context;
procedure CRC32_Update(Context: TCRC32Context; const Buffer; Size: TMemSize);
Function CRC32_Final(var Context: TCRC32Context; const Buffer; Size: TMemSize): TCRC32; overload;
Function CRC32_Final(var Context: TCRC32Context): TCRC32; overload;
Function CRC32_Hash(const Buffer; Size: TMemSize): TCRC32;
implementation
uses
SysUtils
{$IF not Defined(PurePascal) and Defined(CRC32C_Accelerated)}
, SimpleCPUID
{$IFEND};
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5057:={$WARN 5057 OFF}} // Local variable "$1" does not seem to be initialized
{$ENDIF}
{$IF not Defined(FPC) and not Defined(x64)}
{
ASM_MachineCode
When defined, some ASM instructions are inserted into byte stream directly
as a machine code. It is there because not all compilers supports, and
therefore can compile, such instructions.
As I am not able to tell which 32bit delphi compilers do support them,
I am assuming none of them do. I am also assuming that all 64bit delphi
compilers and current FPCs are supporting the instructions.
Has no effect when PurePascal is defined.
}
{$DEFINE ASM_MachineCode}
{$IFEND}
{-------------------------------------------------------------------------------
================================================================================
TCRC32BaseHash
================================================================================
-------------------------------------------------------------------------------}
{===============================================================================
TCRC32BaseHash - Utility functions
===============================================================================}
Function SwapEndian(Value: TCRC32Sys): TCRC32Sys; overload;
begin
Result := TCRC32Sys(
((Value and $000000FF) shl 24) or
((Value and $0000FF00) shl 8) or
((Value and $00FF0000) shr 8) or
((Value and $FF000000) shr 24));
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function SwapEndian(Value: TCRC32): TCRC32; overload;{$IFDEF CanInline} inline; {$ENDIF}
begin
Result := TCRC32(SwapEndian(TCRC32Sys(Value)));
end;
//------------------------------------------------------------------------------
Function ReflectBits(Value: UInt8): UInt8; overload;
const
RevBitsTable: array[UInt8] of UInt8 = (
$00, $80, $40, $C0, $20, $A0, $60, $E0, $10, $90, $50, $D0, $30, $B0, $70, $F0,
$08, $88, $48, $C8, $28, $A8, $68, $E8, $18, $98, $58, $D8, $38, $B8, $78, $F8,
$04, $84, $44, $C4, $24, $A4, $64, $E4, $14, $94, $54, $D4, $34, $B4, $74, $F4,
$0C, $8C, $4C, $CC, $2C, $AC, $6C, $EC, $1C, $9C, $5C, $DC, $3C, $BC, $7C, $FC,
$02, $82, $42, $C2, $22, $A2, $62, $E2, $12, $92, $52, $D2, $32, $B2, $72, $F2,
$0A, $8A, $4A, $CA, $2A, $AA, $6A, $EA, $1A, $9A, $5A, $DA, $3A, $BA, $7A, $FA,
$06, $86, $46, $C6, $26, $A6, $66, $E6, $16, $96, $56, $D6, $36, $B6, $76, $F6,
$0E, $8E, $4E, $CE, $2E, $AE, $6E, $EE, $1E, $9E, $5E, $DE, $3E, $BE, $7E, $FE,
$01, $81, $41, $C1, $21, $A1, $61, $E1, $11, $91, $51, $D1, $31, $B1, $71, $F1,
$09, $89, $49, $C9, $29, $A9, $69, $E9, $19, $99, $59, $D9, $39, $B9, $79, $F9,
$05, $85, $45, $C5, $25, $A5, $65, $E5, $15, $95, $55, $D5, $35, $B5, $75, $F5,
$0D, $8D, $4D, $CD, $2D, $AD, $6D, $ED, $1D, $9D, $5D, $DD, $3D, $BD, $7D, $FD,
$03, $83, $43, $C3, $23, $A3, $63, $E3, $13, $93, $53, $D3, $33, $B3, $73, $F3,
$0B, $8B, $4B, $CB, $2B, $AB, $6B, $EB, $1B, $9B, $5B, $DB, $3B, $BB, $7B, $FB,
$07, $87, $47, $C7, $27, $A7, $67, $E7, $17, $97, $57, $D7, $37, $B7, $77, $F7,
$0F, $8F, $4F, $CF, $2F, $AF, $6F, $EF, $1F, $9F, $5F, $DF, $3F, $BF, $7F, $FF);
begin
Result := RevBitsTable[Value];
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function ReflectBits(Value: TCRC32Sys): TCRC32Sys; overload;
type
TByteOverlay = packed array[0..3] of UInt8;
begin
TByteOverlay(Result)[3] := ReflectBits(TByteOverlay(Value)[0]);
TByteOverlay(Result)[2] := ReflectBits(TByteOverlay(Value)[1]);
TByteOverlay(Result)[1] := ReflectBits(TByteOverlay(Value)[2]);
TByteOverlay(Result)[0] := ReflectBits(TByteOverlay(Value)[3]);
end;
//------------------------------------------------------------------------------
Function ReflectByteBits(Value: TCRC32Sys): TCRC32Sys; overload;
type
TByteOverlay = packed array[0..3] of UInt8;
begin
TByteOverlay(Result)[0] := ReflectBits(TByteOverlay(Value)[0]);
TByteOverlay(Result)[1] := ReflectBits(TByteOverlay(Value)[1]);
TByteOverlay(Result)[2] := ReflectBits(TByteOverlay(Value)[2]);
TByteOverlay(Result)[3] := ReflectBits(TByteOverlay(Value)[3]);
end;
//------------------------------------------------------------------------------
procedure SplitString(const Str: String; Parts: TStrings);
var
i: Integer;
Start: Integer;
Len: Integer;
begin
Parts.Clear;
If Length(Str) > 0 then
begin
Start := 1;
Len := 0;
For i := 1 to Length(Str) do
If Str[i] = ',' then
begin
Parts.Add(Trim(Copy(Str,Start,Len)));
Start := Succ(i);
Len := 0;
end
else Inc(Len);
If Len > 0 then
Parts.Add(Trim(Copy(Str,Start,Len)));
end;
end;
{===============================================================================
TCRC32BaseHash - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCRC32BaseHash - protected methods
-------------------------------------------------------------------------------}
Function TCRC32BaseHash.GetCRC32: TCRC32;
begin
Result := CRC32FromSys(fCRC32Value);
end;
//------------------------------------------------------------------------------
Function TCRC32BaseHash.GetCRC32Poly: TCRC32Sys;
begin
Result := ReflectBits(GetCRC32PolyRef);
end;
//------------------------------------------------------------------------------
Function TCRC32BaseHash.GetHashImplementation: THashImplementation;
var
SelectedImplID: TUIMIdentifier;
begin
// do not call inherited
If fImplManager.FindObj(0).Selected(SelectedImplID) then
Result := THashImplementation(SelectedImplID)
else
raise ECRC32NoImplementation.Create('TCRC32BaseHash.GetHashImplementation: No implementation selected.');
end;
//------------------------------------------------------------------------------
procedure TCRC32BaseHash.SetHashImplementation(Value: THashImplementation);
begin
// do not call inherited
fImplManager.FindObj(0).Select(TUIMIdentifier(Value));
end;
//------------------------------------------------------------------------------
{$IFNDEF PurePascal}
procedure TCRC32BaseHash.ProcessBuffer_ASM(const Buffer; Size: TMemSize); assembler;
asm
{$IFDEF x64}
{$IFDEF Windows}
{-------------------------------------------------------------------------------
x86-64 assembly (64bit) - Windows
Content of registers on enter:
RCX Self
RDX pointer to Buffer
R8 Size
Used registers:
RAX, RCX, RDX, R8, R9, R10
-------------------------------------------------------------------------------}
MOV R10, qword ptr Self.fCRC32Table // address of CRC table into R10
LEA RCX, Self.fCRC32Value // load address of CRC
MOV R9D, dword ptr [RCX] // move old CRC into R9D
TEST R8, R8 // check whether size is zero...
JZ @RoutineEnd // ...end calculation when it is
//-- Main calculation, loop executed RCX times ---------------------------------
@MainLoop: MOV AL, byte ptr [RDX]
XOR AL, R9B
AND RAX, $00000000000000FF
MOV EAX, dword ptr [R10 + RAX * 4]
SHR R9D, 8
XOR R9D, EAX
INC RDX
DEC R8
JNZ @MainLoop
//-- Routine end ---------------------------------------------------------------
@RoutineEnd: MOV dword ptr [RCX], R9D // store result
{$ELSE Windows}
{-------------------------------------------------------------------------------
x86-64 assembly (64bit) - Linux
Content of registers on enter:
RDI Self
RSI pointer to Buffer
RDX Size
Used registers:
RAX, RDX, RDI, RSI, R8, R9
-------------------------------------------------------------------------------}
MOV R9, qword ptr Self.fCRC32Table // address of CRC table into R9
LEA RDI, Self.fCRC32Value // load address of CRC
MOV R8D, dword ptr [RDI] // move old CRC into R8D
TEST RDX, RDX // check whether size is zero...
JZ @RoutineEnd // ...end calculation when it is
//-- Main calculation, loop executed RCX times ---------------------------------
@MainLoop: MOV AL, byte ptr [RSI]
XOR AL, R8B
AND RAX, $00000000000000FF
MOV EAX, dword ptr [R9 + RAX * 4]
SHR R8D, 8
XOR R8D, EAX
INC RSI
DEC RDX
JNZ @MainLoop
//-- Routine end ---------------------------------------------------------------
@RoutineEnd: MOV dword ptr [RDI], R8D // store result
{$ENDIF Windows}
{$ELSE x64}
{-------------------------------------------------------------------------------
x86 assembly (32bit) - Windows, Linux
Content of registers on enter:
EAX Self
EDX pointer to Buffer
ECX Size
Used registers:
EAX, EBX (value preserved), ECX, EDX, ESI (value preserved)
-------------------------------------------------------------------------------}
PUSH ESI // preserve ESI on stack
MOV ESI, dword ptr Self.fCRC32Table // address of CRC table into ESI
LEA EAX, Self.fCRC32Value // load address of CRC
PUSH EAX // preserve address of CRC on stack
MOV EAX, dword ptr [EAX] // move old CRC into EAX
TEST ECX, ECX // check whether size is zero...
JZ @RoutineEnd // ...end calculation when it is
PUSH EBX // preserve EBX on stack
MOV EBX, EDX // move @Buffer to EBX
//-- Main calculation, loop executed ECX times ---------------------------------
@MainLoop: MOV DL, byte ptr [EBX]
XOR DL, AL
AND EDX, $000000FF
MOV EDX, dword ptr [ESI + EDX * 4]
SHR EAX, 8
XOR EAX, EDX
INC EBX
DEC ECX
JNZ @MainLoop
//-- Routine end ---------------------------------------------------------------
POP EBX // restore EBX register
@RoutineEnd: POP EDX // get address of CRC from stack
MOV dword ptr [EDX], EAX // store result
POP ESI // restore ESI register
{$ENDIF x64}
end;
{$ENDIF PurePascal}
//------------------------------------------------------------------------------
procedure TCRC32BaseHash.ProcessBuffer_PAS(const Buffer; Size: TMemSize);
var
i: TMemSize;
Buff: PByte;
begin
Buff := @Buffer;
For i := 1 to Size do
begin
fCRC32Value := fCRC32Table^[Byte(fCRC32Value) xor Buff^] xor (fCRC32Value shr 8);
Inc(Buff);
end;
end;
//------------------------------------------------------------------------------
procedure TCRC32BaseHash.ProcessBuffer(const Buffer; Size: TMemSize);
begin
fProcessBuffer(Buffer,Size);
end;
//------------------------------------------------------------------------------
procedure TCRC32BaseHash.Initialize;
begin
inherited;
fImplManager := TImplementationManager.Create;
with fImplManager.AddObj(0,TMethod(fProcessBuffer)) do
begin
Add(TUIMIdentifier(hiPascal),@TCRC32BaseHash.ProcessBuffer_PAS,Self,[ifSelect]);
{$IFDEF PurePascal}
AddAlias(TUIMIdentifier(hiPascal),TUIMIdentifier(hiAssembly));
AddAlias(TUIMIdentifier(hiPascal),TUIMIdentifier(hiAccelerated));
{$ELSE}
Add(TUIMIdentifier(hiAssembly),@TCRC32BaseHash.ProcessBuffer_ASM,Self);
AddAlias(TUIMIdentifier(hiAssembly),TUIMIdentifier(hiAccelerated));
{$ENDIF}
end;
fCRC32Value := 0;
InitializeTable;
HashImplementation := hiAccelerated; // sets fProcessBuffer
end;
//------------------------------------------------------------------------------
procedure TCRC32BaseHash.Finalize;
begin
FinalizeTable;
FreeAndNil(fImplManager);
inherited;
end;
{-------------------------------------------------------------------------------
TCRC32BaseHash - public methods
-------------------------------------------------------------------------------}
class Function TCRC32BaseHash.CRC32ToSys(CRC32: TCRC32): TCRC32Sys;
begin
Result := {$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(TCRC32Sys(CRC32));
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.CRC32FromSys(CRC32: TCRC32Sys): TCRC32;
begin
Result := TCRC32({$IFDEF ENDIAN_BIG}SwapEndian{$ENDIF}(CRC32));
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.CRC32ToLE(CRC32: TCRC32): TCRC32;
begin
Result := CRC32;
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.CRC32ToBE(CRC32: TCRC32): TCRC32;
begin
Result := SwapEndian(CRC32);
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.CRC32FromLE(CRC32: TCRC32): TCRC32;
begin
Result := CRC32;
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.CRC32FromBE(CRC32: TCRC32): TCRC32;
begin
Result := SwapEndian(CRC32);
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.HashImplementationsAvailable: THashImplementations;
begin
Result := [hiPascal{$IFNDEF PurePascal},hiAssembly{$ENDIF}];
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.HashImplementationsSupported: THashImplementations;
begin
Result := [hiPascal{$IFNDEF PurePascal},hiAssembly{$ENDIF}];
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.HashSize: TMemSize;
begin
Result := SizeOf(TCRC32);
end;
//------------------------------------------------------------------------------
class Function TCRC32BaseHash.HashEndianness: THashEndianness;
begin
Result := heLittle;
end;
//------------------------------------------------------------------------------