math/big: permit passing of (possibly nil) *Float to MantExp to avoid allocation

Change-Id: Ia92eea833283f8b16fa09d4ca1c9cb3bc0eb18a2
Reviewed-on: https://go-review.googlesource.com/5870
Reviewed-by: Rob Pike <r@golang.org>
diff --git a/src/math/big/float.go b/src/math/big/float.go
index 015f164..60e9a2d 100644
--- a/src/math/big/float.go
+++ b/src/math/big/float.go
@@ -203,6 +203,8 @@
 // It returns mant and exp satisfying x == mant × 2**exp, with
 // the absolute value of mant satisfying 0.5 <= |mant| < 1.0.
 // mant has the same precision and rounding mode as x.
+// If a non-nil *Float argument z is provided it is used to
+// store the result mant; otherwise a new Float is allocated.
 //
 // Special cases are:
 //
@@ -210,11 +212,14 @@
 //	(±Inf).MantExp() = ±Inf, 0
 //
 // MantExp does not modify x; the result mant is a new Float.
-func (x *Float) MantExp() (mant *Float, exp int) {
-	mant = new(Float).Copy(x)
+func (x *Float) MantExp(z *Float) (mant *Float, exp int) {
+	if z == nil {
+		z = new(Float)
+	}
+	mant = z.Copy(x)
 	if x.exp != infExp {
-		mant.exp = 0
 		exp = int(x.exp)
+		mant.exp = 0 // after reading x.exp (x and mant may be aliases)
 	}
 	return
 }
diff --git a/src/math/big/float_test.go b/src/math/big/float_test.go
index 00bb309..f7c243e 100644
--- a/src/math/big/float_test.go
+++ b/src/math/big/float_test.go
@@ -147,13 +147,24 @@
 	} {
 		x := makeFloat(test.x)
 		frac := makeFloat(test.frac)
-		f, e := x.MantExp()
+		f, e := x.MantExp(nil)
 		if !feq(f, frac) || e != test.exp {
 			t.Errorf("%s.MantExp() = %s, %d; want %s, %d", test.x, f.Format('g', 10), e, test.frac, test.exp)
 		}
 	}
 }
 
+func TestFloatMantExpAliasing(t *testing.T) {
+	x := makeFloat("0.5p10")
+	z := new(Float)
+	if m, _ := x.MantExp(z); m != z {
+		t.Fatalf("MantExp didn't use supplied *Float")
+	}
+	if _, e := x.MantExp(x); e != 10 {
+		t.Fatalf("MantExp aliasing error: got %d; want 10", e)
+	}
+}
+
 func TestFloatSetMantExp(t *testing.T) {
 	for _, test := range []struct {
 		frac string
@@ -185,7 +196,7 @@
 			t.Errorf("SetMantExp(%s, %d) = %s; want %s", test.frac, test.exp, z.Format('g', 10), test.z)
 		}
 		// test inverse property
-		if z.SetMantExp(want.MantExp()).Cmp(want) != 0 {
+		if z.SetMantExp(want.MantExp(nil)).Cmp(want) != 0 {
 			t.Errorf("Inverse property not satisfied: got %s; want %s", z.Format('g', 10), test.z)
 		}
 	}