SkChecksum.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright 2012 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SkChecksum_DEFINED
  8. #define SkChecksum_DEFINED
  9. #include "include/core/SkString.h"
  10. #include "include/core/SkTypes.h"
  11. #include "include/private/SkNoncopyable.h"
  12. #include "include/private/SkTLogic.h"
  13. // #include "src/core/SkOpts.h"
  14. // It's sort of pesky to be able to include SkOpts.h here, so we'll just re-declare what we need.
  15. namespace SkOpts {
  16. extern uint32_t (*hash_fn)(const void*, size_t, uint32_t);
  17. }
  18. class SkChecksum : SkNoncopyable {
  19. public:
  20. /**
  21. * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you
  22. * suspect its low bits aren't well mixed.
  23. *
  24. * This is the Murmur3 finalizer.
  25. */
  26. static uint32_t Mix(uint32_t hash) {
  27. hash ^= hash >> 16;
  28. hash *= 0x85ebca6b;
  29. hash ^= hash >> 13;
  30. hash *= 0xc2b2ae35;
  31. hash ^= hash >> 16;
  32. return hash;
  33. }
  34. /**
  35. * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you
  36. * suspect its low bits aren't well mixed.
  37. *
  38. * This version is 2-lines cheaper than Mix, but seems to be sufficient for the font cache.
  39. */
  40. static uint32_t CheapMix(uint32_t hash) {
  41. hash ^= hash >> 16;
  42. hash *= 0x85ebca6b;
  43. hash ^= hash >> 16;
  44. return hash;
  45. }
  46. };
  47. // SkGoodHash should usually be your first choice in hashing data.
  48. // It should be both reasonably fast and high quality.
  49. struct SkGoodHash {
  50. template <typename K>
  51. SK_WHEN(sizeof(K) == 4, uint32_t) operator()(const K& k) const {
  52. return SkChecksum::Mix(*(const uint32_t*)&k);
  53. }
  54. template <typename K>
  55. SK_WHEN(sizeof(K) != 4, uint32_t) operator()(const K& k) const {
  56. return SkOpts::hash_fn(&k, sizeof(K), 0);
  57. }
  58. uint32_t operator()(const SkString& k) const {
  59. return SkOpts::hash_fn(k.c_str(), k.size(), 0);
  60. }
  61. };
  62. #endif