parseInt parses a decimal representation of an int64 from b. The function is equivalent to calling strconv.ParseInt(string(b), 10, 64) but it prevents Go from making a memory allocation for converting a byte slice to a string (escape analysis fails due to the error returned by strconv.ParseInt). B
(b []byte, t reflect.Type)
| 81 | // Because it only works with base 10 the function is also significantly faster |
| 82 | // than strconv.ParseInt. |
| 83 | func (d decoder) parseInt(b []byte, t reflect.Type) (int64, []byte, error) { |
| 84 | var value int64 |
| 85 | var count int |
| 86 | |
| 87 | if len(b) == 0 { |
| 88 | return 0, b, syntaxError(b, "cannot decode integer from an empty input") |
| 89 | } |
| 90 | |
| 91 | if b[0] == '-' { |
| 92 | const max = math.MinInt64 |
| 93 | const lim = max / 10 |
| 94 | |
| 95 | if len(b) == 1 { |
| 96 | return 0, b, syntaxError(b, "cannot decode integer from '-'") |
| 97 | } |
| 98 | |
| 99 | if len(b) > 2 && b[1] == '0' && '0' <= b[2] && b[2] <= '9' { |
| 100 | return 0, b, syntaxError(b, "invalid leading character '0' in integer") |
| 101 | } |
| 102 | |
| 103 | for _, c := range b[1:] { |
| 104 | if c < '0' || c > '9' { |
| 105 | if count == 0 { |
| 106 | b, err := d.inputError(b, t) |
| 107 | return 0, b, err |
| 108 | } |
| 109 | break |
| 110 | } |
| 111 | |
| 112 | if value < lim { |
| 113 | return 0, b, unmarshalOverflow(b, t) |
| 114 | } |
| 115 | |
| 116 | value *= 10 |
| 117 | x := int64(c - '0') |
| 118 | |
| 119 | if value < (max + x) { |
| 120 | return 0, b, unmarshalOverflow(b, t) |
| 121 | } |
| 122 | |
| 123 | value -= x |
| 124 | count++ |
| 125 | } |
| 126 | |
| 127 | count++ |
| 128 | } else { |
| 129 | if len(b) > 1 && b[0] == '0' && '0' <= b[1] && b[1] <= '9' { |
| 130 | return 0, b, syntaxError(b, "invalid leading character '0' in integer") |
| 131 | } |
| 132 | |
| 133 | for ; count < len(b) && b[count] >= '0' && b[count] <= '9'; count++ { |
| 134 | x := int64(b[count] - '0') |
| 135 | next := value*10 + x |
| 136 | if next < value { |
| 137 | return 0, b, unmarshalOverflow(b, t) |
| 138 | } |
| 139 | value = next |
| 140 | } |
no test coverage detected