Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions gs/builtin/runtime-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,25 @@ describe('builtin runtime contract helpers', () => {
)
})

it('returns the same field reference across interleaved fieldRef calls', () => {
// The last reference is cached, which must not change which reference
// each target and field gets.
const a = { x: 1, y: 2 }
const b = { x: 3, y: 4 }
const ax = fieldRef(a, 'x')
const bx = fieldRef(b, 'x')
const ay = fieldRef(a, 'y')
expect(fieldRef(a, 'x')).toBe(ax)
expect(fieldRef(a, 'x')).toBe(ax)
expect(fieldRef(b, 'x')).toBe(bx)
expect(fieldRef(a, 'y')).toBe(ay)
expect(ax).not.toBe(bx)
expect(ax).not.toBe(ay)
ax.value = 5
expect(a.x).toBe(5)
expect(fieldRef(a, 'x').value).toBe(5)
})

it('matches struct map keys by Go comparable value', () => {
class Key {
declare public name: string
Expand Down
25 changes: 25 additions & 0 deletions gs/builtin/varRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,31 @@ export function varRef<T>(v: T): VarRef<T> {
export function fieldRef<T extends object, K extends keyof T>(
target: T,
key: K,
): VarRef<T[K]> {
// A loop usually takes the address of the same field again and again, as
// a method returning &s.field does, so the last reference is remembered,
// which avoids the two map lookups. References are never replaced, so it
// is always the one that the maps hold.
if (target === lastFieldTarget && key === lastFieldKey) {
return lastFieldRef as VarRef<T[K]>
}
const ref = fieldRefLookup(target, key)
lastFieldTarget = target
lastFieldKey = key
lastFieldRef = ref
return ref
}

// lastFieldTarget, lastFieldKey and lastFieldRef are the arguments and result
// of the last fieldRef call. Only this one target is kept alive by them.
let lastFieldTarget: object | undefined
let lastFieldKey: PropertyKey | undefined
let lastFieldRef: VarRef<unknown> | undefined

// fieldRefLookup finds or makes the reference of fieldRef in fieldReferences.
function fieldRefLookup<T extends object, K extends keyof T>(
target: T,
key: K,
): VarRef<T[K]> {
let references = fieldReferences.get(target)
if (references === undefined) {
Expand Down
Loading