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

structural-identity.test.ts

34 lines1.5 KB

1// Ordinary structural-identity tests: hand-written collision pairs that a
2// missing length prefix would merge, and a cyclic value with no identity. Both
3// compare production with fixed expectations. structural-identity-oracle.property.test.ts
4// owns the identity law (agreement with D2 value identity) and its checks.
5import { describe, expect, it } from 'vitest'
6import { equalHashValues, structuralIdentity } from '../src/hashing/hash.js'
7​
8// Different values whose parts, read without lengths, join to the same text.
9// A random four-character string never embeds a whole later part, so these
10// pairs pin the cases that a missing length prefix would merge.
11const collisionPairs: Array<[string, unknown, unknown]> = [
12 [`string spans a later key`, { a: `x|1:b="y` }, { a: `x`, b: `y` }],
13 [`key spans a later key`, { [`a="1:x|b`]: `y` }, { a: `x`, b: `y` }],
14 [`string spans a later element`, [`x|1:1="y`, ``], [`x`, `y`]],
15 [`header spans the body`, [`#1`], [1]],
17​
18describe(`structuralIdentity`, () => {
19 it.each(collisionPairs)(
20 `gives different values different identities: %s`,
21 (_, left, right) => {
22 expect(equalHashValues(left, right)).toBe(false)
23 const leftIdentity = structuralIdentity(left)
24 expect(leftIdentity).toBeDefined()
25 expect(leftIdentity).not.toBe(structuralIdentity(right))
26 },
27 )
28​
29 it(`returns no identity for a cyclic value`, () => {
30 const cyclic: Record<string, unknown> = {}
31 cyclic.self = cyclic
32 expect(structuralIdentity(cyclic)).toBeUndefined()
33 })
34})