int.go 1.3 KB

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