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

murmur-stream-reference-oracle.ts

106 lines2.9 KB

1/**
2 * Reference model for the murmur stream oracle: the stream as it was before
3 * it wrote whole words, with one `writeByte` call per byte. Load it after
4 * stubbing `Math.random`, so its seed and markers equal the current module's.
5 */
6​
7const randomHash = () => (Math.random() * (2 ** 31 - 1)) >>> 0
8​
9const RANDOM_SEED = randomHash()
10const STRING_MARKER = randomHash()
11const BIG_INT_MARKER = randomHash()
12const NEG_BIG_INT_MARKER = randomHash()
13​
14const buf = new ArrayBuffer(8)
15const dv = new DataView(buf)
16const u8 = new Uint8Array(buf)
17​
18export class ReferenceByteStream {
19 private hash: number = RANDOM_SEED
20 private length = 0
21 private carry = 0
22 private carryBytes = 0
23​
24 private _mix(k1: number): void {
25 k1 = Math.imul(k1, 0xcc9e2d51)
26 k1 = (k1 << 15) | (k1 >>> 17)
27 k1 = Math.imul(k1, 0x1b873593)
28 this.hash ^= k1
29 this.hash = (this.hash << 13) | (this.hash >>> 19)
30 this.hash = Math.imul(this.hash, 5) + 0xe6546b64
31 }
32​
33 writeByte(byte: number): void {
34 this.carry |= (byte & 0xff) << (8 * this.carryBytes)
35 this.carryBytes++
36 this.length++
37​
38 if (this.carryBytes === 4) {
39 this._mix(this.carry >>> 0)
40 this.carry = 0
41 this.carryBytes = 0
42 }
43 }
44​
45 update(chunk: symbol | string | number | bigint): void {
46 switch (typeof chunk) {
47 case `symbol`:
48 throw new TypeError(`The reference stream takes no symbols`)
49 case `string`:
50 this.update(STRING_MARKER)
51 for (let i = 0; i < chunk.length; i++) {
52 const code = chunk.charCodeAt(i)
53 this.writeByte(code & 0xff)
54 this.writeByte((code >>> 8) & 0xff)
55 }
56 return
57 case `number`:
58 dv.setFloat64(0, chunk, true) // fixed little-endian
59 this.writeByte(u8[0]!)
60 this.writeByte(u8[1]!)
61 this.writeByte(u8[2]!)
62 this.writeByte(u8[3]!)
63 this.writeByte(u8[4]!)
64 this.writeByte(u8[5]!)
65 this.writeByte(u8[6]!)
66 this.writeByte(u8[7]!)
67 return
68 case `bigint`: {
69 let value = chunk
70 if (value < 0n) {
71 value = -value
72 this.update(NEG_BIG_INT_MARKER)
73 } else {
74 this.update(BIG_INT_MARKER)
75 }
76 while (value > 0n) {
77 this.writeByte(Number(value & 0xffn))
78 value >>= 8n
79 }
80 if (chunk === 0n) this.writeByte(0)
81 return
82 }
83 default:
84 throw new TypeError(`Unsupported input type: ${typeof chunk}`)
85 }
86 }
87​
88 digest(): number {
89 if (this.carryBytes > 0) {
90 let k1 = this.carry >>> 0
91 k1 = Math.imul(k1, 0xcc9e2d51)
92 k1 = (k1 << 15) | (k1 >>> 17)
93 k1 = Math.imul(k1, 0x1b873593)
94 this.hash ^= k1
95 }
96​
97 this.hash ^= this.length
98 this.hash ^= this.hash >>> 16
99 this.hash = Math.imul(this.hash, 0x85ebca6b)
100 this.hash ^= this.hash >>> 13
101 this.hash = Math.imul(this.hash, 0xc2b2ae35)
102 this.hash ^= this.hash >>> 16
103​
104 return this.hash >>> 0
105 }