]> Cypherpunks.ru repositories - gostls13.git/commitdiff
time: add Duration.Abs
authorCarl Johnson <me@carlmjohnson.net>
Sat, 26 Mar 2022 02:10:29 +0000 (02:10 +0000)
committerEmmanuel Odeke <emmanuel@orijtech.com>
Sun, 27 Mar 2022 20:23:17 +0000 (20:23 +0000)
Fixes #51414

Change-Id: Ia3b1674f2a902c8396fe029397536643a3bc1784
GitHub-Last-Rev: 67159648af09e7a8ac2825a1fe71b2de3fb9d748
GitHub-Pull-Request: golang/go#51739
Reviewed-on: https://go-review.googlesource.com/c/go/+/393515
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
api/next/51414.txt [new file with mode: 0644]
src/time/time.go
src/time/time_test.go

diff --git a/api/next/51414.txt b/api/next/51414.txt
new file mode 100644 (file)
index 0000000..7491285
--- /dev/null
@@ -0,0 +1 @@
+pkg time, method (Duration) Abs() Duration #51414
index 8046ff508b6b4fc7a77258e23e241da8d1c40389..d77074c5c27572a796cc8c5e6fbe9b7f9918903a 100644 (file)
@@ -815,6 +815,19 @@ func (d Duration) Round(m Duration) Duration {
        return maxDuration // overflow
 }
 
+// Abs returns the absolute value of d.
+// As a special case, math.MinInt64 is converted to math.MaxInt64.
+func (d Duration) Abs() Duration {
+       switch {
+       case d >= 0:
+               return d
+       case d == minDuration:
+               return maxDuration
+       default:
+               return -d
+       }
+}
+
 // Add returns the time t+d.
 func (t Time) Add(d Duration) Time {
        dsec := int64(d / 1e9)
index ea13ffe3c9470dc5d90c5936b6374855d8f158d2..1701401ab4ba893231430f29bff0865681055284 100644 (file)
@@ -1240,6 +1240,30 @@ func TestDurationRound(t *testing.T) {
        }
 }
 
+var durationAbsTests = []struct {
+       d    Duration
+       want Duration
+}{
+       {0, 0},
+       {1, 1},
+       {-1, 1},
+       {1 * Minute, 1 * Minute},
+       {-1 * Minute, 1 * Minute},
+       {minDuration, maxDuration},
+       {minDuration + 1, maxDuration},
+       {minDuration + 2, maxDuration - 1},
+       {maxDuration, maxDuration},
+       {maxDuration - 1, maxDuration - 1},
+}
+
+func TestDurationAbs(t *testing.T) {
+       for _, tt := range durationAbsTests {
+               if got := tt.d.Abs(); got != tt.want {
+                       t.Errorf("Duration(%s).Abs() = %s; want: %s", tt.d, got, tt.want)
+               }
+       }
+}
+
 var defaultLocTests = []struct {
        name string
        f    func(t1, t2 Time) bool