OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 /// Jenkins hash function, optimized for small integers. | |
6 /// Borrowed from sdk/lib/math/jenkins_smi_hash.dart. | |
Brian Wilkerson
2016/11/15 20:51:37
"Borrowed from sdk/lib/math/jenkins_smi_hash.dart"
Paul Berry
2016/11/15 22:54:23
Done.
| |
7 /// | |
8 /// Where performance is critical, use [hash2], [hash3], or [hash4], or the | |
9 /// pattern `finish(combine(combine(...combine(0, a), b)..., z))`, where a..z | |
10 /// are hash codes to be combined. | |
11 /// | |
12 /// For ease of use, you may also use this pattern: | |
13 /// `(new JenkinsSmiHash()..add(a)..add(b)....add(z)).hashCode`, where a..z are | |
14 /// the sub-objects whose hashes should be combined. This pattern performs the | |
15 /// same operations as the performance critical variant, but allocates an extra | |
16 /// object. | |
17 class JenkinsSmiHash { | |
18 /// Accumulates the hash code [value] into the running hash [hash]. | |
19 static int combine(int hash, int value) { | |
20 hash = 0x1fffffff & (hash + value); | |
21 hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); | |
22 return hash ^ (hash >> 6); | |
23 } | |
24 | |
25 /// Finalizes a running hash produced by [combine]. | |
26 static int finish(int hash) { | |
27 hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); | |
28 hash = hash ^ (hash >> 11); | |
29 return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); | |
30 } | |
31 | |
32 /// Combines together two hash codes. | |
33 static int hash2(a, b) => finish(combine(combine(0, a), b)); | |
34 | |
35 /// Combines together three hash codes. | |
36 static int hash3(a, b, c) => finish(combine(combine(combine(0, a), b), c)); | |
37 | |
38 /// Combines together four hash codes. | |
39 static int hash4(a, b, c, d) => | |
40 finish(combine(combine(combine(combine(0, a), b), c), d)); | |
41 | |
42 int _hash = 0; | |
43 | |
44 /// Accumulates the object [o] into the hash. | |
45 void add(Object o) { | |
46 _hash = combine(_hash, o.hashCode); | |
47 } | |
48 | |
49 /// Finalizes the hash and return the resulting hashcode. | |
50 int get hashCode => finish(_hash); | |
51 } | |
OLD | NEW |