You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.4 KiB

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