This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 419
/
Copy pathhash.d
908 lines (845 loc) · 31.3 KB
/
hash.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
/**
* Written in the D programming language.
* This module provides functions to uniform calculating hash values for different types
*
* Copyright: Copyright Igor Stepanov 2013-2013.
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Igor Stepanov
* Source: $(DRUNTIMESRC core/internal/_hash.d)
*/
module core.internal.hash;
import core.internal.traits : Unconst;
// If true ensure that positive zero and negative zero have the same hash.
// Historically typeid(float).getHash did this but hashOf(float) did not.
private enum floatCoalesceZeroes = true;
// If true ensure that all NaNs of the same floating point type have the same hash.
// Historically typeid(float).getHash didn't do this but hashOf(float) did.
private enum floatCoalesceNaNs = true;
// If either of the above are true then no struct or array that contains the
// representation of a floating point number may be hashed with `bytesHash`.
@nogc nothrow pure @safe unittest
{
static if (floatCoalesceZeroes)
assert(hashOf(+0.0) == hashOf(-0.0)); // Same hash for +0.0 and -0.0.
static if (floatCoalesceNaNs)
assert(hashOf(double.nan) == hashOf(-double.nan)); // Same hash for different NaN.
}
private enum hasCallableToHash(T) = __traits(compiles,
{
size_t hash = ((T* x) => (*x).toHash())(null);
});
@nogc nothrow pure @safe unittest
{
static struct S { size_t toHash() { return 4; } }
assert(hasCallableToHash!S);
assert(!hasCallableToHash!(shared const S));
}
private enum isFinalClassWithAddressBasedHash(T) = __traits(isFinalClass, T)
// Use __traits(compiles, ...) in case there are multiple overloads of `toHash`.
&& __traits(compiles, {static assert(&Object.toHash is &T.toHash);});
@nogc nothrow pure @safe unittest
{
static class C1 {}
final static class C2 : C1 {}
final static class C3 : C1 { override size_t toHash() const nothrow { return 1; }}
static assert(!isFinalClassWithAddressBasedHash!Object);
static assert(!isFinalClassWithAddressBasedHash!C1);
static assert(isFinalClassWithAddressBasedHash!C2);
static assert(!isFinalClassWithAddressBasedHash!C3);
}
private template isCppClassWithoutHash(T)
{
static if (!is(T == class) && !is(T == interface))
enum isCppClassWithoutHash = false;
else
enum bool isCppClassWithoutHash = __traits(getLinkage, T) == "C++"
&& !is(immutable T* : immutable Object*) && !hasCallableToHash!T;
}
/+
Is it valid to calculate a hash code for T based on the bits of its
representation? Always false for interfaces, dynamic arrays, and
associative arrays. False for all classes except final classes that do
not override `toHash`.
Note: according to the spec as of
https://github.com/dlang/dlang.org/commit/d66eff16491b0664c0fc00ba80a7aa291703f1f2
the contents of unnamed paddings between fields is undefined. Currently
this hashing implementation assumes that the padding contents (if any)
for all instances of `T` are the same. The correctness of this
assumption is yet to be verified.
+/
private template canBitwiseHash(T)
{
static if (is(T EType == enum))
enum canBitwiseHash = .canBitwiseHash!EType;
else static if (__traits(isFloating, T))
enum canBitwiseHash = !(floatCoalesceZeroes || floatCoalesceNaNs);
else static if (__traits(isScalar, T))
enum canBitwiseHash = true;
else static if (is(T == class))
{
enum canBitwiseHash = isFinalClassWithAddressBasedHash!T || isCppClassWithoutHash!T;
}
else static if (is(T == interface))
{
enum canBitwiseHash = isCppClassWithoutHash!T;
}
else static if (is(T == struct))
{
static if (hasCallableToHash!T || __traits(isNested, T))
enum canBitwiseHash = false;
else
{
import core.internal.traits : allSatisfy;
enum canBitwiseHash = allSatisfy!(.canBitwiseHash, typeof(T.tupleof));
}
}
else static if (is(T == union))
{
// Right now we always bytewise hash unions that lack callable `toHash`.
enum canBitwiseHash = !hasCallableToHash!T;
}
else static if (is(T E : E[]))
{
static if (__traits(isStaticArray, T))
enum canBitwiseHash = (T.length == 0) || .canBitwiseHash!E;
else
enum canBitwiseHash = false;
}
else static if (__traits(isAssociativeArray, T))
{
enum canBitwiseHash = false;
}
else
{
static assert(is(T == delegate) || is(T : void) || is(T : typeof(null)),
"Internal error: unanticipated type "~T.stringof);
enum canBitwiseHash = true;
}
}
//enum hash. CTFE depends on base type
size_t hashOf(T)(auto ref T val, size_t seed = 0)
if (is(T == enum) && !__traits(isScalar, T))
{
static if (is(T EType == enum)) {} //for EType
return hashOf(cast(EType) val, seed);
}
//CTFE ready (depends on base type).
size_t hashOf(T)(scope const auto ref T val, size_t seed = 0)
if (!is(T == enum) && __traits(isStaticArray, T) && canBitwiseHash!T)
{
import core.internal.convert : toUbyte;
// FIXME:
// We would like to to do this:
//
//static if (T.length == 0)
// return seed;
//else static if (T.length == 1)
// return hashOf(val[0], seed);
//else
// return bytesHashWithExactSizeAndAlignment!T(toUbyte(val), seed);
//
// ... but that's inefficient when using a runtime TypeInfo (introduces a branch)
// and PR #2243 wants typeid(T).getHash(&val) to produce the same result as
// hashOf(val).
static if (T.length == 0)
{
return bytesHashAlignedBy!size_t((ubyte[]).init, seed);
}
static if (is(typeof(toUbyte(val)) == const(ubyte)[]))
{
return bytesHashAlignedBy!T(toUbyte(val), seed);
}
else //Other types. CTFE unsupported
{
assert(!__ctfe, "unable to compute hash of "~T.stringof~" at compile time");
return bytesHashAlignedBy!T((cast(const(ubyte)*) &val)[0 .. T.sizeof], seed);
}
}
//CTFE ready (depends on base type).
size_t hashOf(T)(auto ref T val, size_t seed = 0)
if (!is(T == enum) && __traits(isStaticArray, T) && !canBitwiseHash!T)
{
// FIXME:
// We would like to to do this:
//
//static if (T.length == 0)
// return seed;
//else static if (T.length == 1)
// return hashOf(val[0], seed);
//else
// /+ hash like a dynamic array +/
//
// ... but that's inefficient when using a runtime TypeInfo (introduces a branch)
// and PR #2243 wants typeid(T).getHash(&val) to produce the same result as
// hashOf(val).
return hashOf(val[], seed);
}
//dynamic array hash
size_t hashOf(T)(scope const T val, size_t seed = 0)
if (is(T == S[], S) && (__traits(isScalar, S) || canBitwiseHash!S)) // excludes enum types
{
import core.internal.convert : toUbyte;
alias ElementType = typeof(val[0]);
static if (!canBitwiseHash!ElementType)
{
size_t hash = seed;
foreach (ref o; val)
{
hash = hashOf(hashOf(o), hash); // double hashing to match TypeInfo.getHash
}
return hash;
}
else static if (is(typeof(toUbyte(val)) == const(ubyte)[]))
//ubyteble array (arithmetic types and structs without toHash) CTFE ready for arithmetic types and structs without reference fields
{
return bytesHashAlignedBy!ElementType(toUbyte(val), seed);
}
else //Other types. CTFE unsupported
{
assert(!__ctfe, "unable to compute hash of "~T.stringof~" at compile time");
return bytesHashAlignedBy!ElementType((cast(const(ubyte)*) val.ptr)[0 .. ElementType.sizeof*val.length], seed);
}
}
//dynamic array hash
size_t hashOf(T)(T val, size_t seed = 0)
if (is(T == S[], S) && !(__traits(isScalar, S) || canBitwiseHash!S)) // excludes enum types
{
size_t hash = seed;
foreach (ref o; val)
{
hash = hashOf(hashOf(o), hash); // double hashing because TypeInfo.getHash doesn't allow to pass seed value
}
return hash;
}
// Indicates if F is a built-in complex number type.
private F coalesceFloat(F)(const F val)
if (__traits(isFloating, val) && !is(F == __vector) && !is(F : creal))
{
static if (floatCoalesceZeroes)
if (val == cast(F) 0)
return cast(F) 0;
static if (floatCoalesceNaNs)
if (val != val)
return F.nan;
return val;
}
//scalar type hash
@trusted @nogc nothrow pure
size_t hashOf(T)(scope const T val) if (__traits(isScalar, T) && !is(T == __vector))
{
static if (is(T V : V*))
{
if (__ctfe)
{
if (val is null) return 0;
assert(0, "Unable to calculate hash of non-null pointer at compile time");
}
size_t result = cast(size_t) val;
return result ^ (result >> 4);
}
else static if (is(T EType == enum) && is(typeof(val[0])))
{
// Enum type whose base type is vector.
return hashOf(cast(EType) val);
}
else static if (__traits(isIntegral, T))
{
static if (T.sizeof <= size_t.sizeof)
return val;
else
return cast(size_t) (val ^ (val >>> (size_t.sizeof * 8)));
}
else static if (is(T : creal))
{
return hashOf(coalesceFloat(val.re), hashOf(coalesceFloat(val.im)));
}
else
{
static assert(__traits(isFloating, T));
auto data = coalesceFloat(val);
static if (T.sizeof == float.sizeof && T.mant_dig == float.mant_dig)
return *cast(const uint*) &data;
else static if (T.sizeof == double.sizeof && T.mant_dig == double.mant_dig)
return hashOf(*cast(const ulong*) &data);
else
{
import core.internal.convert : floatSize, toUbyte;
return bytesHashWithExactSizeAndAlignment!T(toUbyte(data)[0 .. floatSize!T], 0);
}
}
}
//scalar type hash
@trusted @nogc nothrow pure
size_t hashOf(T)(scope const T val, size_t seed) if (__traits(isScalar, T) && !is(T == __vector))
{
static if (is(T V : V*))
{
if (__ctfe)
{
if (val is null) return hashOf(size_t(0), seed);
assert(0, "Unable to calculate hash of non-null pointer at compile time");
}
return hashOf(cast(size_t) val, seed);
}
else static if (is(T EType == enum) && is(typeof(val[0])))
{
// Enum type whose base type is vector.
return hashOf(cast(EType) val, seed);
}
else static if (__traits(isIntegral, val) && T.sizeof <= size_t.sizeof)
{
static if (size_t.sizeof < ulong.sizeof)
{
//MurmurHash3 32-bit single round
enum uint c1 = 0xcc9e2d51;
enum uint c2 = 0x1b873593;
enum uint c3 = 0xe6546b64;
enum uint r1 = 15;
enum uint r2 = 13;
}
else
{
//Half of MurmurHash3 64-bit single round
//(omits second interleaved update)
enum ulong c1 = 0x87c37b91114253d5;
enum ulong c2 = 0x4cf5ad432745937f;
enum ulong c3 = 0x52dce729;
enum uint r1 = 31;
enum uint r2 = 27;
}
size_t h = c1 * val;
h = (h << r1) | (h >>> (size_t.sizeof * 8 - r1));
h = (h * c2) ^ seed;
h = (h << r2) | (h >>> (size_t.sizeof * 8 - r2));
return h * 5 + c3;
}
else static if (__traits(isIntegral, val) && T.sizeof > size_t.sizeof)
{
static foreach (i; 0 .. T.sizeof / size_t.sizeof)
seed = hashOf(cast(size_t) (val >>> (size_t.sizeof * 8 * i)), seed);
return seed;
}
else static if (is(T : creal))
{
return hashOf(val.re, hashOf(val.im, seed));
}
else static if (__traits(isFloating, T))
{
auto data = coalesceFloat(val);
static if (T.sizeof == float.sizeof && T.mant_dig == float.mant_dig)
return hashOf(*cast(const uint*) &data, seed);
else static if (T.sizeof == double.sizeof && T.mant_dig == double.mant_dig)
return hashOf(*cast(const ulong*) &data, seed);
else
{
import core.internal.convert : floatSize, toUbyte;
return bytesHashWithExactSizeAndAlignment!T(toUbyte(data)[0 .. floatSize!T], seed);
}
}
else
{
static assert(0);
}
}
size_t hashOf(T)(scope const T val, size_t seed = 0) @safe @nogc nothrow pure
if (is(T == __vector)) // excludes enum types
{
static if (__traits(isFloating, T) && (floatCoalesceZeroes || floatCoalesceNaNs))
{
if (__ctfe)
{
// Workaround for CTFE bug.
static if (is(immutable typeof(val[0]) == immutable E, E)) {} // Get E.
E[T.sizeof / E.sizeof] array;
foreach (i; 0 .. T.sizeof / E.sizeof)
array[i] = val[i];
return hashOf(array, seed);
}
return hashOf(val.array, seed);
}
else
{
import core.internal.convert : toUbyte;
return bytesHashAlignedBy!T(toUbyte(val), seed);
}
}
//typeof(null) hash. CTFE supported
@trusted @nogc nothrow pure
size_t hashOf(T)(scope const T val) if (!is(T == enum) && is(T : typeof(null)))
{
return 0;
}
//typeof(null) hash. CTFE supported
@trusted @nogc nothrow pure
size_t hashOf(T)(scope const T val, size_t seed) if (!is(T == enum) && is(T : typeof(null)))
{
return hashOf(size_t(0), seed);
}
private enum _hashOfStruct =
q{
enum bool isChained = is(typeof(seed) : size_t);
static if (!isChained) enum size_t seed = 0;
static if (hasCallableToHash!(typeof(val))) //CTFE depends on toHash()
{
static if (!__traits(isSame, typeof(val), __traits(parent, val.toHash))
&& is(typeof(val is null)))
{
static if (isChained)
return hashOf(__traits(getMember, val, __traits(getAliasThis, typeof(val))), seed);
else
return hashOf(__traits(getMember, val, __traits(getAliasThis, typeof(val))));
}
else
{
static if (isChained)
return hashOf(cast(size_t) val.toHash(), seed);
else
return val.toHash();
}
}
else
{
import core.internal.convert : toUbyte;
static if (__traits(hasMember, T, "toHash") && is(typeof(T.toHash) == function))
{
// TODO: in the future maybe this should be changed to a static
// assert(0), because if there's a `toHash` the programmer probably
// expected it to be called and a compilation failure here will
// expose a bug in his code.
// In the future we also might want to disallow non-const toHash
// altogether.
pragma(msg, "Warning: struct "~__traits(identifier, T)
~" has method toHash, however it cannot be called with "
~typeof(val).stringof~" this.");
static if (__traits(compiles, __traits(getLocation, T.toHash)))
{
enum file = __traits(getLocation, T.toHash)[0];
enum line = __traits(getLocation, T.toHash)[1].stringof;
pragma(msg, " ",__traits(identifier, T),".toHash defined here: ",file,"(",line,")");
}
}
static if (T.tupleof.length == 0)
{
return seed;
}
else static if ((is(T == struct) && !canBitwiseHash!T) || T.tupleof.length == 1)
{
static if (isChained) size_t h = seed;
static foreach (i, F; typeof(val.tupleof))
{
static if (__traits(isStaticArray, F))
{
static if (i == 0 && !isChained) size_t h = 0;
static if (F.sizeof > 0 && canBitwiseHash!F)
// May use smallBytesHash instead of bytesHash.
h = bytesHashWithExactSizeAndAlignment!F(toUbyte(val.tupleof[i]), h);
else
// We can avoid the "double hashing" the top-level version uses
// for consistency with TypeInfo.getHash.
foreach (ref e; val.tupleof[i])
h = hashOf(e, h);
}
else static if (is(F == struct) || is(F == union))
{
static if (hasCallableToHash!F)
{
static if (!__traits(isSame, F, __traits(parent, val.tupleof[i].toHash))
&& is(typeof(val.tupleof[i] is null)))
{
static if (i == 0 && !isChained)
size_t h = hashOf(__traits(getMember, val.tupleof[i], __traits(getAliasThis, F)));
else
h = hashOf(__traits(getMember, val.tupleof[i], __traits(getAliasThis, F)), h);
}
else
{
static if (i == 0 && !isChained)
size_t h = val.tupleof[i].toHash();
else
h = hashOf(cast(size_t) val.tupleof[i].toHash(), h);
}
}
else static if (F.tupleof.length == 1)
{
// Handle the single member case separately to avoid unnecessarily using bytesHash.
static if (i == 0 && !isChained)
size_t h = hashOf(val.tupleof[i].tupleof[0]);
else
h = hashOf(val.tupleof[i].tupleof[0], h);
}
else static if (canBitwiseHash!F)
{
// May use smallBytesHash instead of bytesHash.
static if (i == 0 && !isChained) size_t h = 0;
h = bytesHashWithExactSizeAndAlignment!F(toUbyte(val.tupleof[i]), h);
}
else
{
// Nothing special happening.
static if (i == 0 && !isChained)
size_t h = hashOf(val.tupleof[i]);
else
h = hashOf(val.tupleof[i], h);
}
}
else
{
// Nothing special happening.
static if (i == 0 && !isChained)
size_t h = hashOf(val.tupleof[i]);
else
h = hashOf(val.tupleof[i], h);
}
}
return h;
}
else static if (is(typeof(toUbyte(val)) == const(ubyte)[]))//CTFE ready for structs without reference fields
{
// Not using bytesHashWithExactSizeAndAlignment here because
// the result may differ from typeid(T).hashOf(&val).
return bytesHashAlignedBy!T(toUbyte(val), seed);
}
else // CTFE unsupported
{
assert(!__ctfe, "unable to compute hash of "~T.stringof~" at compile time");
const(ubyte)[] bytes = (() @trusted => (cast(const(ubyte)*)&val)[0 .. T.sizeof])();
// Not using bytesHashWithExactSizeAndAlignment here because
// the result may differ from typeid(T).hashOf(&val).
return bytesHashAlignedBy!T(bytes, seed);
}
}
};
//struct or union hash
size_t hashOf(T)(scope const auto ref T val, size_t seed = 0)
if (!is(T == enum) && (is(T == struct) || is(T == union))
&& !is(T == const) && !is(T == immutable)
&& canBitwiseHash!T)
{
mixin(_hashOfStruct);
}
//struct or union hash
size_t hashOf(T)(auto ref T val)
if (!is(T == enum) && (is(T == struct) || is(T == union))
&& !canBitwiseHash!T)
{
mixin(_hashOfStruct);
}
//struct or union hash
size_t hashOf(T)(auto ref T val, size_t seed)
if (!is(T == enum) && (is(T == struct) || is(T == union))
&& !canBitwiseHash!T)
{
mixin(_hashOfStruct);
}
//struct or union hash - https://issues.dlang.org/show_bug.cgi?id=19332 (support might be removed in future)
size_t hashOf(T)(scope auto ref T val, size_t seed = 0)
if (!is(T == enum) && (is(T == struct) || is(T == union))
&& (is(T == const) || is(T == immutable))
&& canBitwiseHash!T && !canBitwiseHash!(Unconst!T))
{
mixin(_hashOfStruct);
}
//delegate hash. CTFE only if null.
@trusted @nogc nothrow pure
size_t hashOf(T)(scope const T val, size_t seed = 0) if (!is(T == enum) && is(T == delegate))
{
if (__ctfe)
{
if (val is null) return hashOf(size_t(0), hashOf(size_t(0), seed));
assert(0, "unable to compute hash of "~T.stringof~" at compile time");
}
return hashOf(val.ptr, hashOf(cast(void*) val.funcptr, seed));
}
//address-based class hash. CTFE only if null.
@nogc nothrow pure @trusted
size_t hashOf(T)(scope const T val)
if (!is(T == enum) && (is(T == interface) || is(T == class))
&& canBitwiseHash!T)
{
if (__ctfe) if (val is null) return 0;
return hashOf(cast(const void*) val);
}
//address-based class hash. CTFE only if null.
@nogc nothrow pure @trusted
size_t hashOf(T)(scope const T val, size_t seed)
if (!is(T == enum) && (is(T == interface) || is(T == class))
&& canBitwiseHash!T)
{
if (__ctfe) if (val is null) return hashOf(size_t(0), seed);
return hashOf(cast(const void*) val, seed);
}
//class or interface hash. CTFE depends on toHash
size_t hashOf(T)(T val)
if (!is(T == enum) && (is(T == interface) || is(T == class))
&& !canBitwiseHash!T)
{
static if (__traits(compiles, {size_t h = val.toHash();}))
{
static if (is(__traits(parent, val.toHash) P) && !is(immutable T* : immutable P*)
&& is(typeof((ref P p) => p is null)))
return val ? hashOf(__traits(getMember, val, __traits(getAliasThis, T))) : 0;
else
return val ? val.toHash() : 0;
}
else
return val ? (cast(Object)val).toHash() : 0;
}
//class or interface hash. CTFE depends on toHash
size_t hashOf(T)(T val, size_t seed)
if (!is(T == enum) && (is(T == interface) || is(T == class))
&& !canBitwiseHash!T)
{
static if (__traits(compiles, {size_t h = val.toHash();}))
{
static if (is(__traits(parent, val.toHash) P) && !is(immutable T* : immutable P*)
&& is(typeof((ref P p) => p is null)))
return hashOf(val ? hashOf(__traits(getMember, val, __traits(getAliasThis, T)))
: size_t(0), seed);
else
return hashOf(val ? cast(size_t) val.toHash() : size_t(0), seed);
}
else
return hashOf(val ? (cast(Object)val).toHash() : 0, seed);
}
//associative array hash. CTFE depends on base types
size_t hashOf(T)(T aa) if (!is(T == enum) && __traits(isAssociativeArray, T))
{
static if (is(typeof(aa) : V[K], K, V)) {} // Put K & V in scope.
static if (__traits(compiles, (ref K k, ref V v) nothrow => .hashOf(k) + .hashOf(v)))
scope (failure) assert(0); // Allow compiler to infer nothrow.
if (!aa.length) return 0;
size_t h = 0;
// The computed hash is independent of the foreach traversal order.
foreach (ref key, ref val; aa)
h += hashOf(hashOf(val), hashOf(key));
return h;
}
//associative array hash. CTFE depends on base types
size_t hashOf(T)(T aa, size_t seed) if (!is(T == enum) && __traits(isAssociativeArray, T))
{
return hashOf(hashOf(aa), seed);
}
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// This overload is for backwards compatibility.
@system pure nothrow @nogc
size_t bytesHash()(scope const(void)* buf, size_t len, size_t seed)
{
return bytesHashAlignedBy!ubyte((cast(const(ubyte)*) buf)[0 .. len], seed);
}
private template bytesHashAlignedBy(AlignType)
{
static if (size_t.sizeof == 4)
alias bytesHashAlignedBy = bytesHash32!(
AlignType.alignof >= uint.alignof ? uint.alignof :
ubyte.alignof);
else
alias bytesHashAlignedBy = bytesHash64!(
AlignType.alignof >= ulong.alignof ? ulong.alignof :
AlignType.alignof >= uint.alignof ? uint.alignof :
ubyte.alignof);
}
private template bytesHashWithExactSizeAndAlignment(SizeAndAlignType)
{
static if (SizeAndAlignType.sizeof <= 3 || size_t.sizeof <= 4 &&
SizeAndAlignType.sizeof <= (SizeAndAlignType.alignof < uint.alignof ? 12 : 10))
alias bytesHashWithExactSizeAndAlignment = smallBytesHash;
else
alias bytesHashWithExactSizeAndAlignment = bytesHashAlignedBy!SizeAndAlignType;
}
// Fowler/Noll/Vo hash. http://www.isthe.com/chongo/tech/comp/fnv/
private size_t fnv()(scope const(ubyte)[] bytes, size_t seed) @nogc nothrow pure @safe
{
static if (size_t.max <= uint.max)
enum prime = (1U << 24) + (1U << 8) + 0x93U;
else static if (size_t.max <= ulong.max)
enum prime = (1UL << 40) + (1UL << 8) + 0xb3UL;
else
enum prime = (size_t(1) << 88) + (size_t(1) << 8) + size_t(0x3b);
foreach (b; bytes)
seed = (seed ^ b) * prime;
return seed;
}
private alias smallBytesHash = fnv;
//-----------------------------------------------------------------------------
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here
private uint get32bits()(scope const(ubyte)* x) @nogc nothrow pure @system
{
version (BigEndian)
{
return ((cast(uint) x[0]) << 24) | ((cast(uint) x[1]) << 16) | ((cast(uint) x[2]) << 8) | (cast(uint) x[3]);
}
else
{
return ((cast(uint) x[3]) << 24) | ((cast(uint) x[2]) << 16) | ((cast(uint) x[1]) << 8) | (cast(uint) x[0]);
}
}
private ulong get64bits()(scope const(ubyte)* x) @nogc nothrow pure @system
{
version (BigEndian)
{
return ((cast(ulong) x[0]) << 56) |
((cast(ulong) x[1]) << 48) |
((cast(ulong) x[2]) << 40) |
((cast(ulong) x[3]) << 32) |
((cast(ulong) x[4]) << 24) |
((cast(ulong) x[5]) << 16) |
((cast(ulong) x[6]) << 8) |
(cast(ulong) x[7]); }
else
{
return ((cast(ulong) x[7]) << 56) |
((cast(ulong) x[6]) << 48) |
((cast(ulong) x[5]) << 40) |
((cast(ulong) x[4]) << 32) |
((cast(ulong) x[3]) << 24) |
((cast(ulong) x[2]) << 16) |
((cast(ulong) x[1]) << 8) |
(cast(ulong) x[0]);
}
}
static if (size_t.sizeof == 4)
@nogc nothrow pure @trusted
private uint bytesHash32(uint alignment)(scope const(ubyte)[] bytes, size_t seed)
{
// MurmurHash3_x86_32.
auto len = bytes.length;
auto data = bytes.ptr;
auto nblocks = len / 4;
uint h1 = cast(uint)seed;
enum uint c1 = 0xcc9e2d51;
enum uint c2 = 0x1b873593;
enum uint c3 = 0xe6546b64;
//----------
// body
auto end_data = data+nblocks*uint.sizeof;
for (; data!=end_data; data += uint.sizeof)
{
static if (alignment == uint.alignof)
uint k1 = __ctfe ? get32bits(data) : *(cast(const uint*) data);
else static if (alignment == ubyte.alignof)
uint k1 = get32bits(data);
else
static assert(0, "Do not create unnecessary template instantiations.");
k1 *= c1;
k1 = (k1 << 15) | (k1 >> (32 - 15));
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >> (32 - 13));
h1 = h1*5+c3;
}
//----------
// tail
uint k1 = 0;
switch (len & 3)
{
case 3: k1 ^= data[2] << 16; goto case;
case 2: k1 ^= data[1] << 8; goto case;
case 1: k1 ^= data[0];
k1 *= c1; k1 = (k1 << 15) | (k1 >> (32 - 15)); k1 *= c2; h1 ^= k1;
goto default;
default:
}
//----------
// finalization
h1 ^= len;
// Force all bits of the hash block to avalanche.
h1 = (h1 ^ (h1 >> 16)) * 0x85ebca6b;
h1 = (h1 ^ (h1 >> 13)) * 0xc2b2ae35;
h1 ^= h1 >> 16;
return h1;
}
static if (size_t.sizeof == 8)
@nogc nothrow pure @trusted
private ulong bytesHash64(uint alignment)(scope const ubyte[] bytes, ulong seed)
{
// MurmurHash3_x86_32 modified to be 64-bit using constants from MurmurHash3_x64_128.
alias h1 = seed;
enum ulong c1 = 0x87c37b91114253d5;
enum ulong c2 = 0x4cf5ad432745937f;
enum uint c3 = 0x52dce729;
const(ubyte)* data = bytes.ptr;
//----------
// body
for (const end_data = bytes.ptr + (bytes.length & ~7);
data !is end_data;
data += 8)
{
static if (alignment == ulong.alignof)
auto k1 = __ctfe ? get64bits(data) : *cast(ulong*) data;
else static if (alignment == uint.alignof)
{
version (BigEndian)
auto k1 = __ctfe ? get64bits(data) : (((cast(ulong) *cast(uint*) data) << 32) | *cast(uint*) (data + 4));
else
auto k1 = __ctfe ? get64bits(data) : (((cast(ulong) *cast(uint*) (data + 4)) << 32) | *cast(uint*) data);
}
else static if (alignment == ubyte.alignof)
auto k1 = get64bits(data);
else
static assert(0, "Do not create unnecessary template instantiations.");
k1 *= c1;
k1 = (k1 << 31) | (k1 >> (64 - 31));
k1 *= c2;
h1 ^= k1;
h1 = (h1 << 27) | (h1 >> (64 - 27));
h1 = h1*5+c3;
}
//----------
// tail
ulong k1 = 0;
switch (bytes.length & 7)
{
case 7: k1 ^= (cast(ulong) data[6]) << 48; goto case;
case 6: k1 ^= (cast(ulong) data[5]) << 40; goto case;
case 5: k1 ^= (cast(ulong) data[4]) << 32; goto case;
case 4: k1 ^= (cast(ulong) data[3]) << 24; goto case;
case 3: k1 ^= (cast(ulong) data[2]) << 16; goto case;
case 2: k1 ^= (cast(ulong) data[1]) << 8; goto case;
case 1: k1 ^= (cast(ulong) data[0]);
k1 *= c1; k1 = (k1 << 31) | (k1 >> (64 - 31)); k1 *= c2; h1 ^= k1;
goto default;
default:
}
//----------
// finalization
h1 ^= bytes.length;
// Force all bits of the hash block to avalanche.
h1 = (h1 ^ (h1 >> 33)) * 0xff51afd7ed558ccd;
h1 = (h1 ^ (h1 >> 33)) * 0xc4ceb9fe1a85ec53;
return h1 ^= h1 >> 33;
}
// Check that bytesHash works with CTFE
pure nothrow @system @nogc unittest
{
size_t ctfeHash(string x)
{
return bytesHash(x.ptr, x.length, 0);
}
enum test_str = "Sample string";
enum size_t hashVal = ctfeHash(test_str);
assert(hashVal == bytesHash(&test_str[0], test_str.length, 0));
// Detect unintended changes to bytesHash on unaligned and aligned inputs.
version (BigEndian)
{
const ubyte[7] a = [99, 4, 3, 2, 1, 5, 88];
const uint[2] b = [0x04_03_02_01, 0x05_ff_ff_ff];
const ulong[1] c = [0x04_03_02_01_05_ff_ff_ff];
}
else
{
const ubyte[7] a = [99, 1, 2, 3, 4, 5, 88];
const uint[2] b = [0x04_03_02_01, 0xff_ff_ff_05];
const ulong[1] c = [0xff_ff_ff_05_04_03_02_01];
}
// It is okay to change the below values if you make a change
// that you expect to change the result of bytesHash.
enum expectedResult = size_t.sizeof == 4 ? 2727459272U : 10677742034643552556UL;
assert(bytesHash(&a[1], a.length - 2, 0) == expectedResult);
assert(bytesHash(&b, 5, 0) == expectedResult);
assert(bytesHashAlignedBy!uint((cast(const ubyte*) &b)[0 .. 5], 0) == expectedResult);
assert(bytesHashAlignedBy!ulong((cast(const ubyte*) &c)[0 .. 5], 0) == expectedResult);
assert(bytesHashAlignedBy!ulong((cast(const ubyte*) &c)[0 .. c.sizeof], 0) ==
(size_t.sizeof == 4 ? 2948526704 : 7625915911016357963));
}