Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

murmur.ts

173 lines4.8 KB

1/*
2 * Implementation of murmur hash based on the Composites polyfill implementation:
3 * https://github.com/tc39/proposal-composites
4 */
5​
6const RANDOM_SEED = randomHash()
7const STRING_MARKER = randomHash()
8const BIG_INT_MARKER = randomHash()
9const NEG_BIG_INT_MARKER = randomHash()
10const SYMBOL_MARKER = randomHash()
11​
12type SymbolIdStore = {
13 get: (key: symbol) => number | undefined
14 set: (key: symbol, value: number) => unknown
16​
17const symbolIds = createSymbolIdStore()
18const registeredSymbolIds = new Map<string, number>()
19let nextSymbolId = 0
20​
21export function getSymbolIdentity(symbol: symbol): number {
22 const registeredKey = Symbol.keyFor(symbol)
23 if (registeredKey !== undefined) {
24 let id = registeredSymbolIds.get(registeredKey)
25 if (id === undefined) {
26 id = ++nextSymbolId
27 registeredSymbolIds.set(registeredKey, id)
28 }
29 return id
30 }
31​
32 let id = symbolIds.get(symbol)
33 if (id === undefined) {
34 id = ++nextSymbolId
35 symbolIds.set(symbol, id)
36 }
37 return id
39​
40function createSymbolIdStore(): SymbolIdStore {
41 const weakIds = new WeakMap<object, number>() as unknown as SymbolIdStore
42 const probe = Symbol()
43​
44 try {
45 weakIds.set(probe, 0)
46 if (weakIds.get(probe) === 0) return weakIds
47 } catch {
48 // Older runtimes reject symbols as weak keys. Retain them rather than
49 // merge distinct symbols and corrupt differential state.
50 }
51​
52 return new Map<symbol, number>()
54​
55export type Hash = number
56​
57export function randomHash() {
58 return (Math.random() * (2 ** 31 - 1)) >>> 0
60​
61export interface Hasher {
62 update: (val: symbol | string | number | bigint) => void
63 digest: () => number
65​
66// Allocate these once, outside the hot path
67const buf = new ArrayBuffer(8)
68// dv and u8 are 2 different views on the same buffer `buf`
69const dv = new DataView(buf)
70const u8 = new Uint8Array(buf)
71​
72/**
73 * This implementation of Murmur hash uses a random initial seed and random markers.
74 * This means that hashes aren't deterministic across app restarts.
75 * This is intentional in the composites polyfill to be resistent to hash-flooding attacks
76 * where malicious users would precompute lots of different objects whose hashes collide with each other.
77 *
78 * Currently, for ts/db-ivm this is fine because we don't persist client state.
79 * However, when we will introduce persistence we will either need to store the seeds or remove the randomness
80 * to ensure deterministic hashes across app restarts.
81 */
82export class MurmurHashStream implements Hasher {
83 private hash: number = RANDOM_SEED
84 private length = 0
85 private carry = 0
86 private carryBytes = 0
87​
88 private _mix(k1: number): void {
89 k1 = Math.imul(k1, 0xcc9e2d51)
90 k1 = (k1 << 15) | (k1 >>> 17)
91 k1 = Math.imul(k1, 0x1b873593)
92 this.hash ^= k1
93 this.hash = (this.hash << 13) | (this.hash >>> 19)
94 this.hash = Math.imul(this.hash, 5) + 0xe6546b64
95 }
96​
97 writeByte(byte: number): void {
98 this.carry |= (byte & 0xff) << (8 * this.carryBytes)
99 this.carryBytes++
100 this.length++
101​
102 if (this.carryBytes === 4) {
103 this._mix(this.carry >>> 0)
104 this.carry = 0
105 this.carryBytes = 0
106 }
107 }
108​
109 update(chunk: symbol | string | number | bigint): void {
110 switch (typeof chunk) {
111 case `symbol`: {
112 this.update(SYMBOL_MARKER)
113 this.update(getSymbolIdentity(chunk))
114 return
115 }
116 case `string`:
117 this.update(STRING_MARKER)
118 for (let i = 0; i < chunk.length; i++) {
119 const code = chunk.charCodeAt(i)
120 this.writeByte(code & 0xff)
121 this.writeByte((code >>> 8) & 0xff)
122 }
123 return
124 case `number`:
125 dv.setFloat64(0, chunk, true) // fixed little-endian
126 this.writeByte(u8[0]!)
127 this.writeByte(u8[1]!)
128 this.writeByte(u8[2]!)
129 this.writeByte(u8[3]!)
130 this.writeByte(u8[4]!)
131 this.writeByte(u8[5]!)
132 this.writeByte(u8[6]!)
133 this.writeByte(u8[7]!)
134 return
135 case `bigint`: {
136 let value = chunk
137 if (value < 0n) {
138 value = -value
139 this.update(NEG_BIG_INT_MARKER)
140 } else {
141 this.update(BIG_INT_MARKER)
142 }
143 while (value > 0n) {
144 this.writeByte(Number(value & 0xffn))
145 value >>= 8n
146 }
147 if (chunk === 0n) this.writeByte(0)
148 return
149 }
150 default:
151 throw new TypeError(`Unsupported input type: ${typeof chunk}`)
152 }
153 }
154​
155 digest(): number {
156 if (this.carryBytes > 0) {
157 let k1 = this.carry >>> 0
158 k1 = Math.imul(k1, 0xcc9e2d51)
159 k1 = (k1 << 15) | (k1 >>> 17)
160 k1 = Math.imul(k1, 0x1b873593)
161 this.hash ^= k1
162 }
163​
164 this.hash ^= this.length
165 this.hash ^= this.hash >>> 16
166 this.hash = Math.imul(this.hash, 0x85ebca6b)
167 this.hash ^= this.hash >>> 13
168 this.hash = Math.imul(this.hash, 0xc2b2ae35)
169 this.hash ^= this.hash >>> 16
170​
171 return this.hash >>> 0
172 }