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 8 #ifndef SkChecksum_DEFINED 9 #define SkChecksum_DEFINED 10 11 #include "include/core/SkString.h" 12 #include "include/core/SkTypes.h" 13 #include "include/private/SkOpts_spi.h" 14 #include "include/private/base/SkTLogic.h" 15 16 #include <string> 17 #include <string_view> 18 19 class SkChecksum { 20 public: 21 SkChecksum() = default; 22 // Make noncopyable 23 SkChecksum(const SkChecksum&) = delete; 24 SkChecksum& operator=(const SkChecksum&) = delete; 25 26 /** 27 * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you 28 * suspect its low bits aren't well mixed. 29 * 30 * This is the Murmur3 finalizer. 31 */ Mix(uint32_t hash)32 static uint32_t Mix(uint32_t hash) { 33 hash ^= hash >> 16; 34 hash *= 0x85ebca6b; 35 hash ^= hash >> 13; 36 hash *= 0xc2b2ae35; 37 hash ^= hash >> 16; 38 return hash; 39 } 40 41 /** 42 * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you 43 * suspect its low bits aren't well mixed. 44 * 45 * This version is 2-lines cheaper than Mix, but seems to be sufficient for the font cache. 46 */ CheapMix(uint32_t hash)47 static uint32_t CheapMix(uint32_t hash) { 48 hash ^= hash >> 16; 49 hash *= 0x85ebca6b; 50 hash ^= hash >> 16; 51 return hash; 52 } 53 }; 54 55 // SkGoodHash should usually be your first choice in hashing data. 56 // It should be both reasonably fast and high quality. 57 struct SkGoodHash { 58 template <typename K> operatorSkGoodHash59 std::enable_if_t<sizeof(K) == 4, uint32_t> operator()(const K& k) const { 60 return SkChecksum::Mix(*(const uint32_t*)&k); 61 } 62 63 template <typename K> operatorSkGoodHash64 std::enable_if_t<sizeof(K) != 4, uint32_t> operator()(const K& k) const { 65 return SkOpts::hash_fn(&k, sizeof(K), 0); 66 } 67 operatorSkGoodHash68 uint32_t operator()(const SkString& k) const { 69 return SkOpts::hash_fn(k.c_str(), k.size(), 0); 70 } 71 operatorSkGoodHash72 uint32_t operator()(const std::string& k) const { 73 return SkOpts::hash_fn(k.c_str(), k.size(), 0); 74 } 75 operatorSkGoodHash76 uint32_t operator()(std::string_view k) const { 77 return SkOpts::hash_fn(k.data(), k.size(), 0); 78 } 79 }; 80 81 #endif 82