aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoe Tsai <thebrokentoaster@gmail.com>2019-08-16 03:16:34 +0000
committerJoe Tsai <thebrokentoaster@gmail.com>2019-08-16 17:01:35 +0000
commit4983a0b75b40448d3245811ddcf682a9c86fc975 (patch)
tree23637e943df3fea232fe103458d0beb6f488890b
parent0212f0410f845815f5327a7f2e705891a9598f3d (diff)
downloadgo-4983a0b75b40448d3245811ddcf682a9c86fc975.tar.gz
go-4983a0b75b40448d3245811ddcf682a9c86fc975.zip
Revert "time: optimize Sub"
This reverts commit CL 131196 because there is a bug in the calculation of nanoseconds. Fixes #33677 Change-Id: Ic8e94c547ee29b8aeda1b9a5cb9764dbf47b14b4 Reviewed-on: https://go-review.googlesource.com/c/go/+/190497 Run-TryBot: Andrew Bonventre <andybons@golang.org> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com> Reviewed-by: Andrew Bonventre <andybons@golang.org>
-rw-r--r--src/time/time.go33
-rw-r--r--src/time/time_test.go10
2 files changed, 9 insertions, 34 deletions
diff --git a/src/time/time.go b/src/time/time.go
index c8116a74f4..0d1cb9e5a1 100644
--- a/src/time/time.go
+++ b/src/time/time.go
@@ -906,33 +906,16 @@ func (t Time) Sub(u Time) Duration {
}
return d
}
-
- ts, us := t.sec(), u.sec()
-
- var sec, nsec, d int64
-
- ssub := ts - us
- if (ssub < ts) != (us > 0) {
- goto overflow
- }
-
- if ssub < int64(minDuration/Second) || ssub > int64(maxDuration/Second) {
- goto overflow
- }
- sec = ssub * int64(Second)
-
- nsec = int64(t.nsec() - u.nsec())
- d = sec + nsec
- if (d > sec) != (nsec > 0) {
- goto overflow
- }
- return Duration(d)
-
-overflow:
- if t.Before(u) {
+ d := Duration(t.sec()-u.sec())*Second + Duration(t.nsec()-u.nsec())
+ // Check for overflow or underflow.
+ switch {
+ case u.Add(d).Equal(t):
+ return d // d is correct
+ case t.Before(u):
return minDuration // t - u is negative out of range
+ default:
+ return maxDuration // t - u is positive out of range
}
- return maxDuration // t - u is positive out of range
}
// Since returns the time elapsed since t.
diff --git a/src/time/time_test.go b/src/time/time_test.go
index dd3a8160cd..0ac3c3a27f 100644
--- a/src/time/time_test.go
+++ b/src/time/time_test.go
@@ -690,7 +690,7 @@ var gobTests = []Time{
Date(0, 1, 2, 3, 4, 5, 6, UTC),
Date(7, 8, 9, 10, 11, 12, 13, FixedZone("", 0)),
Unix(81985467080890095, 0x76543210), // Time.sec: 0x0123456789ABCDEF
- {}, // nil location
+ {}, // nil location
Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", 32767*60)),
Date(1, 2, 3, 4, 5, 6, 7, FixedZone("", -32768*60)),
}
@@ -1008,14 +1008,6 @@ func TestSub(t *testing.T) {
}
}
-func BenchmarkSub(b *testing.B) {
- for i := 0; i < b.N; i++ {
- for _, st := range subTests {
- st.t.Sub(st.u)
- }
- }
-}
-
var nsDurationTests = []struct {
d Duration
want int64