Created
November 3, 2021 13:26
-
-
Save Havret/50e54d62d18360eed4d82b0cb12211ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArtemisBucketHelper | |
{ | |
public int GetBucket(string groupId, int bucketCount) | |
{ | |
var bytes = ToBytes(groupId); | |
var hashCode = ToHashCode(bytes); | |
return (hashCode & int.MaxValue) % bucketCount; | |
} | |
private byte[] ToBytes(string groupId) | |
{ | |
var data = new byte[groupId.Length << 1]; | |
int j = 0; | |
foreach (var c in groupId) | |
{ | |
byte low = (byte) (c & 0xFF); // low byte | |
data[j++] = low; | |
byte high = (byte) (c >> 8 & 0xFF); // high byte | |
data[j++] = high; | |
} | |
return data; | |
} | |
private int ToHashCode(byte[] bytes) | |
{ | |
var hashCode = 0; | |
foreach (var element in bytes) | |
{ | |
hashCode = (hashCode << 5) - hashCode + element; // (hash << 5) - hash is same as hash * 31 | |
} | |
return hashCode; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment