tstime/mono: make json.Unmarshal of a zero time.Time yield a zero Time

This was the proximate cause of #2579.
#2582 is a deeper fix, but this will remain
as a footgun, so may as well fix it too.

Signed-off-by: Josh Bleecher Snyder <josh@tailscale.com>
pull/2572/head
Josh Bleecher Snyder 3 years ago committed by Josh Bleecher Snyder
parent f3c96df162
commit f013960d87

@ -121,6 +121,10 @@ func (t *Time) UnmarshalJSON(data []byte) error {
if err != nil { if err != nil {
return err return err
} }
if tt.IsZero() {
*t = 0
return nil
}
*t = Now().Add(-time.Since(tt)) *t = Now().Add(-time.Since(tt))
return nil return nil
} }

@ -5,6 +5,7 @@
package mono package mono
import ( import (
"encoding/json"
"testing" "testing"
"time" "time"
) )
@ -17,6 +18,22 @@ func TestNow(t *testing.T) {
} }
} }
func TestUnmarshalZero(t *testing.T) {
var tt time.Time
buf, err := json.Marshal(tt)
if err != nil {
t.Fatal(err)
}
var m Time
err = json.Unmarshal(buf, &m)
if err != nil {
t.Fatal(err)
}
if !m.IsZero() {
t.Errorf("expected unmarshal of zero time to be 0, got %d (~=%v)", m, m)
}
}
func BenchmarkMonoNow(b *testing.B) { func BenchmarkMonoNow(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
Now() Now()

Loading…
Cancel
Save