]> Cypherpunks repositories - gostls13.git/commitdiff
time: panic with a more helpful error on use of invalid Timer
authorBrad Fitzpatrick <bradfitz@golang.org>
Tue, 21 Oct 2014 11:26:40 +0000 (13:26 +0200)
committerBrad Fitzpatrick <bradfitz@golang.org>
Tue, 21 Oct 2014 11:26:40 +0000 (13:26 +0200)
Fixes #8721

LGTM=rsc
R=r, rsc
CC=golang-codereviews
https://golang.org/cl/155620045

src/time/sleep.go
src/time/sleep_test.go

index 61660d14ff94449f694d4ecf5c9074f4c3e4c401..e7a2ee2059867bd545d3f36d46f01efba3934155 100644 (file)
@@ -55,6 +55,9 @@ type Timer struct {
 // Stop does not close the channel, to prevent a read from the channel succeeding
 // incorrectly.
 func (t *Timer) Stop() bool {
+       if t.r.f == nil {
+               panic("time: Stop called on uninitialized Timer")
+       }
        return stopTimer(&t.r)
 }
 
@@ -78,6 +81,9 @@ func NewTimer(d Duration) *Timer {
 // It returns true if the timer had been active, false if the timer had
 // expired or been stopped.
 func (t *Timer) Reset(d Duration) bool {
+       if t.r.f == nil {
+               panic("time: Reset called on uninitialized Timer")
+       }
        w := when(d)
        active := stopTimer(&t.r)
        t.r.when = w
index 2cfb6a59c22f72e628942717cdec8201540fd5dd..c9b2956b7845e58e1d5bf0c766bade121ce3a8c6 100644 (file)
@@ -9,6 +9,7 @@ import (
        "fmt"
        "runtime"
        "sort"
+       "strings"
        "sync"
        "sync/atomic"
        "testing"
@@ -407,3 +408,23 @@ func TestOverflowRuntimeTimer(t *testing.T) {
        // the end of CheckRuntimeTimerOverflow in internal_test.go.
        CheckRuntimeTimerOverflow()
 }
+
+func checkZeroPanicString(t *testing.T) {
+       e := recover()
+       s, _ := e.(string)
+       if want := "called on uninitialized Timer"; !strings.Contains(s, want) {
+               t.Errorf("panic = %v; want substring %q", e, want)
+       }
+}
+
+func TestZeroTimerResetPanics(t *testing.T) {
+       defer checkZeroPanicString(t)
+       var tr Timer
+       tr.Reset(1)
+}
+
+func TestZeroTimerStopPanics(t *testing.T) {
+       defer checkZeroPanicString(t)
+       var tr Timer
+       tr.Stop()
+}