| 1 | /** |
| 2 | * Internal hashing helpers used by cluster routing to map entity identifiers to |
| 3 | * shard numbers. The hash is intentionally small and deterministic for |
| 4 | * JavaScript strings so every node that sees the same entity id and sharding |
| 5 | * configuration derives the same destination shard. |
| 6 | * |
| 7 | * **Gotchas** |
| 8 | * |
| 9 | * - Changing this implementation changes entity-to-shard assignment. |
| 10 | * - Strings are hashed as UTF-16 code units; normalize ids before routing if |
| 11 | * callers may produce equivalent text in different Unicode forms. |
| 12 | */ |
| 13 | /** |
| 14 | * @internal |
| 15 | */ |
| 16 | export const hashOptimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000) |
| 17 | |
| 18 | /** |
| 19 | * @internal |
| 20 | */ |
| 21 | export const hashString = (str: string) => { |
| 22 | let h = 5381, i = str.length |
| 23 | while (i) { |
| 24 | h = (h * 33) ^ str.charCodeAt(--i) |
| 25 | } |
| 26 | return hashOptimize(h) |
| 27 | } |