小组成员:姚凯文(kevinyao0901),姜嘉琪
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.3 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include <string.h>
  5. #include "util/coding.h"
  6. #include "util/hash.h"
  7. // The FALLTHROUGH_INTENDED macro can be used to annotate implicit fall-through
  8. // between switch labels. The real definition should be provided externally.
  9. // This one is a fallback version for unsupported compilers.
  10. #ifndef FALLTHROUGH_INTENDED
  11. #define FALLTHROUGH_INTENDED do { } while (0)
  12. #endif
  13. namespace leveldb {
  14. uint32_t Hash(const char* data, size_t n, uint32_t seed) {
  15. // Similar to murmur hash
  16. const uint32_t m = 0xc6a4a793;
  17. const uint32_t r = 24;
  18. const char* limit = data + n;
  19. uint32_t h = seed ^ (n * m);
  20. // Pick up four bytes at a time
  21. while (data + 4 <= limit) {
  22. uint32_t w = DecodeFixed32(data);
  23. data += 4;
  24. h += w;
  25. h *= m;
  26. h ^= (h >> 16);
  27. }
  28. // Pick up remaining bytes
  29. switch (limit - data) {
  30. case 3:
  31. h += data[2] << 16;
  32. FALLTHROUGH_INTENDED;
  33. case 2:
  34. h += data[1] << 8;
  35. FALLTHROUGH_INTENDED;
  36. case 1:
  37. h += data[0];
  38. h *= m;
  39. h ^= (h >> r);
  40. break;
  41. }
  42. return h;
  43. }
  44. } // namespace leveldb