-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed
Labels
Milestone
Description
Currently there is no standard, efficient way of detecting overflow/underflow in integer arithmetic.
Everyone has to devise their own functions and algorithms for checking if an overflow/underflow happened, which is tedious and likely to be inefficient.
I propose a new suite of functions in the math package.
Each one would return the result together with a boolean flag set to false when an overflow/underflow took place.
func AddOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Add two integers and detect overflow.
func SubOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Subtract two integers and detect overflow.
func MulOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Multiply two integers and detect overflow.
func DivOverflow[T int | uint | int64 | uint64 | int32 | uint32 | int16 | uint16 | int8 | uint8](i T) (T, bool)
Divide two integers and detect overflow.
Example usage:
import "math"
var a int8 = 127
var b int8 = 1
c, ok := math.AddOverflow(a, b)
// c = -128
// ok = false
a = 25
b = 4
c, ok = math.AddOverflow(a, b)
// c = 29
// ok = trueAnother option would be to enhance the arithmetic operators to optionally allow two return values.
This however would constitute a language change.
var a int8 = 127
var b int8 = 1
c, ok := a + b
// c = -128
// ok = falsemateusz834