fpccrc.pas 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. {
  2. Copyright (c) 2000-2002 by Free Pascal Development Team
  3. Routines to compute CRC values
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. Unit fpccrc;
  18. {$i fpcdefs.inc}
  19. Interface
  20. Function UpdateCrc32(InitCrc:cardinal;const InBuf;InLen:integer):cardinal;
  21. { If needed trims the string to maxlen, adding at the end the CRC32 of discarded chars.
  22. The resulting string is guaranteed to be not longer than maxlen. }
  23. function TrimStrCRC32(const s: ansistring; maxlen: longint): ansistring;
  24. Implementation
  25. {*****************************************************************************
  26. Crc 32
  27. *****************************************************************************}
  28. var
  29. Crc32Tbl : array[0..255] of cardinal;
  30. procedure MakeCRC32Tbl;
  31. var
  32. crc : cardinal;
  33. i,n : integer;
  34. begin
  35. for i:=0 to 255 do
  36. begin
  37. crc:=i;
  38. for n:=1 to 8 do
  39. if (crc and 1)<>0 then
  40. crc:=(crc shr 1) xor cardinal($edb88320)
  41. else
  42. crc:=crc shr 1;
  43. Crc32Tbl[i]:=crc;
  44. end;
  45. end;
  46. Function UpdateCrc32(InitCrc:cardinal;const InBuf;InLen:Integer):cardinal;
  47. var
  48. i : integer;
  49. p : pchar;
  50. begin
  51. if Crc32Tbl[1]=0 then
  52. MakeCrc32Tbl;
  53. p:=@InBuf;
  54. result:=not InitCrc;
  55. for i:=1 to InLen do
  56. begin
  57. result:=Crc32Tbl[byte(result) xor byte(p^)] xor (result shr 8);
  58. inc(p);
  59. end;
  60. result:=not result;
  61. end;
  62. function TrimStrCRC32(const s: ansistring; maxlen: longint): ansistring;
  63. var
  64. crc: DWord;
  65. len: longint;
  66. begin
  67. len:=length(s);
  68. if (len<=maxlen) or (len<12) then
  69. result:=s
  70. else
  71. begin
  72. dec(maxlen,11);
  73. crc:=0;
  74. crc:=UpdateCrc32(crc,s[maxlen+1],len-maxlen);
  75. result:=copy(s,1,maxlen)+'$CRC'+hexstr(crc,8);
  76. end;
  77. end;
  78. end.