]> Cypherpunks repositories - gostls13.git/commitdiff
time: don't panic stringifying the zero Month
authorBrad Fitzpatrick <bradfitz@golang.org>
Fri, 11 Nov 2016 20:54:07 +0000 (20:54 +0000)
committerBrad Fitzpatrick <bradfitz@golang.org>
Fri, 11 Nov 2016 21:31:52 +0000 (21:31 +0000)
Fixes #17720

Change-Id: Ib95c230deef3934db729856c17908f8e5a1e2b7f
Reviewed-on: https://go-review.googlesource.com/33145
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
src/time/time.go
src/time/time_test.go

index 03fde335c719283599fd83a07bb8af43c2aed172..175c9a9ae6fb98035e8cdd8049fb7ab0e4cc7aad 100644 (file)
@@ -114,7 +114,18 @@ var months = [...]string{
 }
 
 // String returns the English name of the month ("January", "February", ...).
-func (m Month) String() string { return months[m-1] }
+func (m Month) String() string {
+       if January <= m && m <= December {
+               return months[m-1]
+       }
+       const prefix = "%!Month("
+       buf := make([]byte, 20+len(prefix)+1)
+       buf[len(buf)-1] = ')'
+       n := fmtInt(buf[:len(buf)-1], uint64(m))
+       n -= len(prefix)
+       copy(buf[n:], prefix)
+       return string(buf[n:])
+}
 
 // A Weekday specifies a day of the week (Sunday = 0, ...).
 type Weekday int
index 0af9da34a20e9a3c9ac0d16e0fdae14a04994bfe..07afcffc2147161e23c39a74db17a7d27b51e6e9 100644 (file)
@@ -1117,8 +1117,8 @@ var defaultLocTests = []struct {
 
        {"Truncate", func(t1, t2 Time) bool { return t1.Truncate(Hour).Equal(t2.Truncate(Hour)) }},
        {"Round", func(t1, t2 Time) bool { return t1.Round(Hour).Equal(t2.Round(Hour)) }},
-       
-       {"== Time{}", func(t1, t2 Time) bool { return (t1==Time{}) == (t2==Time{}) }},
+
+       {"== Time{}", func(t1, t2 Time) bool { return (t1 == Time{}) == (t2 == Time{}) }},
 }
 
 func TestDefaultLoc(t *testing.T) {
@@ -1230,3 +1230,10 @@ func TestMarshalBinaryZeroTime(t *testing.T) {
                t.Errorf("t0=%#v\nt1=%#v\nwant identical structures", t0, t1)
        }
 }
+
+// Issue 17720: Zero value of time.Month fails to print
+func TestZeroMonthString(t *testing.T) {
+       if got, want := Month(0).String(), "%!Month(0)"; got != want {
+               t.Errorf("zero month = %q; want %q", got, want)
+       }
+}