Commit 7ad512e7 authored by Caleb Spare's avatar Caleb Spare Committed by Russ Cox

time: format negative monotonic times correctly in Time.String

Fixes #18993

Change-Id: Ia1fa20b6d82384b07e9ba5512b909439e0bec2a5
Reviewed-on: https://go-review.googlesource.com/36611
Run-TryBot: Caleb Spare <cespare@gmail.com>
Reviewed-by: 's avatarRuss Cox <rsc@golang.org>
Reviewed-by: 's avatarIan Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent 9799622f
......@@ -433,17 +433,13 @@ func (t Time) String() string {
// Format monotonic clock reading as m=±ddd.nnnnnnnnn.
if t.wall&hasMonotonic != 0 {
m2 := t.ext
m1, m2 := m2/1e9, m2%1e9
if m2 < 0 {
m2 += 1e9
m1--
}
m2 := uint64(t.ext)
sign := byte('+')
if m1 < 0 {
if t.ext < 0 {
sign = '-'
m1 = -m1
m2 = -m2
}
m1, m2 := m2/1e9, m2%1e9
m0, m1 := m1/1e9, m1%1e9
var buf []byte
buf = append(buf, " m="...)
......
......@@ -5,7 +5,7 @@
package time_test
import (
"regexp"
"strings"
"testing"
. "time"
)
......@@ -231,22 +231,28 @@ func TestMonotonicOverflow(t *testing.T) {
}
}
func TestMonotonicString(t *testing.T) {
t1 := Now()
re := regexp.MustCompile(` m=\+[0-9]+\.[0-9]{9}$`)
if !re.MatchString(t1.String()) {
t.Errorf("Now().String() = %q, want match for /%s/", t1.String(), re)
}
t2 := Now().Add(-5 * Hour)
re = regexp.MustCompile(` m=-[0-9]+\.[0-9]{9}$`)
if !re.MatchString(t2.String()) {
t.Errorf("Now().Add(-5*Hour).String() = %q, want match for /%s/", t2.String(), re)
}
var monotonicStringTests = []struct {
mono int64
want string
}{
{0, "m=+0.000000000"},
{123456789, "m=+0.123456789"},
{-123456789, "m=-0.123456789"},
{123456789000, "m=+123.456789000"},
{-123456789000, "m=-123.456789000"},
{9e18, "m=+9000000000.000000000"},
{-9e18, "m=-9000000000.000000000"},
{-1 << 63, "m=-9223372036.854775808"},
}
t3 := Now().Add(1.2e18)
re = regexp.MustCompile(` m=\+120[0-9]{7}\.[0-9]{9}$`)
if !re.MatchString(t3.String()) {
t.Errorf("Now().Add(12e17).String() = %q, want match for /%s/", t3.String(), re)
func TestMonotonicString(t *testing.T) {
for _, tt := range monotonicStringTests {
t1 := Now()
SetMono(&t1, tt.mono)
s := t1.String()
got := s[strings.LastIndex(s, " ")+1:]
if got != tt.want {
t.Errorf("with mono=%d: got %q; want %q", tt.mono, got, tt.want)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment