Skip to content

Commit fa56bf1

Browse files
author
Bill Chung
committed
Issue zeromq#1080: Replace the original usage of string.GetHashCode() with hash value calculation using the MurmurHash algorithm.
1 parent 0af4d61 commit fa56bf1

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

src/NetMQ/Core/Transports/Ipc/IpcAddress.cs

+54-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public void Resolve(string name, bool ip4Only)
3939
{
4040
m_name = name;
4141

42-
int hash = name.GetHashCode();
42+
int hash = GetMurmurHash(name);
4343
if (hash < 0)
4444
hash = -hash;
4545
hash = hash%55536;
@@ -48,6 +48,59 @@ public void Resolve(string name, bool ip4Only)
4848
this.Address = new IPEndPoint(IPAddress.Loopback, hash);
4949
}
5050

51+
/// <summary>
52+
/// Calculate hash values using the MurmurHash algorithm
53+
/// </summary>
54+
/// <param name="name">input</param>
55+
/// <returns>hash value</returns>
56+
private static int GetMurmurHash(string name)
57+
{
58+
const uint seed = 0xc58f1a7b;
59+
const uint m = 0x5bd1e995;
60+
const int r = 24;
61+
62+
uint hash = seed ^ (uint)name.Length;
63+
int length = name.Length;
64+
int currentIndex = 0;
65+
66+
while (length >= 4)
67+
{
68+
uint k = (uint)(name[currentIndex] |
69+
(name[currentIndex + 1] << 8) |
70+
(name[currentIndex + 2] << 16) |
71+
(name[currentIndex + 3] << 24));
72+
73+
k *= m;
74+
k ^= k >> r;
75+
k *= m;
76+
77+
hash *= m;
78+
hash ^= k;
79+
80+
currentIndex += 4;
81+
length -= 4;
82+
}
83+
84+
switch (length)
85+
{
86+
case 3:
87+
hash ^= (uint)(name[currentIndex + 2] << 16);
88+
goto case 2;
89+
case 2:
90+
hash ^= (uint)(name[currentIndex + 1] << 8);
91+
goto case 1;
92+
case 1:
93+
hash ^= name[currentIndex];
94+
hash *= m;
95+
break;
96+
}
97+
98+
hash ^= hash >> 13;
99+
hash *= m;
100+
hash ^= hash >> 15;
101+
return (int)hash;
102+
}
103+
51104
[DisallowNull]
52105
public IPEndPoint? Address { get; private set; }
53106

0 commit comments

Comments
 (0)