github.com/ari-anchor/sei-tendermint@v0.0.0-20230519144642-dc826b7b56bb/libs/math/safemath.go (about)

     1  package math
     2  
     3  import (
     4  	"errors"
     5  	"math"
     6  )
     7  
     8  var ErrOverflowInt32 = errors.New("int32 overflow")
     9  var ErrOverflowUint8 = errors.New("uint8 overflow")
    10  var ErrOverflowInt8 = errors.New("int8 overflow")
    11  
    12  // SafeAddInt32 adds two int32 integers.
    13  func SafeAddInt32(a, b int32) (int32, error) {
    14  	if b > 0 && (a > math.MaxInt32-b) {
    15  		return 0, ErrOverflowInt32
    16  	} else if b < 0 && (a < math.MinInt32-b) {
    17  		return 0, ErrOverflowInt32
    18  	}
    19  	return a + b, nil
    20  }
    21  
    22  // SafeSubInt32 subtracts two int32 integers.
    23  func SafeSubInt32(a, b int32) (int32, error) {
    24  	if b > 0 && (a < math.MinInt32+b) {
    25  		return 0, ErrOverflowInt32
    26  	} else if b < 0 && (a > math.MaxInt32+b) {
    27  		return 0, ErrOverflowInt32
    28  	}
    29  	return a - b, nil
    30  }
    31  
    32  // SafeConvertInt32 takes a int and checks if it overflows.
    33  func SafeConvertInt32(a int64) (int32, error) {
    34  	if a > math.MaxInt32 {
    35  		return 0, ErrOverflowInt32
    36  	} else if a < math.MinInt32 {
    37  		return 0, ErrOverflowInt32
    38  	}
    39  	return int32(a), nil
    40  }
    41  
    42  // SafeConvertUint8 takes an int64 and checks if it overflows.
    43  func SafeConvertUint8(a int64) (uint8, error) {
    44  	if a > math.MaxUint8 {
    45  		return 0, ErrOverflowUint8
    46  	} else if a < 0 {
    47  		return 0, ErrOverflowUint8
    48  	}
    49  	return uint8(a), nil
    50  }
    51  
    52  // SafeConvertInt8 takes an int64 and checks if it overflows.
    53  func SafeConvertInt8(a int64) (int8, error) {
    54  	if a > math.MaxInt8 {
    55  		return 0, ErrOverflowInt8
    56  	} else if a < math.MinInt8 {
    57  		return 0, ErrOverflowInt8
    58  	}
    59  	return int8(a), nil
    60  }