Skip to content

Commit 37bc17c

Browse files
committed
refactor: replace WeakValueDict with WeakKeyDict
1 parent 8bb339e commit 37bc17c

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/types.jl

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -528,15 +528,15 @@ Implements hash consing (flyweight design pattern) for `BasicSymbolic` objects.
528528
529529
This function checks if an equivalent `BasicSymbolic` object already exists. It uses a
530530
custom hash function (`hash2`) incorporating metadata and symtypes to search for existing
531-
objects in a `WeakValueDict` (`wvd`). Due to the possibility of hash collisions (where
531+
objects in a `WeakKeyDict` (`wkd`). Due to the possibility of hash collisions (where
532532
different objects produce the same hash), a custom equality check (`isequal_with_metadata`)
533533
which includes metadata comparison, is used to confirm the equivalence of objects with
534534
matching hashes. If an equivalent object is found, the existing object is returned;
535535
otherwise, the input `s` is returned. This reduces memory usage, improves compilation time
536536
for runtime code generation, and supports built-in common subexpression elimination,
537537
particularly when working with symbolic objects with metadata.
538538
539-
Using a `WeakValueDict` ensures that only weak references to `BasicSymbolic` objects are
539+
Using a `WeakKeyDict` ensures that only weak references to `BasicSymbolic` objects are
540540
stored, allowing objects that are no longer strongly referenced to be garbage collected.
541541
Custom functions `hash2` and `isequal_with_metadata` are used instead of `Base.hash` and
542542
`Base.isequal` to accommodate metadata without disrupting existing tests reliant on the
@@ -546,12 +546,13 @@ function BasicSymbolic(s::BasicSymbolic)::BasicSymbolic
546546
if !ENABLE_HASHCONSING[]
547547
return s
548548
end
549-
h = hash2(s)
550-
t = get!(wvd[], h, s)
551-
if t === s || isequal_with_metadata(t, s)
552-
t
549+
hcw = HashConsingWrapper(s)
550+
k = getkey(wkd[], hcw, nothing)
551+
if isnothing(k)
552+
wkd[][hcw] = nothing
553+
return s
553554
else
554-
s
555+
return k.bs
555556
end
556557
end
557558

0 commit comments

Comments
 (0)