Skip to content

Commit

Permalink
weak: don't panic when calling Value on a zero Pointer
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
mknyszek authored and gopherbot committed Jan 7, 2025
1 parent 9d0772b commit d62154d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/weak/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ func Make[T any](ptr *T) Pointer[T] {
// If a weak pointer points to an object with a finalizer, then Value will
// return nil as soon as the object's finalizer is queued for execution.
func (p Pointer[T]) Value() *T {
if p.u == nil {
return nil
}
return (*T)(runtime_makeStrongFromWeak(p.u))
}

Expand Down
15 changes: 15 additions & 0 deletions src/weak/pointer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ type T struct {
}

func TestPointer(t *testing.T) {
var zero weak.Pointer[T]
if zero.Value() != nil {
t.Error("Value of zero value of weak.Pointer is not nil")
}
zeroNil := weak.Make[T](nil)
if zeroNil.Value() != nil {
t.Error("Value of weak.Make[T](nil) is not nil")
}

bt := new(T)
wt := weak.Make(bt)
if st := wt.Value(); st != bt {
Expand All @@ -41,6 +50,12 @@ func TestPointer(t *testing.T) {
}

func TestPointerEquality(t *testing.T) {
var zero weak.Pointer[T]
zeroNil := weak.Make[T](nil)
if zero != zeroNil {
t.Error("weak.Make[T](nil) != zero value of weak.Pointer[T]")
}

bt := make([]*T, 10)
wt := make([]weak.Pointer[T], 10)
wo := make([]weak.Pointer[int], 10)
Expand Down

0 comments on commit d62154d

Please sign in to comment.