Skip to content

Commit

Permalink
Fix integer overflow handling in parseUintBuf() (#789)
Browse files Browse the repository at this point in the history
* Add more tests for parseUintBuf()

* Fix integer overflow handling in parseUintBuf()
  • Loading branch information
im-0 committed Apr 23, 2020
1 parent 571315f commit 3e27d8e
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 3 additions & 2 deletions bytesconv.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,11 +185,12 @@ func parseUintBuf(b []byte) (int, int, error) {
}
return v, i, nil
}
vNew := 10*v + int(k)
// Test for overflow.
if v*10 < v {
if vNew < v {
return -1, i, errTooLongInt
}
v = 10*v + int(k)
v = vNew
}
return v, n, nil
}
Expand Down
12 changes: 12 additions & 0 deletions bytesconv_32_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,22 @@ func TestReadHexIntSuccess(t *testing.T) {
testReadHexIntSuccess(t, "1234ZZZ", 0x1234)
}

func TestParseUintError32(t *testing.T) {
t.Parallel()

// Overflow by last digit: 2 ** 32 / 2 * 10 ** n
testParseUintError(t, "2147483648")
testParseUintError(t, "21474836480")
testParseUintError(t, "214748364800")
}

func TestParseUintSuccess(t *testing.T) {
t.Parallel()

testParseUintSuccess(t, "0", 0)
testParseUintSuccess(t, "123", 123)
testParseUintSuccess(t, "123456789", 123456789)

// Max supported value: 2 ** 32 / 2 - 1
testParseUintSuccess(t, "2147483647", 2147483647)
}
11 changes: 11 additions & 0 deletions bytesconv_64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,23 @@ func TestReadHexIntSuccess(t *testing.T) {
testReadHexIntSuccess(t, "7ffffffffffffff", 0x7ffffffffffffff)
}

func TestParseUintError64(t *testing.T) {
t.Parallel()

// Overflow by last digit: 2 ** 64 / 2 * 10 ** n
testParseUintError(t, "9223372036854775808")
testParseUintError(t, "92233720368547758080")
testParseUintError(t, "922337203685477580800")
}

func TestParseUintSuccess(t *testing.T) {
t.Parallel()

testParseUintSuccess(t, "0", 0)
testParseUintSuccess(t, "123", 123)
testParseUintSuccess(t, "1234567890", 1234567890)
testParseUintSuccess(t, "123456789012345678", 123456789012345678)

// Max supported value: 2 ** 64 / 2 - 1
testParseUintSuccess(t, "9223372036854775807", 9223372036854775807)
}

0 comments on commit 3e27d8e

Please sign in to comment.