From 5ee2290420889281637b536473a9a51ffd63dda4 Mon Sep 17 00:00:00 2001 From: Brian Kessler Date: Thu, 31 Jan 2019 22:28:21 -0700 Subject: [PATCH] math/big: implement Rat.SetUint64 Implemented via the underlying Int.SetUint64. Added tests for Rat.SetInt64 and Rat.SetUint64. Fixes #29579 Change-Id: I03faaffc93e36873b202b58ae72b139dea5c40f9 Reviewed-on: https://go-review.googlesource.com/c/go/+/160682 Run-TryBot: Robert Griesemer TryBot-Result: Gobot Gobot Reviewed-by: Robert Griesemer --- src/math/big/rat.go | 7 ++++++ src/math/big/rat_test.go | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/math/big/rat.go b/src/math/big/rat.go index 5d0800ca93..675889f33b 100644 --- a/src/math/big/rat.go +++ b/src/math/big/rat.go @@ -339,6 +339,13 @@ func (z *Rat) SetInt64(x int64) *Rat { return z } +// SetUint64 sets z to x and returns z. +func (z *Rat) SetUint64(x uint64) *Rat { + z.a.SetUint64(x) + z.b.abs = z.b.abs[:0] + return z +} + // Set sets z to x (by making a copy of x) and returns z. func (z *Rat) Set(x *Rat) *Rat { if z != x { diff --git a/src/math/big/rat_test.go b/src/math/big/rat_test.go index afda68658f..b169477e23 100644 --- a/src/math/big/rat_test.go +++ b/src/math/big/rat_test.go @@ -620,3 +620,54 @@ func TestIsFinite(t *testing.T) { } } } + +func TestRatSetInt64(t *testing.T) { + var testCases = []int64{ + 0, + 1, + -1, + 12345, + -98765, + math.MaxInt64, + math.MinInt64, + } + var r = new(Rat) + for i, want := range testCases { + r.SetInt64(want) + if !r.IsInt() { + t.Errorf("#%d: Rat.SetInt64(%d) is not an integer", i, want) + } + num := r.Num() + if !num.IsInt64() { + t.Errorf("#%d: Rat.SetInt64(%d) numerator is not an int64", i, want) + } + got := num.Int64() + if got != want { + t.Errorf("#%d: Rat.SetInt64(%d) = %d, but expected %d", i, want, got, want) + } + } +} + +func TestRatSetUint64(t *testing.T) { + var testCases = []uint64{ + 0, + 1, + 12345, + ^uint64(0), + } + var r = new(Rat) + for i, want := range testCases { + r.SetUint64(want) + if !r.IsInt() { + t.Errorf("#%d: Rat.SetUint64(%d) is not an integer", i, want) + } + num := r.Num() + if !num.IsUint64() { + t.Errorf("#%d: Rat.SetUint64(%d) numerator is not a uint64", i, want) + } + got := num.Uint64() + if got != want { + t.Errorf("#%d: Rat.SetUint64(%d) = %d, but expected %d", i, want, got, want) + } + } +} -- 2.50.0