Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 599e10c

Browse files
committed
Create MurmurHash2.cs
1 parent b8d149e commit 599e10c

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

src/ServiceStack.Text/MurmurHash2.cs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using System;
2+
3+
namespace ServiceStack.Text
4+
{
5+
// https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed#answer-145633
6+
// https://github.com/jitbit/MurmurHash.net
7+
public class MurmurHash2
8+
{
9+
public static uint Hash(string data)
10+
{
11+
return Hash(System.Text.Encoding.UTF8.GetBytes(data));
12+
}
13+
14+
public static uint Hash(byte[] data)
15+
{
16+
return Hash(data, 0xc58f1a7a);
17+
}
18+
const uint m = 0x5bd1e995;
19+
const int r = 24;
20+
21+
public static uint Hash(byte[] data, uint seed)
22+
{
23+
int length = data.Length;
24+
if (length == 0)
25+
return 0;
26+
uint h = seed ^ (uint)length;
27+
int currentIndex = 0;
28+
while (length >= 4)
29+
{
30+
uint k = (uint)(data[currentIndex++] | data[currentIndex++] << 8 | data[currentIndex++] << 16 | data[currentIndex++] << 24);
31+
k *= m;
32+
k ^= k >> r;
33+
k *= m;
34+
35+
h *= m;
36+
h ^= k;
37+
length -= 4;
38+
}
39+
switch (length)
40+
{
41+
case 3:
42+
h ^= (UInt16)(data[currentIndex++] | data[currentIndex++] << 8);
43+
h ^= (uint)(data[currentIndex] << 16);
44+
h *= m;
45+
break;
46+
case 2:
47+
h ^= (UInt16)(data[currentIndex++] | data[currentIndex] << 8);
48+
h *= m;
49+
break;
50+
case 1:
51+
h ^= data[currentIndex];
52+
h *= m;
53+
break;
54+
default:
55+
break;
56+
}
57+
58+
h ^= h >> 13;
59+
h *= m;
60+
h ^= h >> 15;
61+
62+
return h;
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)