Checksum.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. //
  2. // Checksum.h
  3. //
  4. // Library: Foundation
  5. // Package: Core
  6. // Module: Checksum
  7. //
  8. // Definition of the Checksum class.
  9. //
  10. // Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #ifndef Foundation_Checksum_INCLUDED
  16. #define Foundation_Checksum_INCLUDED
  17. #include "Poco/Foundation.h"
  18. namespace Poco {
  19. class Foundation_API Checksum
  20. /// This class calculates CRC-32 or Adler-32 checksums
  21. /// for arbitrary data.
  22. ///
  23. /// A cyclic redundancy check (CRC) is a type of hash function, which is used to produce a
  24. /// small, fixed-size checksum of a larger block of data, such as a packet of network
  25. /// traffic or a computer file. CRC-32 is one of the most commonly used CRC algorithms.
  26. ///
  27. /// Adler-32 is a checksum algorithm which was invented by Mark Adler.
  28. /// It is almost as reliable as a 32-bit cyclic redundancy check for protecting against
  29. /// accidental modification of data, such as distortions occurring during a transmission,
  30. /// but is significantly faster to calculate in software.
  31. {
  32. public:
  33. enum Type
  34. {
  35. TYPE_ADLER32 = 0,
  36. TYPE_CRC32
  37. };
  38. Checksum();
  39. /// Creates a CRC-32 checksum initialized to 0.
  40. Checksum(Type t);
  41. /// Creates the Checksum, using the given type.
  42. ~Checksum();
  43. /// Destroys the Checksum.
  44. void update(const char* data, unsigned length);
  45. /// Updates the checksum with the given data.
  46. void update(const std::string& data);
  47. /// Updates the checksum with the given data.
  48. void update(char data);
  49. /// Updates the checksum with the given data.
  50. Poco::UInt32 checksum() const;
  51. /// Returns the calculated checksum.
  52. Type type() const;
  53. /// Which type of checksum are we calulcating
  54. private:
  55. Type _type;
  56. Poco::UInt32 _value;
  57. };
  58. //
  59. // inlines
  60. //
  61. inline void Checksum::update(const std::string& data)
  62. {
  63. update(data.c_str(), static_cast<unsigned int>(data.size()));
  64. }
  65. inline void Checksum::update(char c)
  66. {
  67. update(&c, 1);
  68. }
  69. inline Poco::UInt32 Checksum::checksum() const
  70. {
  71. return _value;
  72. }
  73. inline Checksum::Type Checksum::type() const
  74. {
  75. return _type;
  76. }
  77. } // namespace Poco
  78. #endif // Foundation_Checksum_INCLUDED