int.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package strconv
  2. import (
  3. "math"
  4. )
  5. // ParseInt parses a byte-slice and returns the integer it represents.
  6. // If an invalid character is encountered, it will stop there.
  7. func ParseInt(b []byte) (int64, int) {
  8. i := 0
  9. neg := false
  10. if len(b) > 0 && (b[0] == '+' || b[0] == '-') {
  11. neg = b[0] == '-'
  12. i++
  13. }
  14. start := i
  15. n := uint64(0)
  16. for i < len(b) {
  17. c := b[i]
  18. if '0' <= c && c <= '9' {
  19. if uint64(-math.MinInt64)/10 < n || uint64(-math.MinInt64)-uint64(c-'0') < n*10 {
  20. return 0, 0
  21. }
  22. n *= 10
  23. n += uint64(c - '0')
  24. } else {
  25. break
  26. }
  27. i++
  28. }
  29. if i == start {
  30. return 0, 0
  31. }
  32. if !neg && uint64(math.MaxInt64) < n {
  33. return 0, 0
  34. } else if neg {
  35. return -int64(n), i
  36. }
  37. return int64(n), i
  38. }
  39. // ParseUint parses a byte-slice and returns the integer it represents.
  40. // If an invalid character is encountered, it will stop there.
  41. func ParseUint(b []byte) (uint64, int) {
  42. i := 0
  43. n := uint64(0)
  44. for i < len(b) {
  45. c := b[i]
  46. if '0' <= c && c <= '9' {
  47. if math.MaxUint64/10 < n || math.MaxUint64-uint64(c-'0') < n*10 {
  48. return 0, 0
  49. }
  50. n *= 10
  51. n += uint64(c - '0')
  52. } else {
  53. break
  54. }
  55. i++
  56. }
  57. return n, i
  58. }
  59. // LenInt returns the written length of an integer.
  60. func LenInt(i int64) int {
  61. if i < 0 {
  62. if i == -9223372036854775808 {
  63. return 19
  64. }
  65. i = -i
  66. }
  67. return LenUint(uint64(i))
  68. }
  69. func LenUint(i uint64) int {
  70. switch {
  71. case i < 10:
  72. return 1
  73. case i < 100:
  74. return 2
  75. case i < 1000:
  76. return 3
  77. case i < 10000:
  78. return 4
  79. case i < 100000:
  80. return 5
  81. case i < 1000000:
  82. return 6
  83. case i < 10000000:
  84. return 7
  85. case i < 100000000:
  86. return 8
  87. case i < 1000000000:
  88. return 9
  89. case i < 10000000000:
  90. return 10
  91. case i < 100000000000:
  92. return 11
  93. case i < 1000000000000:
  94. return 12
  95. case i < 10000000000000:
  96. return 13
  97. case i < 100000000000000:
  98. return 14
  99. case i < 1000000000000000:
  100. return 15
  101. case i < 10000000000000000:
  102. return 16
  103. case i < 100000000000000000:
  104. return 17
  105. case i < 1000000000000000000:
  106. return 18
  107. case i < 10000000000000000000:
  108. return 19
  109. }
  110. return 20
  111. }