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.

65 lines
1.6 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. // If there is an overflow this will panic
  11. func SafeAddInt32(a, b int32) int32 {
  12. if b > 0 && (a > math.MaxInt32-b) {
  13. panic(ErrOverflowInt32)
  14. } else if b < 0 && (a < math.MinInt32-b) {
  15. panic(ErrOverflowInt32)
  16. }
  17. return a + b
  18. }
  19. // SafeSubInt32 subtracts two int32 integers
  20. // If there is an overflow this will panic
  21. func SafeSubInt32(a, b int32) int32 {
  22. if b > 0 && (a < math.MinInt32+b) {
  23. panic(ErrOverflowInt32)
  24. } else if b < 0 && (a > math.MaxInt32+b) {
  25. panic(ErrOverflowInt32)
  26. }
  27. return a - b
  28. }
  29. // SafeConvertInt32 takes a int and checks if it overflows
  30. // If there is an overflow this will panic
  31. func SafeConvertInt32(a int64) int32 {
  32. if a > math.MaxInt32 {
  33. panic(ErrOverflowInt32)
  34. } else if a < math.MinInt32 {
  35. panic(ErrOverflowInt32)
  36. }
  37. return int32(a)
  38. }
  39. // SafeConvertUint8 takes an int64 and checks if it overflows
  40. // If there is an overflow it returns an error
  41. func SafeConvertUint8(a int64) (uint8, error) {
  42. if a > math.MaxUint8 {
  43. return 0, ErrOverflowUint8
  44. } else if a < 0 {
  45. return 0, ErrOverflowUint8
  46. }
  47. return uint8(a), nil
  48. }
  49. // SafeConvertInt8 takes an int64 and checks if it overflows
  50. // If there is an overflow it returns an error
  51. func SafeConvertInt8(a int64) (int8, error) {
  52. if a > math.MaxInt8 {
  53. return 0, ErrOverflowInt8
  54. } else if a < math.MinInt8 {
  55. return 0, ErrOverflowInt8
  56. }
  57. return int8(a), nil
  58. }