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