Skip to content

Commit

Permalink
util/types: fix floatStrToIntStr, handle large exponent corner case. (p…
Browse files Browse the repository at this point in the history
  • Loading branch information
coocood authored and hanfei1991 committed Dec 8, 2016
1 parent b134396 commit 7e61f16
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
11 changes: 10 additions & 1 deletion util/types/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ func floatStrToIntStr(validFloat string) (string, error) {
if err != nil {
return validFloat, errors.Trace(err)
}
if exp > 0 && intCnt > (math.MaxInt64-exp) {
// (exp + incCnt) overflows MaxInt64.
return validFloat, errors.Trace(ErrOverflow)
}
intCnt += exp
}
if intCnt <= 0 {
Expand All @@ -216,7 +220,12 @@ func floatStrToIntStr(validFloat string) (string, error) {
if intCnt <= len(digits) {
validInt = string(digits[:intCnt])
} else {
validInt = string(digits) + strings.Repeat("0", intCnt-len(digits))
extraZeroCount := intCnt - len(digits)
if extraZeroCount > 20 {
// Return overflow to avoid allocating too much memory.
return validFloat, errors.Trace(ErrOverflow)
}
validInt = string(digits) + strings.Repeat("0", extraZeroCount)
}
return validInt, nil
}
Expand Down
4 changes: 4 additions & 0 deletions util/types/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -644,4 +644,8 @@ func (s *testTypeConvertSuite) TestGetValidFloat(c *C) {
_, err := strconv.ParseFloat(prefix, 64)
c.Assert(err, IsNil)
}
_, err := floatStrToIntStr("1e9223372036854775807")
c.Assert(terror.ErrorEqual(err, ErrOverflow), IsTrue)
_, err = floatStrToIntStr("1e21")
c.Assert(terror.ErrorEqual(err, ErrOverflow), IsTrue)
}

0 comments on commit 7e61f16

Please sign in to comment.