Open History to see the last commit
1import { MurmurHashStream, randomHash } from './murmur.js'
2import type { Hasher } from './murmur.js'
3
4/*
5 * Implementation of structural hashing based on the Composites polyfill implementation:
6 * https://github.com/tc39/proposal-composites
7 */
8
9const TRUE = randomHash()
10const FALSE = randomHash()
11const NULL = randomHash()
12const UNDEFINED = randomHash()
13const KEY = randomHash()
14const FUNCTIONS = randomHash()
15const DATE_MARKER = randomHash()
16const OBJECT_MARKER = randomHash()
17const ARRAY_MARKER = randomHash()
18const MAP_MARKER = randomHash()
19const SET_MARKER = randomHash()
20const UINT8ARRAY_MARKER = randomHash()
21const TEMPORAL_MARKER = randomHash()
22
23const temporalTypes = new Set([
24 `Temporal.Duration`,
25 `Temporal.Instant`,
26 `Temporal.PlainDate`,
27 `Temporal.PlainDateTime`,
28 `Temporal.PlainMonthDay`,
29 `Temporal.PlainTime`,
30 `Temporal.PlainYearMonth`,
31 `Temporal.ZonedDateTime`,
32])
33
34interface TemporalLike {
35 [Symbol.toStringTag]: string
36 toString: () => string
37}
38
39function isTemporal(input: object): input is TemporalLike {
40 const tag = (input as Record<symbol, unknown>)[Symbol.toStringTag]
41 return typeof tag === `string` && temporalTypes.has(tag)
42}
43
44// Maximum byte length for Uint8Arrays to hash by content instead of reference
45// Arrays smaller than this will be hashed by content, allowing proper equality comparisons
46// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays
47const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128
48
49const hashCache = new WeakMap<object, number>()
50
51export function hash(input: any): number {
52 const hasher = new MurmurHashStream()
53 updateHasher(hasher, input)
54 return hasher.digest()
55}
56
57function hashObject(input: object): number {
58 const cachedHash = hashCache.get(input)
59 if (cachedHash !== undefined) {
60 return cachedHash
61 }
62
63 let valueHash: number | undefined
64 if (input instanceof Date) {
65 valueHash = hashDate(input)
66 } else if (
67 // Check if input is a Uint8Array or Buffer
68 (typeof Buffer !== `undefined` && input instanceof Buffer) ||
69 input instanceof Uint8Array
70 ) {
71 // For small Uint8Arrays/Buffers (e.g., ULIDs, UUIDs), hash by content
72 // to enable proper equality comparisons. For large arrays, hash by reference
73 // to avoid performance costs.
74 if (input.byteLength <= UINT8ARRAY_CONTENT_HASH_THRESHOLD) {
75 valueHash = hashUint8Array(input)
76 } else {
77 // Deeply hashing large arrays would be too costly
78 // so we track them by reference and cache them in a weak map
79 return cachedReferenceHash(input)
80 }
81 } else if (input instanceof File) {
82 // Files are always hashed by reference due to their potentially large size
83 return cachedReferenceHash(input)
84 } else if (isTemporal(input)) {
85 valueHash = hashTemporal(input)
86 } else {
87 let plainObjectInput = input
88 let marker = OBJECT_MARKER
89
90 if (input instanceof Array) {
91 marker = ARRAY_MARKER
92 }
93
94 if (input instanceof Map) {
95 marker = MAP_MARKER
96 plainObjectInput = [...input.entries()]
97 }
98
99 if (input instanceof Set) {
100 marker = SET_MARKER
101 plainObjectInput = [...input.entries()]
102 }
103
104 valueHash = hashPlainObject(plainObjectInput, marker)
105 }
106
107 hashCache.set(input, valueHash)
108 return valueHash
109}
110
111function hashDate(input: Date): number {
112 const hasher = new MurmurHashStream()
113 hasher.update(DATE_MARKER)
114 hasher.update(input.getTime())
115 return hasher.digest()
116}
117
118function hashUint8Array(input: Uint8Array): number {
119 const hasher = new MurmurHashStream()
120 hasher.update(UINT8ARRAY_MARKER)
121 // Hash the byte length first to differentiate arrays of different sizes
122 hasher.update(input.byteLength)
123 // Hash each byte in the array
124 for (let i = 0; i < input.byteLength; i++) {
125 hasher.writeByte(input[i]!)
126 }
127 return hasher.digest()
128}
129
130function hashTemporal(input: TemporalLike): number {
131 const hasher = new MurmurHashStream()
132 hasher.update(TEMPORAL_MARKER)
133 hasher.update(input[Symbol.toStringTag])
134 hasher.update(input.toString())
135 return hasher.digest()
136}
137
138function hashPlainObject(input: object, marker: number): number {
139 const hasher = new MurmurHashStream()
140
141 // Mark the type of the input
142 hasher.update(marker)
143 const keys = Object.keys(input)
144 keys.sort(keySort)
145 for (const key of keys) {
146 hasher.update(KEY)
147 hasher.update(key)
148 updateHasher(hasher, input[key as keyof typeof input])
149 }
150
151 return hasher.digest()
152}
153
154function updateHasher(hasher: Hasher, input: unknown): void {
155 if (input === null) {
156 hasher.update(NULL)
157 return
158 }
159 switch (typeof input) {
160 case `undefined`:
161 hasher.update(UNDEFINED)
162 return
163 case `boolean`:
164 hasher.update(input ? TRUE : FALSE)
165 return
166 case `number`:
167 // Normalize NaNs and -0
168 hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
169 return
170 case `bigint`:
171 case `string`:
172 case `symbol`:
173 hasher.update(input)
174 return
175 case `object`:
176 hasher.update(getCachedHash(input))
177 return
178 case `function`:
179 // Functions are assigned a globally unique ID
180 // and that ID is cached in the weak map
181 hasher.update(cachedReferenceHash(input))
182 return
183 default:
184 console.warn(
185 `Ignored input during hashing because it is of type ${typeof input} which is not supported`,
186 )
187 }
188}
189
190function getCachedHash(input: object): number {
191 let valueHash = hashCache.get(input)
192 if (valueHash === undefined) {
193 valueHash = hashObject(input)
194 }
195 return valueHash
196}
197
198let nextRefId = 1
199function cachedReferenceHash(fn: object): number {
200 let valueHash = hashCache.get(fn)
201 if (valueHash === undefined) {
202 valueHash = nextRefId ^ FUNCTIONS
203 nextRefId++
204 hashCache.set(fn, valueHash)
205 }
206 return valueHash
207}
208
209/**
210 * Strings sorted lexicographically.
211 */
212function keySort(a: string, b: string): number {
213 return a.localeCompare(b)
214}