Skip to content

Commit d62154d

Browse files
mknyszekgopherbot
authored andcommitted
weak: don't panic when calling Value on a zero Pointer
Currently weak.Pointer.Value will panic if the weak.Pointer is uninitialized (zero value) which goes against it's documentation. Fix this and add a test. While we're here, also add a test to ensure weak.Make[T](nil) is equivalent to the zero value of weak.Pointer[T]. Fixes #71153. Change-Id: I4d9196026360bc42a5bfcb33ce449131ec251dba Reviewed-on: https://go-review.googlesource.com/c/go/+/641095 Reviewed-by: David Finkel <[email protected]> Auto-Submit: Michael Knyszek <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Carlos Amedee <[email protected]>
1 parent 9d0772b commit d62154d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/weak/pointer.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,9 @@ func Make[T any](ptr *T) Pointer[T] {
7878
// If a weak pointer points to an object with a finalizer, then Value will
7979
// return nil as soon as the object's finalizer is queued for execution.
8080
func (p Pointer[T]) Value() *T {
81+
if p.u == nil {
82+
return nil
83+
}
8184
return (*T)(runtime_makeStrongFromWeak(p.u))
8285
}
8386

src/weak/pointer_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ type T struct {
2121
}
2222

2323
func TestPointer(t *testing.T) {
24+
var zero weak.Pointer[T]
25+
if zero.Value() != nil {
26+
t.Error("Value of zero value of weak.Pointer is not nil")
27+
}
28+
zeroNil := weak.Make[T](nil)
29+
if zeroNil.Value() != nil {
30+
t.Error("Value of weak.Make[T](nil) is not nil")
31+
}
32+
2433
bt := new(T)
2534
wt := weak.Make(bt)
2635
if st := wt.Value(); st != bt {
@@ -41,6 +50,12 @@ func TestPointer(t *testing.T) {
4150
}
4251

4352
func TestPointerEquality(t *testing.T) {
53+
var zero weak.Pointer[T]
54+
zeroNil := weak.Make[T](nil)
55+
if zero != zeroNil {
56+
t.Error("weak.Make[T](nil) != zero value of weak.Pointer[T]")
57+
}
58+
4459
bt := make([]*T, 10)
4560
wt := make([]weak.Pointer[T], 10)
4661
wo := make([]weak.Pointer[int], 10)

0 commit comments

Comments
 (0)