github.com/algorand/go-algorand-sdk@v1.24.0/types/overflow.go (about)

     1  package types
     2  
     3  // Overflow provides a set of helper function to prevent overflows
     4  
     5  // OAdd16 adds 2 uint16 values with overflow detection
     6  func OAdd16(a uint16, b uint16) (res uint16, overflowed bool) {
     7  	res = a + b
     8  	overflowed = res < a
     9  	return
    10  }
    11  
    12  // OAdd adds 2 values with overflow detection
    13  func OAdd(a uint64, b uint64) (res uint64, overflowed bool) {
    14  	res = a + b
    15  	overflowed = res < a
    16  	return
    17  }
    18  
    19  // OSub subtracts b from a with overflow detection
    20  func OSub(a uint64, b uint64) (res uint64, overflowed bool) {
    21  	res = a - b
    22  	overflowed = res > a
    23  	return
    24  }
    25  
    26  // OMul multiplies 2 values with overflow detection
    27  func OMul(a uint64, b uint64) (res uint64, overflowed bool) {
    28  	if b == 0 {
    29  		return 0, false
    30  	}
    31  
    32  	c := a * b
    33  	if c/b != a {
    34  		return 0, true
    35  	}
    36  	return c, false
    37  }