int.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package strconv // import "github.com/tdewolff/parse/strconv"
  2. import (
  3. "math"
  4. )
  5. // Int 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. n := uint64(0)
  15. for i < len(b) {
  16. c := b[i]
  17. if n > math.MaxUint64/10 {
  18. return 0, 0
  19. } else if c >= '0' && c <= '9' {
  20. n *= 10
  21. n += uint64(c - '0')
  22. } else {
  23. break
  24. }
  25. i++
  26. }
  27. if !neg && n > uint64(math.MaxInt64) || n > uint64(math.MaxInt64)+1 {
  28. return 0, 0
  29. } else if neg {
  30. return -int64(n), i
  31. }
  32. return int64(n), i
  33. }
  34. func LenInt(i int64) int {
  35. if i < 0 {
  36. if i == -9223372036854775808 {
  37. return 19
  38. }
  39. i = -i
  40. }
  41. switch {
  42. case i < 10:
  43. return 1
  44. case i < 100:
  45. return 2
  46. case i < 1000:
  47. return 3
  48. case i < 10000:
  49. return 4
  50. case i < 100000:
  51. return 5
  52. case i < 1000000:
  53. return 6
  54. case i < 10000000:
  55. return 7
  56. case i < 100000000:
  57. return 8
  58. case i < 1000000000:
  59. return 9
  60. case i < 10000000000:
  61. return 10
  62. case i < 100000000000:
  63. return 11
  64. case i < 1000000000000:
  65. return 12
  66. case i < 10000000000000:
  67. return 13
  68. case i < 100000000000000:
  69. return 14
  70. case i < 1000000000000000:
  71. return 15
  72. case i < 10000000000000000:
  73. return 16
  74. case i < 100000000000000000:
  75. return 17
  76. case i < 1000000000000000000:
  77. return 18
  78. }
  79. return 19
  80. }