1 module cachetools.hash;
2 
3 import std.traits;
4 
5 ///
6 /// For classes (and structs with toHash method) we use v.toHash() to compute hash.
7 /// -------------------------------------------------------------------------------
8 /// toHash method CAN BE @nogc or not. HashMap 'nogc' properties is inherited from this method.
9 /// toHash method MUST BE @safe or @trusted, as all HashMap code alredy safe.
10 ///
11 /// See also: https://dlang.org/spec/hash-map.html#using_classes_as_key 
12 /// and https://dlang.org/spec/hash-map.html#using_struct_as_key
13 ///
14 bool UseToHashMethod(T)() {
15     return (is(T == class) || (is(T==struct) && __traits(compiles, {
16         T v = T.init; hash_t h = v.toHash();
17     })));
18 }
19 
20 hash_t hash_function(T)(in T v) @safe /* @nogc inherited from toHash method */
21 if ( UseToHashMethod!T )
22 {
23     return v.toHash();
24 }
25 
26 hash_t hash_function(T)(in T v) @nogc @trusted
27 if ( !UseToHashMethod!T )
28 {
29     static if ( isNumeric!T ) {
30         enum m = 0x5bd1e995;
31         hash_t h = v;
32         h ^= h >> 13;
33         h *= m;
34         h ^= h >> 15;
35         return h;
36     }
37     else static if ( is(T == string) ) {
38         // FNV-1a hash
39         ulong h = 0xcbf29ce484222325;
40         foreach (const ubyte c; cast(ubyte[]) v)
41         {
42             h ^= c;
43             h *= 0x100000001b3;
44         }
45         return cast(hash_t)h;
46     }
47     else
48     {
49         const(ubyte)[] bytes = (cast(const(ubyte)*)&v)[0 .. T.sizeof];
50         ulong h = 0xcbf29ce484222325;
51         foreach (const ubyte c; bytes)
52         {
53             h ^= c;
54             h *= 0x100000001b3;
55         }
56         return cast(hash_t)h;
57     }
58 }
59 
60 @safe unittest
61 {
62     assert(hash_function("abc") == cast(hash_t)0xe71fa2190541574b);
63 
64     struct A0 {}
65     assert(!UseToHashMethod!A0);
66 
67     struct A1 {
68         hash_t toHash() const @safe {
69             return 0;
70         }
71     }
72     assert(UseToHashMethod!A1);
73 
74     // class with toHash override - will use toHash
75     class C0 {
76         override hash_t toHash() const @safe {
77             return 0;
78         }
79     }
80     assert(UseToHashMethod!C0);
81     C0 c0 = new C0();
82     assert(c0.toHash() == 0);
83 
84     // class without toHash override - use Object.toHash method
85     class C1 {
86     }
87     assert(UseToHashMethod!C1);
88 }