bytes.go 862 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package jsonparser
  2. import (
  3. bio "bytes"
  4. )
  5. // minInt64 '-9223372036854775808' is the smallest representable number in int64
  6. const minInt64 = `9223372036854775808`
  7. // About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
  8. func parseInt(bytes []byte) (v int64, ok bool, overflow bool) {
  9. if len(bytes) == 0 {
  10. return 0, false, false
  11. }
  12. var neg bool = false
  13. if bytes[0] == '-' {
  14. neg = true
  15. bytes = bytes[1:]
  16. }
  17. var b int64 = 0
  18. for _, c := range bytes {
  19. if c >= '0' && c <= '9' {
  20. b = (10 * v) + int64(c-'0')
  21. } else {
  22. return 0, false, false
  23. }
  24. if overflow = (b < v); overflow {
  25. break
  26. }
  27. v = b
  28. }
  29. if overflow {
  30. if neg && bio.Equal(bytes, []byte(minInt64)) {
  31. return b, true, false
  32. }
  33. return 0, false, true
  34. }
  35. if neg {
  36. return -v, true, false
  37. } else {
  38. return v, true, false
  39. }
  40. }