Skip to content

Commit 0bbd05b

Browse files
earthboundkidodeke-em
authored andcommitted
time: add Duration.Abs
Fixes #51414 Change-Id: Ia3b1674f2a902c8396fe029397536643a3bc1784 GitHub-Last-Rev: 6715964 GitHub-Pull-Request: #51739 Reviewed-on: https://go-review.googlesource.com/c/go/+/393515 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Emmanuel Odeke <[email protected]>
1 parent 737837c commit 0bbd05b

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

api/next/51414.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg time, method (Duration) Abs() Duration #51414

src/time/time.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,19 @@ func (d Duration) Round(m Duration) Duration {
815815
return maxDuration // overflow
816816
}
817817

818+
// Abs returns the absolute value of d.
819+
// As a special case, math.MinInt64 is converted to math.MaxInt64.
820+
func (d Duration) Abs() Duration {
821+
switch {
822+
case d >= 0:
823+
return d
824+
case d == minDuration:
825+
return maxDuration
826+
default:
827+
return -d
828+
}
829+
}
830+
818831
// Add returns the time t+d.
819832
func (t Time) Add(d Duration) Time {
820833
dsec := int64(d / 1e9)

src/time/time_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,6 +1240,30 @@ func TestDurationRound(t *testing.T) {
12401240
}
12411241
}
12421242

1243+
var durationAbsTests = []struct {
1244+
d Duration
1245+
want Duration
1246+
}{
1247+
{0, 0},
1248+
{1, 1},
1249+
{-1, 1},
1250+
{1 * Minute, 1 * Minute},
1251+
{-1 * Minute, 1 * Minute},
1252+
{minDuration, maxDuration},
1253+
{minDuration + 1, maxDuration},
1254+
{minDuration + 2, maxDuration - 1},
1255+
{maxDuration, maxDuration},
1256+
{maxDuration - 1, maxDuration - 1},
1257+
}
1258+
1259+
func TestDurationAbs(t *testing.T) {
1260+
for _, tt := range durationAbsTests {
1261+
if got := tt.d.Abs(); got != tt.want {
1262+
t.Errorf("Duration(%s).Abs() = %s; want: %s", tt.d, got, tt.want)
1263+
}
1264+
}
1265+
}
1266+
12431267
var defaultLocTests = []struct {
12441268
name string
12451269
f func(t1, t2 Time) bool

0 commit comments

Comments
 (0)