integer.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package math
  17. import "strconv"
  18. const (
  19. // Integer limit values.
  20. MaxInt8 = 1<<7 - 1
  21. MinInt8 = -1 << 7
  22. MaxInt16 = 1<<15 - 1
  23. MinInt16 = -1 << 15
  24. MaxInt32 = 1<<31 - 1
  25. MinInt32 = -1 << 31
  26. MaxInt64 = 1<<63 - 1
  27. MinInt64 = -1 << 63
  28. MaxUint8 = 1<<8 - 1
  29. MaxUint16 = 1<<16 - 1
  30. MaxUint32 = 1<<32 - 1
  31. MaxUint64 = 1<<64 - 1
  32. )
  33. // ParseUint64 parses s as an integer in decimal or hexadecimal syntax.
  34. // Leading zeros are accepted. The empty string parses as zero.
  35. func ParseUint64(s string) (uint64, bool) {
  36. if s == "" {
  37. return 0, true
  38. }
  39. if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
  40. v, err := strconv.ParseUint(s[2:], 16, 64)
  41. return v, err == nil
  42. }
  43. v, err := strconv.ParseUint(s, 10, 64)
  44. return v, err == nil
  45. }
  46. // MustParseUint64 parses s as an integer and panics if the string is invalid.
  47. func MustParseUint64(s string) uint64 {
  48. v, ok := ParseUint64(s)
  49. if !ok {
  50. panic("invalid unsigned 64 bit integer: " + s)
  51. }
  52. return v
  53. }
  54. // NOTE: The following methods need to be optimised using either bit checking or asm
  55. // SafeSub returns subtraction result and whether overflow occurred.
  56. func SafeSub(x, y uint64) (uint64, bool) {
  57. return x - y, x < y
  58. }
  59. // SafeAdd returns the result and whether overflow occurred.
  60. func SafeAdd(x, y uint64) (uint64, bool) {
  61. return x + y, y > MaxUint64-x
  62. }
  63. // SafeMul returns multiplication result and whether overflow occurred.
  64. func SafeMul(x, y uint64) (uint64, bool) {
  65. if x == 0 || y == 0 {
  66. return 0, false
  67. }
  68. return x * y, y > MaxUint64/x
  69. }