crc32c.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #pragma once
  10. #include <stddef.h>
  11. #include <stdint.h>
  12. #include <string>
  13. #include "rocksdb/rocksdb_namespace.h"
  14. namespace ROCKSDB_NAMESPACE {
  15. namespace crc32c {
  16. extern std::string IsFastCrc32Supported();
  17. // Return the crc32c of concat(A, data[0,n-1]) where init_crc is the
  18. // crc32c of some string A. Extend() is often used to maintain the
  19. // crc32c of a stream of data.
  20. extern uint32_t Extend(uint32_t init_crc, const char* data, size_t n);
  21. // Return the crc32c of data[0,n-1]
  22. inline uint32_t Value(const char* data, size_t n) {
  23. return Extend(0, data, n);
  24. }
  25. static const uint32_t kMaskDelta = 0xa282ead8ul;
  26. // Return a masked representation of crc.
  27. //
  28. // Motivation: it is problematic to compute the CRC of a string that
  29. // contains embedded CRCs. Therefore we recommend that CRCs stored
  30. // somewhere (e.g., in files) should be masked before being stored.
  31. inline uint32_t Mask(uint32_t crc) {
  32. // Rotate right by 15 bits and add a constant.
  33. return ((crc >> 15) | (crc << 17)) + kMaskDelta;
  34. }
  35. // Return the crc whose masked representation is masked_crc.
  36. inline uint32_t Unmask(uint32_t masked_crc) {
  37. uint32_t rot = masked_crc - kMaskDelta;
  38. return ((rot >> 17) | (rot << 15));
  39. }
  40. } // namespace crc32c
  41. } // namespace ROCKSDB_NAMESPACE