Skip to content

Instantly share code, notes, and snippets.

@Havret
Created November 3, 2021 13:26
Show Gist options
  • Save Havret/50e54d62d18360eed4d82b0cb12211ee to your computer and use it in GitHub Desktop.
Save Havret/50e54d62d18360eed4d82b0cb12211ee to your computer and use it in GitHub Desktop.
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