Debian Codegraph @

parse.go

raw
1 package utils
2
3 import (
4 "math"
5 "strconv"
6
7 "github.com/gofiber/utils/v2/swar"
8 )
9
10 const (
11 maxUint64Cutoff = math.MaxUint64 / 10
12 maxUint64Cutlim = math.MaxUint64 % 10
13 )
14
15 type Signed interface {
16 ~int | ~int8 | ~int16 | ~int32 | ~int64
17 }
18 type Unsigned interface {
19 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
20 }
21
22 // ParseUint parses a decimal ASCII string or byte slice into a uint64.
23 // It returns the parsed value and nil on success.
24 // If the input contains non-digit characters, it returns 0 and an error.
25 func ParseUint[S byteSeq](s S) (uint64, error) {
26 return parseUnsigned[S, uint64]("ParseUint", s, uint64(math.MaxUint64))
27 }
28
29 // ParseNativeUint parses a decimal ASCII string or byte slice into a uint.
30 func ParseNativeUint[S byteSeq](s S) (uint, error) {
31 return parseUnsigned[S, uint]("ParseNativeUint", s, math.MaxUint)
32 }
33
34 // ParseInt parses a decimal ASCII string or byte slice into an int64.
35 // Returns the parsed value and nil on success, else 0 and an error.
36 func ParseInt[S byteSeq](s S) (int64, error) {
37 if len(s) > 0 && s[0] != '-' && s[0] != '+' && len(s) <= 19 {
38 // At most 19 digits fit here, so two 8-digit SWAR steps plus a
39 // scalar remainder can never overflow before the final range check.
40 // A word with a non-digit lane falls through to the scalar loop,
41 // which reports the syntax error. The body deliberately duplicates
42 // the parseDigitsBig structure: routing through parseDigitsBig
43 // instead costs +22% on the 9-digit shape (benchstat -count=10,
44 // Go 1.25, Apple M2 Pro), mostly digit bookkeeping and the extra
45 // call frame.
46 var n uint64
47 i := 0
48 for ; len(s)-i >= 8; i += 8 {
49 w := swar.Load8(s, i)
50 if !isEightDigits(w) {
51 break
52 }
53 n = n*100000000 + parse8Digits(w)
54 }
55 for ; i < len(s); i++ {
56 c := s[i] - '0'
57 if c > 9 {
58 return 0, &strconv.NumError{Func: "ParseInt", Num: string(s), Err: strconv.ErrSyntax}
59 }
60 n = n*10 + uint64(c)
61 }
62 if n > uint64(math.MaxInt64) {
63 return 0, &strconv.NumError{Func: "ParseInt", Num: string(s), Err: strconv.ErrRange}
64 }
65 return int64(n), nil
66 }
67
68 return parseSigned[S, int64]("ParseInt", s, math.MinInt64, math.MaxInt64)
69 }
70
71 // ParseNativeInt parses a decimal ASCII string or byte slice into an int.
72 func ParseNativeInt[S byteSeq](s S) (int, error) {
73 return parseSigned[S, int]("ParseNativeInt", s, math.MinInt, math.MaxInt)
74 }
75
76 // ParseInt32 parses a decimal ASCII string or byte slice into an int32.
77 func ParseInt32[S byteSeq](s S) (int32, error) {
78 return parseSigned[S, int32]("ParseInt32", s, math.MinInt32, math.MaxInt32)
79 }
80
81 // ParseInt16 parses a decimal ASCII string or byte slice into an int16.
82 func ParseInt16[S byteSeq](s S) (int16, error) {
83 return parseSigned[S, int16]("ParseInt16", s, math.MinInt16, math.MaxInt16)
84 }
85
86 // ParseInt8 parses a decimal ASCII string or byte slice into an int8.
87 func ParseInt8[S byteSeq](s S) (int8, error) {
88 if len(s) == 0 {
89 return 0, &strconv.NumError{Func: "ParseInt8", Num: "", Err: strconv.ErrSyntax}
90 }
91
92 neg := false
93 i := 0
94 switch s[0] {
95 case '-':
96 neg = true
97 i++
98 case '+':
99 i++
100 }
101 if i == len(s) {
102 return 0, &strconv.NumError{Func: "ParseInt8", Num: string(s), Err: strconv.ErrSyntax}
103 }
104
105 if len(s)-i <= 3 {
106 var n uint16
107 for ; i < len(s); i++ {
108 c := s[i] - '0'
109 if c > 9 {
110 return 0, &strconv.NumError{Func: "ParseInt8", Num: string(s), Err: strconv.ErrSyntax}
111 }
112 n = n*10 + uint16(c)
113 }
114 if neg {
115 if n > 128 {
116 return 0, &strconv.NumError{Func: "ParseInt8", Num: string(s), Err: strconv.ErrRange}
117 }
118 if n == 128 {
119 return math.MinInt8, nil
120 }
121 return -int8(n), nil
122 }
123 if n > math.MaxInt8 {
124 return 0, &strconv.NumError{Func: "ParseInt8", Num: string(s), Err: strconv.ErrRange}
125 }
126 return int8(n), nil
127 }
128
129 return parseSigned[S, int8]("ParseInt8", s, math.MinInt8, math.MaxInt8)
130 }
131
132 // ParseUint32 parses a decimal ASCII string or byte slice into a uint32.
133 func ParseUint32[S byteSeq](s S) (uint32, error) {
134 return parseUnsigned[S, uint32]("ParseUint32", s, uint32(math.MaxUint32))
135 }
136
137 // ParseUint16 parses a decimal ASCII string or byte slice into a uint16.
138 func ParseUint16[S byteSeq](s S) (uint16, error) {
139 return parseUnsigned[S, uint16]("ParseUint16", s, uint16(math.MaxUint16))
140 }
141
142 // ParseUint8 parses a decimal ASCII string or byte slice into a uint8.
143 func ParseUint8[S byteSeq](s S) (uint8, error) {
144 if len(s) == 0 {
145 return 0, &strconv.NumError{Func: "ParseUint8", Num: "", Err: strconv.ErrSyntax}
146 }
147
148 if len(s) <= 3 {
149 var n uint16
150 for i := range len(s) {
151 c := s[i] - '0'
152 if c > 9 {
153 return 0, &strconv.NumError{Func: "ParseUint8", Num: string(s), Err: strconv.ErrSyntax}
154 }
155 n = n*10 + uint16(c)
156 }
157 if n > math.MaxUint8 {
158 return 0, &strconv.NumError{Func: "ParseUint8", Num: string(s), Err: strconv.ErrRange}
159 }
160 return uint8(n), nil
161 }
162
163 return parseUnsigned[S, uint8]("ParseUint8", s, uint8(math.MaxUint8))
164 }
165
166 // isEightDigits reports whether every lane of w is an ASCII digit ('0'..'9').
167 // High nibbles must all be 3 and low nibbles must not carry past 9 when 6 is
168 // added. A lane >= 0xFA can carry into its neighbor's sum, but such a lane
169 // already fails its own high-nibble test, so the answer stays exact.
170 func isEightDigits(w uint64) bool {
171 const (
172 highNibbles = 0xF0F0F0F0F0F0F0F0
173 sixes = 0x0606060606060606
174 threes = 0x3333333333333333
175 )
176 return (w&highNibbles)|((w+sixes)&highNibbles)>>4 == threes
177 }
178
179 // parse8Digits converts a word of 8 ASCII digit bytes (first digit in lane 0,
180 // most significant) to its numeric value using two pairwise multiply-combine
181 // steps. The caller must have validated that every lane is '0'..'9'.
182 func parse8Digits(w uint64) uint64 {
183 const (
184 pairMask = 0x000000FF000000FF
185 mul1 = 100 + (1000000 << 32)
186 mul2 = 1 + (10000 << 32)
187 )
188 w -= digitZeros
189 w = w*10 + w>>8 // adjacent digit pairs -> 2-digit values in even lanes
190 return ((w&pairMask)*mul1 + (w>>16&pairMask)*mul2) >> 32
191 }
192
193 // parseDigits parses a run of fewer than 8 digits and returns the uint64
194 // value, or an error on the first non-digit. Callers must route runs of 8+
195 // bytes to parseDigitsBig — that is what makes overflow impossible here (at
196 // most 7 digits) and keeps this body under the inlining budget.
197 func parseDigits[S byteSeq](s S, i int) (uint64, error) {
198 var n uint64
199 for ; i < len(s); i++ {
200 c := s[i] - '0'
201 if c > 9 {
202 return 0, strconv.ErrSyntax
203 }
204 n = n*10 + uint64(c)
205 }
206 return n, nil
207 }
208
209 // parseDigitsBig parses digit runs of 8+ bytes, consuming 8 digits per word
210 // while the running value is guaranteed to still fit: two full steps reach 16
211 // digits, and any value with <= 19 digits fits in uint64. A word with any
212 // non-digit lane falls through to the scalar loop, which reports syntax
213 // errors byte-precisely and applies the overflow checks.
214 func parseDigitsBig[S byteSeq](s S, i int) (uint64, error) {
215 var n uint64
216 digits := 0
217 for len(s)-i >= 8 && digits+8 <= 19 {
218 w := swar.Load8(s, i)
219 if !isEightDigits(w) {
220 break
221 }
222 n = n*100000000 + parse8Digits(w)
223 digits += 8
224 i += 8
225 }
226 for ; i < len(s); i++ {
227 c := s[i] - '0'
228 if c > 9 {
229 return 0, strconv.ErrSyntax
230 }
231 d := uint64(c)
232 // Any value with <= 19 digits is guaranteed to fit in uint64.
233 if digits >= 19 && (n > maxUint64Cutoff || (n == maxUint64Cutoff && d > maxUint64Cutlim)) {
234 return 0, strconv.ErrRange
235 }
236 n = n*10 + d
237 digits++
238 }
239 return n, nil
240 }
241
242 // parseSigned parses a decimal ASCII string or byte slice into a signed integer type T.
243 // It supports optional '+' or '-' prefix, checks for overflow and underflow, and returns (0, error) on error.
244 func parseSigned[S byteSeq, T Signed](fn string, s S, minRange, maxRange T) (T, error) {
245 if len(s) == 0 {
246 return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax}
247 }
248
249 neg := false
250 i := 0
251 switch s[0] {
252 case '-':
253 neg = true
254 i++
255 case '+':
256 i++
257 }
258 if i == len(s) {
259 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
260 }
261
262 // Parse digits, taking the 8-digits-per-word path for long runs.
263 var n uint64
264 var err error
265 if len(s)-i >= 8 {
266 n, err = parseDigitsBig(s, i)
267 } else {
268 n, err = parseDigits(s, i)
269 }
270 if err != nil {
271 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: err}
272 }
273
274 if !neg {
275 // Check for overflow
276 if n > uint64(int64(maxRange)) {
277 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange}
278 }
279 return T(n), nil
280 }
281
282 // Check for underflow
283 minAbs := uint64(-int64(minRange))
284 if n > minAbs {
285 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange}
286 }
287
288 return T(-int64(n)), nil
289 }
290
291 // parseUnsigned parses a decimal ASCII string or byte slice into an unsigned integer type T.
292 // It does not support sign prefixes, checks for overflow, and returns (0, error) on error.
293 func parseUnsigned[S byteSeq, T Unsigned](fn string, s S, maxRange T) (T, error) {
294 if len(s) == 0 {
295 return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax}
296 }
297
298 // Parse digits directly from index 0, taking the 8-digits-per-word path
299 // for long runs.
300 var n uint64
301 var err error
302 if len(s) >= 8 {
303 n, err = parseDigitsBig(s, 0)
304 } else {
305 n, err = parseDigits(s, 0)
306 }
307 if err != nil {
308 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: err}
309 }
310 // Check for overflow
311 if n > uint64(maxRange) {
312 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange}
313 }
314 return T(n), nil
315 }
316
317 // parseFloat parses a decimal ASCII string or byte slice into a float64.
318 // It supports optional sign, fractional part and exponent. It returns (0, error)
319 // on error or overflow.
320 func parseFloat[S byteSeq](fn string, s S) (float64, error) {
321 if len(s) == 0 {
322 return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax}
323 }
324 i := 0
325 neg := false
326 switch s[0] {
327 case '-':
328 neg = true
329 i++
330 case '+':
331 i++
332 }
333 if i == len(s) {
334 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
335 }
336
337 // Collect integer and fractional digits into a single mantissa and track
338 // the decimal exponent. Digits beyond uint64 precision are dropped: integer
339 // digits shift the exponent up, fractional digits are simply ignored.
340 var mantissa uint64
341 var exp10 int
342 digits := 0
343 for i < len(s) {
344 c := s[i] - '0'
345 if c > 9 {
346 break
347 }
348 if mantissa > maxUint64Cutoff || (mantissa == maxUint64Cutoff && uint64(c) > maxUint64Cutlim) {
349 exp10++
350 } else {
351 mantissa = mantissa*10 + uint64(c)
352 }
353 digits++
354 i++
355 }
356
357 if i < len(s) && s[i] == '.' {
358 i++
359 for i < len(s) {
360 c := s[i] - '0'
361 if c > 9 {
362 break
363 }
364 if mantissa < maxUint64Cutoff || (mantissa == maxUint64Cutoff && uint64(c) <= maxUint64Cutlim) {
365 mantissa = mantissa*10 + uint64(c)
366 exp10--
367 }
368 digits++
369 i++
370 }
371 }
372
373 if digits == 0 {
374 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
375 }
376
377 var expSign bool
378 var exp int64
379 if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
380 i++
381 if i == len(s) {
382 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
383 }
384 switch s[i] {
385 case '-':
386 expSign = true
387 i++
388 case '+':
389 i++
390 }
391 if i == len(s) {
392 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
393 }
394 // Saturate the parsed exponent far beyond anything exp10 (bounded by
395 // the input length) could pull back into range. Clamping to the final
396 // range must wait until both are combined below.
397 const maxParsedExp = int64(1) << 50
398 for i < len(s) {
399 c := s[i] - '0'
400 if c > 9 {
401 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
402 }
403 if exp < maxParsedExp {
404 exp = exp*10 + int64(c)
405 }
406 i++
407 }
408 }
409
410 if i != len(s) {
411 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax}
412 }
413 if expSign {
414 exp = -exp
415 }
416 // Clamp the combined exponent to math.Pow10's saturation range so the
417 // int conversion below cannot wrap on 32-bit platforms for extremely
418 // long digit strings; larger magnitudes overflow (Inf, caught below) or
419 // underflow (Pow10 returns 0) anyway.
420 exp += int64(exp10)
421 if exp > 309 {
422 exp = 309
423 } else if exp < -325 {
424 exp = -325
425 }
426
427 f := float64(mantissa)
428 // Skip scaling for a zero mantissa: 0 * Pow10(309) would be 0 * Inf = NaN
429 // and turn inputs like "0e400" into a spurious range error.
430 if exp != 0 && f != 0 {
431 f *= math.Pow10(int(exp))
432 }
433 if neg {
434 f = -f
435 }
436 if math.IsInf(f, 0) || math.IsNaN(f) {
437 return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange}
438 }
439 return f, nil
440 }
441
442 // ParseFloat64 parses a decimal ASCII string or byte slice into a float64. It
443 // delegates the actual parsing to parseFloat.
444 func ParseFloat64[S byteSeq](s S) (float64, error) {
445 return parseFloat[S]("ParseFloat64", s)
446 }
447
448 // ParseFloat32 parses a decimal ASCII string or byte slice into a float32. It
449 // returns (0, false) on error or if the parsed value overflows float32.
450 func ParseFloat32[S byteSeq](s S) (float32, error) {
451 f, err := parseFloat[S]("ParseFloat32", s)
452 if err != nil {
453 return 0, err
454 }
455 if f > math.MaxFloat32 || f < -math.MaxFloat32 {
456 return 0, &strconv.NumError{Func: "ParseFloat32", Num: string(s), Err: strconv.ErrRange}
457 }
458 return float32(f), nil
459 }