blob: 8a04c89ae79fac688759768fef5e6f1ea50fab8a [file] [log] [blame]
junov@chromium.orgef760602012-06-27 20:03:16 +00001/*
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
mtklein02f46cf2015-03-20 13:48:42 -070011#include "SkString.h"
12#include "SkTLogic.h"
junov@chromium.orgef760602012-06-27 20:03:16 +000013#include "SkTypes.h"
14
mtklein4e976072016-08-08 09:06:27 -070015// #include "SkOpts.h"
16// It's sort of pesky to be able to include SkOpts.h here, so we'll just re-declare what we need.
17namespace SkOpts {
18 extern uint32_t (*hash_fn)(const void*, size_t, uint32_t);
19}
20
reed@google.com88db9ef2012-07-03 19:44:20 +000021class SkChecksum : SkNoncopyable {
reed@google.com88db9ef2012-07-03 19:44:20 +000022public:
mtklein67a32712014-07-10 06:03:46 -070023 /**
24 * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you
25 * suspect its low bits aren't well mixed.
26 *
27 * This is the Murmur3 finalizer.
28 */
29 static uint32_t Mix(uint32_t hash) {
30 hash ^= hash >> 16;
31 hash *= 0x85ebca6b;
32 hash ^= hash >> 13;
33 hash *= 0xc2b2ae35;
34 hash ^= hash >> 16;
35 return hash;
36 }
commit-bot@chromium.org70d75ca2013-07-23 20:25:34 +000037
38 /**
reed40dab982015-01-28 13:28:53 -080039 * uint32_t -> uint32_t hash, useful for when you're about to trucate this hash but you
40 * suspect its low bits aren't well mixed.
41 *
42 * This version is 2-lines cheaper than Mix, but seems to be sufficient for the font cache.
43 */
44 static uint32_t CheapMix(uint32_t hash) {
45 hash ^= hash >> 16;
46 hash *= 0x85ebca6b;
47 hash ^= hash >> 16;
48 return hash;
49 }
reed@google.com88db9ef2012-07-03 19:44:20 +000050};
51
mtklein02f46cf2015-03-20 13:48:42 -070052// SkGoodHash should usually be your first choice in hashing data.
53// It should be both reasonably fast and high quality.
mtkleinc8d1dd42015-10-15 12:23:01 -070054struct SkGoodHash {
55 template <typename K>
56 SK_WHEN(sizeof(K) == 4, uint32_t) operator()(const K& k) const {
mtklein02f46cf2015-03-20 13:48:42 -070057 return SkChecksum::Mix(*(const uint32_t*)&k);
58 }
mtklein02f46cf2015-03-20 13:48:42 -070059
mtkleinc8d1dd42015-10-15 12:23:01 -070060 template <typename K>
61 SK_WHEN(sizeof(K) != 4, uint32_t) operator()(const K& k) const {
mtklein4e976072016-08-08 09:06:27 -070062 return SkOpts::hash_fn(&k, sizeof(K), 0);
mtkleinc8d1dd42015-10-15 12:23:01 -070063 }
64
65 uint32_t operator()(const SkString& k) const {
mtklein4e976072016-08-08 09:06:27 -070066 return SkOpts::hash_fn(k.c_str(), k.size(), 0);
mtkleinc8d1dd42015-10-15 12:23:01 -070067 }
68};
mtklein02f46cf2015-03-20 13:48:42 -070069
robertphillips@google.comfffc8d02012-06-28 00:29:23 +000070#endif