integer.go 606 B

12345678910111213141516171819202122232425
  1. package math
  2. import gmath "math"
  3. /*
  4. * NOTE: The following methods need to be optimised using either bit checking or asm
  5. */
  6. // SafeSub returns subtraction result and whether overflow occurred.
  7. func SafeSub(x, y uint64) (uint64, bool) {
  8. return x - y, x < y
  9. }
  10. // SafeAdd returns the result and whether overflow occurred.
  11. func SafeAdd(x, y uint64) (uint64, bool) {
  12. return x + y, y > gmath.MaxUint64-x
  13. }
  14. // SafeMul returns multiplication result and whether overflow occurred.
  15. func SafeMul(x, y uint64) (uint64, bool) {
  16. if x == 0 || y == 0 {
  17. return 0, false
  18. }
  19. return x * y, y > gmath.MaxUint64/x
  20. }