1 /**
2 Copyright: Copyright (c) 2016-2017, Joakim Brännström. All rights reserved.
3 License: MPL-2
4 Author: Joakim Brännström (joakim.brannstrom@gmx.com)
5 
6 This Source Code Form is subject to the terms of the Mozilla Public License,
7 v.2.0. If a copy of the MPL was not distributed with this file, You can obtain
8 one at http://mozilla.org/MPL/2.0/.
9 */
10 module dextool.hash;
11 
12 /// Make a hash out of the raw data.
13 ulong makeHash(T)(T raw) @safe pure nothrow @nogc {
14     import std.digest.crc;
15 
16     ulong value = 0;
17 
18     if (raw is null)
19         return value;
20     ubyte[4] hash = crc32Of(raw);
21     return value ^ ((hash[0] << 24) | (hash[1] << 16) | (hash[2] << 8) | hash[3]);
22 }
23 
24 Murmur3 makeMurmur3(const(ubyte)[] p) @trusted nothrow {
25     import std.digest.murmurhash;
26 
27     MurmurHash3!(128, 64) hasher;
28     hasher.put(p);
29 
30     ubyte[16] h = hasher.finish;
31 
32     ulong a = *(cast(ulong*)&h[0]);
33     ulong b = *(cast(ulong*)&h[8]);
34 
35     return Murmur3(a, b);
36 }
37 
38 /// Checksum of the content of a file.
39 struct Murmur3 {
40     ulong c0;
41     ulong c1;
42 
43     bool opEquals(const this o) nothrow @safe {
44         return c0 == o.c0 && c1 == o.c1;
45     }
46 
47     import std.format : FormatSpec;
48 
49     void toString(Writer, Char)(scope Writer w, FormatSpec!Char fmt) const {
50         import std.format : formatValue, formattedWrite;
51         import std.range.primitives : put;
52 
53         if (fmt.spec == 'x')
54             formattedWrite(w, "%x%x", c0, c1);
55         else
56             formattedWrite(w, "%s%s", c0, c1);
57     }
58 }