| 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 | digitZeros = 0x3030303030303030 // '0' in every lane |
| 185 | pairMask = 0x000000FF000000FF |
| 186 | mul1 = 100 + (1000000 << 32) |
| 187 | mul2 = 1 + (10000 << 32) |
| 188 | ) |
| 189 | w -= digitZeros |
| 190 | w = w*10 + w>>8 // adjacent digit pairs -> 2-digit values in even lanes |
| 191 | return ((w&pairMask)*mul1 + (w>>16&pairMask)*mul2) >> 32 |
| 192 | } |
| 193 | |
| 194 | // parseDigits parses a run of fewer than 8 digits and returns the uint64 |
| 195 | // value, or an error on the first non-digit. Callers must route runs of 8+ |
| 196 | // bytes to parseDigitsBig — that is what makes overflow impossible here (at |
| 197 | // most 7 digits) and keeps this body under the inlining budget. |
| 198 | func parseDigits[S byteSeq](s S, i int) (uint64, error) { |
| 199 | var n uint64 |
| 200 | for ; i < len(s); i++ { |
| 201 | c := s[i] - '0' |
| 202 | if c > 9 { |
| 203 | return 0, strconv.ErrSyntax |
| 204 | } |
| 205 | n = n*10 + uint64(c) |
| 206 | } |
| 207 | return n, nil |
| 208 | } |
| 209 | |
| 210 | // parseDigitsBig parses digit runs of 8+ bytes, consuming 8 digits per word |
| 211 | // while the running value is guaranteed to still fit: two full steps reach 16 |
| 212 | // digits, and any value with <= 19 digits fits in uint64. A word with any |
| 213 | // non-digit lane falls through to the scalar loop, which reports syntax |
| 214 | // errors byte-precisely and applies the overflow checks. |
| 215 | func parseDigitsBig[S byteSeq](s S, i int) (uint64, error) { |
| 216 | var n uint64 |
| 217 | digits := 0 |
| 218 | for len(s)-i >= 8 && digits+8 <= 19 { |
| 219 | w := swar.Load8(s, i) |
| 220 | if !isEightDigits(w) { |
| 221 | break |
| 222 | } |
| 223 | n = n*100000000 + parse8Digits(w) |
| 224 | digits += 8 |
| 225 | i += 8 |
| 226 | } |
| 227 | for ; i < len(s); i++ { |
| 228 | c := s[i] - '0' |
| 229 | if c > 9 { |
| 230 | return 0, strconv.ErrSyntax |
| 231 | } |
| 232 | d := uint64(c) |
| 233 | // Any value with <= 19 digits is guaranteed to fit in uint64. |
| 234 | if digits >= 19 && (n > maxUint64Cutoff || (n == maxUint64Cutoff && d > maxUint64Cutlim)) { |
| 235 | return 0, strconv.ErrRange |
| 236 | } |
| 237 | n = n*10 + d |
| 238 | digits++ |
| 239 | } |
| 240 | return n, nil |
| 241 | } |
| 242 | |
| 243 | // parseSigned parses a decimal ASCII string or byte slice into a signed integer type T. |
| 244 | // It supports optional '+' or '-' prefix, checks for overflow and underflow, and returns (0, error) on error. |
| 245 | func parseSigned[S byteSeq, T Signed](fn string, s S, minRange, maxRange T) (T, error) { |
| 246 | if len(s) == 0 { |
| 247 | return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax} |
| 248 | } |
| 249 | |
| 250 | neg := false |
| 251 | i := 0 |
| 252 | switch s[0] { |
| 253 | case '-': |
| 254 | neg = true |
| 255 | i++ |
| 256 | case '+': |
| 257 | i++ |
| 258 | } |
| 259 | if i == len(s) { |
| 260 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 261 | } |
| 262 | |
| 263 | // Parse digits, taking the 8-digits-per-word path for long runs. |
| 264 | var n uint64 |
| 265 | var err error |
| 266 | if len(s)-i >= 8 { |
| 267 | n, err = parseDigitsBig(s, i) |
| 268 | } else { |
| 269 | n, err = parseDigits(s, i) |
| 270 | } |
| 271 | if err != nil { |
| 272 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: err} |
| 273 | } |
| 274 | |
| 275 | if !neg { |
| 276 | // Check for overflow |
| 277 | if n > uint64(int64(maxRange)) { |
| 278 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange} |
| 279 | } |
| 280 | return T(n), nil |
| 281 | } |
| 282 | |
| 283 | // Check for underflow |
| 284 | minAbs := uint64(-int64(minRange)) |
| 285 | if n > minAbs { |
| 286 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange} |
| 287 | } |
| 288 | |
| 289 | return T(-int64(n)), nil |
| 290 | } |
| 291 | |
| 292 | // parseUnsigned parses a decimal ASCII string or byte slice into an unsigned integer type T. |
| 293 | // It does not support sign prefixes, checks for overflow, and returns (0, error) on error. |
| 294 | func parseUnsigned[S byteSeq, T Unsigned](fn string, s S, maxRange T) (T, error) { |
| 295 | if len(s) == 0 { |
| 296 | return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax} |
| 297 | } |
| 298 | |
| 299 | // Parse digits directly from index 0, taking the 8-digits-per-word path |
| 300 | // for long runs. |
| 301 | var n uint64 |
| 302 | var err error |
| 303 | if len(s) >= 8 { |
| 304 | n, err = parseDigitsBig(s, 0) |
| 305 | } else { |
| 306 | n, err = parseDigits(s, 0) |
| 307 | } |
| 308 | if err != nil { |
| 309 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: err} |
| 310 | } |
| 311 | // Check for overflow |
| 312 | if n > uint64(maxRange) { |
| 313 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange} |
| 314 | } |
| 315 | return T(n), nil |
| 316 | } |
| 317 | |
| 318 | // parseFloat parses a decimal ASCII string or byte slice into a float64. |
| 319 | // It supports optional sign, fractional part and exponent. It returns (0, error) |
| 320 | // on error or overflow. |
| 321 | func parseFloat[S byteSeq](fn string, s S) (float64, error) { |
| 322 | if len(s) == 0 { |
| 323 | return 0, &strconv.NumError{Func: fn, Num: "", Err: strconv.ErrSyntax} |
| 324 | } |
| 325 | i := 0 |
| 326 | neg := false |
| 327 | switch s[0] { |
| 328 | case '-': |
| 329 | neg = true |
| 330 | i++ |
| 331 | case '+': |
| 332 | i++ |
| 333 | } |
| 334 | if i == len(s) { |
| 335 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 336 | } |
| 337 | |
| 338 | // Collect integer and fractional digits into a single mantissa and track |
| 339 | // the decimal exponent. Digits beyond uint64 precision are dropped: integer |
| 340 | // digits shift the exponent up, fractional digits are simply ignored. |
| 341 | var mantissa uint64 |
| 342 | var exp10 int |
| 343 | digits := 0 |
| 344 | for i < len(s) { |
| 345 | c := s[i] - '0' |
| 346 | if c > 9 { |
| 347 | break |
| 348 | } |
| 349 | if mantissa > maxUint64Cutoff || (mantissa == maxUint64Cutoff && uint64(c) > maxUint64Cutlim) { |
| 350 | exp10++ |
| 351 | } else { |
| 352 | mantissa = mantissa*10 + uint64(c) |
| 353 | } |
| 354 | digits++ |
| 355 | i++ |
| 356 | } |
| 357 | |
| 358 | if i < len(s) && s[i] == '.' { |
| 359 | i++ |
| 360 | for i < len(s) { |
| 361 | c := s[i] - '0' |
| 362 | if c > 9 { |
| 363 | break |
| 364 | } |
| 365 | if mantissa < maxUint64Cutoff || (mantissa == maxUint64Cutoff && uint64(c) <= maxUint64Cutlim) { |
| 366 | mantissa = mantissa*10 + uint64(c) |
| 367 | exp10-- |
| 368 | } |
| 369 | digits++ |
| 370 | i++ |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | if digits == 0 { |
| 375 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 376 | } |
| 377 | |
| 378 | var expSign bool |
| 379 | var exp int64 |
| 380 | if i < len(s) && (s[i] == 'e' || s[i] == 'E') { |
| 381 | i++ |
| 382 | if i == len(s) { |
| 383 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 384 | } |
| 385 | switch s[i] { |
| 386 | case '-': |
| 387 | expSign = true |
| 388 | i++ |
| 389 | case '+': |
| 390 | i++ |
| 391 | } |
| 392 | if i == len(s) { |
| 393 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 394 | } |
| 395 | // Saturate the parsed exponent far beyond anything exp10 (bounded by |
| 396 | // the input length) could pull back into range. Clamping to the final |
| 397 | // range must wait until both are combined below. |
| 398 | const maxParsedExp = int64(1) << 50 |
| 399 | for i < len(s) { |
| 400 | c := s[i] - '0' |
| 401 | if c > 9 { |
| 402 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 403 | } |
| 404 | if exp < maxParsedExp { |
| 405 | exp = exp*10 + int64(c) |
| 406 | } |
| 407 | i++ |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | if i != len(s) { |
| 412 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrSyntax} |
| 413 | } |
| 414 | if expSign { |
| 415 | exp = -exp |
| 416 | } |
| 417 | // Clamp the combined exponent to math.Pow10's saturation range so the |
| 418 | // int conversion below cannot wrap on 32-bit platforms for extremely |
| 419 | // long digit strings; larger magnitudes overflow (Inf, caught below) or |
| 420 | // underflow (Pow10 returns 0) anyway. |
| 421 | exp += int64(exp10) |
| 422 | if exp > 309 { |
| 423 | exp = 309 |
| 424 | } else if exp < -325 { |
| 425 | exp = -325 |
| 426 | } |
| 427 | |
| 428 | f := float64(mantissa) |
| 429 | // Skip scaling for a zero mantissa: 0 * Pow10(309) would be 0 * Inf = NaN |
| 430 | // and turn inputs like "0e400" into a spurious range error. |
| 431 | if exp != 0 && f != 0 { |
| 432 | f *= math.Pow10(int(exp)) |
| 433 | } |
| 434 | if neg { |
| 435 | f = -f |
| 436 | } |
| 437 | if math.IsInf(f, 0) || math.IsNaN(f) { |
| 438 | return 0, &strconv.NumError{Func: fn, Num: string(s), Err: strconv.ErrRange} |
| 439 | } |
| 440 | return f, nil |
| 441 | } |
| 442 | |
| 443 | // ParseFloat64 parses a decimal ASCII string or byte slice into a float64. It |
| 444 | // delegates the actual parsing to parseFloat. |
| 445 | func ParseFloat64[S byteSeq](s S) (float64, error) { |
| 446 | return parseFloat[S]("ParseFloat64", s) |
| 447 | } |
| 448 | |
| 449 | // ParseFloat32 parses a decimal ASCII string or byte slice into a float32. It |
| 450 | // returns (0, false) on error or if the parsed value overflows float32. |
| 451 | func ParseFloat32[S byteSeq](s S) (float32, error) { |
| 452 | f, err := parseFloat[S]("ParseFloat32", s) |
| 453 | if err != nil { |
| 454 | return 0, err |
| 455 | } |
| 456 | if f > math.MaxFloat32 || f < -math.MaxFloat32 { |
| 457 | return 0, &strconv.NumError{Func: "ParseFloat32", Num: string(s), Err: strconv.ErrRange} |
| 458 | } |
| 459 | return float32(f), nil |
| 460 | } |