Skip to content

Commit 2aa01af

Browse files
committed
fix overflow check for integer multiplication
1 parent 5ae61d1 commit 2aa01af

File tree

2 files changed

+23
-8
lines changed

2 files changed

+23
-8
lines changed

internal/types/numeric.go

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,27 @@ type Integral interface {
3838
}
3939

4040
func isMulOverflow[T int32 | int64](left, right, min, max T) bool {
41-
if right > 0 {
42-
if left > max/right {
43-
return true
44-
}
45-
} else {
46-
if left < min/right {
47-
return true
41+
// zero multiplication cannot overflow
42+
if left == 0 || right == 0 {
43+
return false
44+
}
45+
46+
if left > 0 {
47+
if right > 0 {
48+
// both positive: overflow if left > max / right
49+
return left > max/right
4850
}
51+
// left > 0, right < 0: product negative. overflow if left > min / right
52+
return left > min/right
4953
}
5054

51-
return false
55+
// left < 0
56+
if right > 0 {
57+
// left < 0, right > 0: product negative. overflow if left < min / right
58+
return left < min/right
59+
}
60+
// both negative: product positive. overflow if left < max / right
61+
return left < max/right
5262
}
5363

5464
func isAddOverflow[T int32 | int64](left, right, min, max T) bool {

sqltests/expr/arithmetic.sql

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,11 @@ NULL
9696
> 4.5 + 4.5
9797
9.0
9898

99+
> 10 * -10
100+
-100
101+
102+
> 10 + -10
103+
99104
! 1000000000 * 1000000000
100105

101106
! 1000000000000000000 * 1000000000000000000 * 1000000000000000000

0 commit comments

Comments
 (0)