github.com/go-chrono/chrono@v0.0.0-20240102183611-532f0d0d7c34/utils.go (about) 1 package chrono 2 3 import "math" 4 5 // addInt64 attempts to add v1 to v2 but reports if the operation would underflow or overflow int64. 6 func addInt64(v1, v2 int64) (sum int64, underflows, overflows bool) { 7 if v2 > 0 { 8 v := math.MaxInt64 - v1 9 if v < 0 { 10 v = -v 11 } 12 13 if v < v2 { 14 return 0, false, true 15 } 16 } else if v2 < 0 { 17 v := math.MinInt64 + v1 18 if v < 0 { 19 v = -v 20 } 21 22 if -v > v2 { // v < -v2 can't be used because -math.MinInt64 > math.MaxInt64 23 return 0, true, false 24 } 25 } 26 return v1 + v2, false, false 27 } 28 29 // divideAndRoundInt divides x by y, then rounds the result to the nearest multiple of y, either up or down. 30 func divideAndRoundInt(x, y int) int { 31 r := x % y 32 if r >= (y / 2) { 33 return (x - r + y) / y 34 } 35 return (x - r) / y 36 }