@@ -8,8 +8,7 @@ package core
88
99import (
1010 "errors"
11- "sync"
12- "weak"
11+ "unique"
1312)
1413
1514var errNoCreat = errors .New ("weak: create fn nil" )
@@ -19,9 +18,10 @@ type reftest[V any] func(*V) bool
1918
2019func refpass [V any ](_ * V ) bool { return true }
2120
21+ // WeakRef is a weak reference to a value of type V.
2222type WeakRef [V any ] struct {
23- mu sync. RWMutex
24- weak weak. Pointer [ V ]
23+ // unique.Handle holds a weak reference to *V.
24+ weak unique. Handle [ * V ]
2525 creat reffactory [V ]
2626 test reftest [V ]
2727}
@@ -41,37 +41,23 @@ func NewWeakRef[V any](creat reffactory[V], test reftest[V]) (*WeakRef[V], error
4141}
4242
4343func (w * WeakRef [V ]) load () (v * V , valid bool ) {
44- defer func () { // test without lock held
45- valid = v != nil && w .test (v )
46- }()
47-
48- w .mu .RLock ()
49- defer w .mu .RUnlock ()
5044 v = w .weak .Value ()
45+ valid = v != nil && w .test (v )
5146 return
5247}
5348
54- func (w * WeakRef [V ]) storeLocked () (v * V ) {
49+ func (w * WeakRef [V ]) store () (v * V , valid bool ) {
5550 v = w .creat ()
56- w .weak = weak .Make (v )
51+ w .weak = unique .Make (v )
52+ valid = v != nil && w .test (v )
5753 return
5854}
5955
6056func (w * WeakRef [V ]) loadOrStore () (v * V , valid bool ) {
6157 if v , valid = w .load (); valid {
6258 return
6359 }
64-
65- defer func () { // test without lock held
66- valid = v != nil && w .test (v )
67- }()
68-
69- w .mu .Lock ()
70- defer w .mu .Unlock ()
71- if v = w .weak .Value (); v == nil { // gc won
72- v = w .storeLocked () // new v
73- } // else: use existing v
74- return
60+ return w .store () // new v
7561}
7662
7763func (w * WeakRef [V ]) Ref () (v * V , valid bool ) {
0 commit comments