Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

decimal: Remove unnecessary allocation in bankers round chop #2030

Merged
merged 1 commit into from
Aug 15, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions types/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ func (d Dec) ToLeftPaddedWithDecimals(totalDigits int8) string {
// TODO panic if negative or if totalDigits < len(initStr)???
// evaluate as an integer and return left padded string
func (d Dec) ToLeftPadded(totalDigits int8) string {
chopped := chopPrecisionAndRound(d.Int)
chopped := chopPrecisionAndRoundNonMutative(d.Int)
intStr := chopped.String()
fcode := `%0` + strconv.Itoa(int(totalDigits)) + `s`
return fmt.Sprintf(fcode, intStr)
Expand All @@ -268,9 +268,7 @@ func (d Dec) ToLeftPadded(totalDigits int8) string {
// Remove a Precision amount of rightmost digits and perform bankers rounding
// on the remainder (gaussian rounding) on the digits which have been removed.
//
// TODO We should make this function mutate the input. The functions here
// don't need to allocate different memory for chopped after computing the
// result
// Mutates the input. Use the non-mutative version if that is undesired
func chopPrecisionAndRound(d *big.Int) *big.Int {

// remove the negative and add it back when returning
Expand All @@ -283,7 +281,7 @@ func chopPrecisionAndRound(d *big.Int) *big.Int {
}

// get the trucated quotient and remainder
quo, rem := big.NewInt(0), big.NewInt(0)
quo, rem := d, big.NewInt(0)
quo, rem = quo.QuoRem(d, precisionReuse, rem)

if rem.Sign() == 0 { // remainder is zero
Expand All @@ -304,9 +302,14 @@ func chopPrecisionAndRound(d *big.Int) *big.Int {
}
}

func chopPrecisionAndRoundNonMutative(d *big.Int) *big.Int {
tmp := new(big.Int).Set(d)
return chopPrecisionAndRound(tmp)
}

// RoundInt64 rounds the decimal using bankers rounding
func (d Dec) RoundInt64() int64 {
chopped := chopPrecisionAndRound(d.Int)
chopped := chopPrecisionAndRoundNonMutative(d.Int)
if !chopped.IsInt64() {
panic("Int64() out of bound")
}
Expand All @@ -315,7 +318,7 @@ func (d Dec) RoundInt64() int64 {

// RoundInt round the decimal using bankers rounding
func (d Dec) RoundInt() Int {
return NewIntFromBigInt(chopPrecisionAndRound(d.Int))
return NewIntFromBigInt(chopPrecisionAndRoundNonMutative(d.Int))
}

//___________________________________________________________________________________
Expand Down