decode.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package jsonwire
  5. import (
  6. "io"
  7. "math"
  8. "slices"
  9. "strconv"
  10. "unicode/utf16"
  11. "unicode/utf8"
  12. )
  13. type ValueFlags uint
  14. const (
  15. _ ValueFlags = (1 << iota) / 2 // powers of two starting with zero
  16. stringNonVerbatim // string cannot be naively treated as valid UTF-8
  17. stringNonCanonical // string not formatted according to RFC 8785, section 3.2.2.2.
  18. // TODO: Track whether a number is a non-integer?
  19. )
  20. func (f *ValueFlags) Join(f2 ValueFlags) { *f |= f2 }
  21. func (f ValueFlags) IsVerbatim() bool { return f&stringNonVerbatim == 0 }
  22. func (f ValueFlags) IsCanonical() bool { return f&stringNonCanonical == 0 }
  23. // ConsumeWhitespace consumes leading JSON whitespace per RFC 7159, section 2.
  24. func ConsumeWhitespace(b []byte) (n int) {
  25. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  26. for len(b) > n && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') {
  27. n++
  28. }
  29. return n
  30. }
  31. // ConsumeNull consumes the next JSON null literal per RFC 7159, section 3.
  32. // It returns 0 if it is invalid, in which case consumeLiteral should be used.
  33. func ConsumeNull(b []byte) int {
  34. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  35. const literal = "null"
  36. if len(b) >= len(literal) && string(b[:len(literal)]) == literal {
  37. return len(literal)
  38. }
  39. return 0
  40. }
  41. // ConsumeFalse consumes the next JSON false literal per RFC 7159, section 3.
  42. // It returns 0 if it is invalid, in which case consumeLiteral should be used.
  43. func ConsumeFalse(b []byte) int {
  44. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  45. const literal = "false"
  46. if len(b) >= len(literal) && string(b[:len(literal)]) == literal {
  47. return len(literal)
  48. }
  49. return 0
  50. }
  51. // ConsumeTrue consumes the next JSON true literal per RFC 7159, section 3.
  52. // It returns 0 if it is invalid, in which case consumeLiteral should be used.
  53. func ConsumeTrue(b []byte) int {
  54. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  55. const literal = "true"
  56. if len(b) >= len(literal) && string(b[:len(literal)]) == literal {
  57. return len(literal)
  58. }
  59. return 0
  60. }
  61. // ConsumeLiteral consumes the next JSON literal per RFC 7159, section 3.
  62. // If the input appears truncated, it returns io.ErrUnexpectedEOF.
  63. func ConsumeLiteral(b []byte, lit string) (n int, err error) {
  64. for i := 0; i < len(b) && i < len(lit); i++ {
  65. if b[i] != lit[i] {
  66. return i, NewInvalidCharacterError(b[i:], "in literal "+lit+" (expecting "+strconv.QuoteRune(rune(lit[i]))+")")
  67. }
  68. }
  69. if len(b) < len(lit) {
  70. return len(b), io.ErrUnexpectedEOF
  71. }
  72. return len(lit), nil
  73. }
  74. // ConsumeSimpleString consumes the next JSON string per RFC 7159, section 7
  75. // but is limited to the grammar for an ASCII string without escape sequences.
  76. // It returns 0 if it is invalid or more complicated than a simple string,
  77. // in which case consumeString should be called.
  78. //
  79. // It rejects '<', '>', and '&' for compatibility reasons since these were
  80. // always escaped in the v1 implementation. Thus, if this function reports
  81. // non-zero then we know that the string would be encoded the same way
  82. // under both v1 or v2 escape semantics.
  83. func ConsumeSimpleString(b []byte) (n int) {
  84. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  85. if len(b) > 0 && b[0] == '"' {
  86. n++
  87. for len(b) > n && b[n] < utf8.RuneSelf && escapeASCII[b[n]] == 0 {
  88. n++
  89. }
  90. if uint(len(b)) > uint(n) && b[n] == '"' {
  91. n++
  92. return n
  93. }
  94. }
  95. return 0
  96. }
  97. // ConsumeString consumes the next JSON string per RFC 7159, section 7.
  98. // If validateUTF8 is false, then this allows the presence of invalid UTF-8
  99. // characters within the string itself.
  100. // It reports the number of bytes consumed and whether an error was encountered.
  101. // If the input appears truncated, it returns io.ErrUnexpectedEOF.
  102. func ConsumeString(flags *ValueFlags, b []byte, validateUTF8 bool) (n int, err error) {
  103. return ConsumeStringResumable(flags, b, 0, validateUTF8)
  104. }
  105. // ConsumeStringResumable is identical to consumeString but supports resuming
  106. // from a previous call that returned io.ErrUnexpectedEOF.
  107. func ConsumeStringResumable(flags *ValueFlags, b []byte, resumeOffset int, validateUTF8 bool) (n int, err error) {
  108. // Consume the leading double quote.
  109. switch {
  110. case resumeOffset > 0:
  111. n = resumeOffset // already handled the leading quote
  112. case uint(len(b)) == 0:
  113. return n, io.ErrUnexpectedEOF
  114. case b[0] == '"':
  115. n++
  116. default:
  117. return n, NewInvalidCharacterError(b[n:], `at start of string (expecting '"')`)
  118. }
  119. // Consume every character in the string.
  120. for uint(len(b)) > uint(n) {
  121. // Optimize for long sequences of unescaped characters.
  122. noEscape := func(c byte) bool {
  123. return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"'
  124. }
  125. for uint(len(b)) > uint(n) && noEscape(b[n]) {
  126. n++
  127. }
  128. if uint(len(b)) <= uint(n) {
  129. return n, io.ErrUnexpectedEOF
  130. }
  131. // Check for terminating double quote.
  132. if b[n] == '"' {
  133. n++
  134. return n, nil
  135. }
  136. switch r, rn := utf8.DecodeRune(b[n:]); {
  137. // Handle UTF-8 encoded byte sequence.
  138. // Due to specialized handling of ASCII above, we know that
  139. // all normal sequences at this point must be 2 bytes or larger.
  140. case rn > 1:
  141. n += rn
  142. // Handle escape sequence.
  143. case r == '\\':
  144. flags.Join(stringNonVerbatim)
  145. resumeOffset = n
  146. if uint(len(b)) < uint(n+2) {
  147. return resumeOffset, io.ErrUnexpectedEOF
  148. }
  149. switch r := b[n+1]; r {
  150. case '/':
  151. // Forward slash is the only character with 3 representations.
  152. // Per RFC 8785, section 3.2.2.2., this must not be escaped.
  153. flags.Join(stringNonCanonical)
  154. n += 2
  155. case '"', '\\', 'b', 'f', 'n', 'r', 't':
  156. n += 2
  157. case 'u':
  158. if uint(len(b)) < uint(n+6) {
  159. if hasEscapedUTF16Prefix(b[n:], false) {
  160. return resumeOffset, io.ErrUnexpectedEOF
  161. }
  162. flags.Join(stringNonCanonical)
  163. return n, NewInvalidEscapeSequenceError(b[n:])
  164. }
  165. v1, ok := parseHexUint16(b[n+2 : n+6])
  166. if !ok {
  167. flags.Join(stringNonCanonical)
  168. return n, NewInvalidEscapeSequenceError(b[n : n+6])
  169. }
  170. // Only certain control characters can use the \uFFFF notation
  171. // for canonical formatting (per RFC 8785, section 3.2.2.2.).
  172. switch v1 {
  173. // \uFFFF notation not permitted for these characters.
  174. case '\b', '\f', '\n', '\r', '\t':
  175. flags.Join(stringNonCanonical)
  176. default:
  177. // \uFFFF notation only permitted for control characters.
  178. if v1 >= ' ' {
  179. flags.Join(stringNonCanonical)
  180. } else {
  181. // \uFFFF notation must be lower case.
  182. for _, c := range b[n+2 : n+6] {
  183. if 'A' <= c && c <= 'F' {
  184. flags.Join(stringNonCanonical)
  185. }
  186. }
  187. }
  188. }
  189. n += 6
  190. r := rune(v1)
  191. if validateUTF8 && utf16.IsSurrogate(r) {
  192. if uint(len(b)) < uint(n+6) {
  193. if hasEscapedUTF16Prefix(b[n:], true) {
  194. return resumeOffset, io.ErrUnexpectedEOF
  195. }
  196. flags.Join(stringNonCanonical)
  197. return n - 6, NewInvalidEscapeSequenceError(b[n-6:])
  198. } else if v2, ok := parseHexUint16(b[n+2 : n+6]); b[n] != '\\' || b[n+1] != 'u' || !ok {
  199. flags.Join(stringNonCanonical)
  200. return n - 6, NewInvalidEscapeSequenceError(b[n-6 : n+6])
  201. } else if r = utf16.DecodeRune(rune(v1), rune(v2)); r == utf8.RuneError {
  202. flags.Join(stringNonCanonical)
  203. return n - 6, NewInvalidEscapeSequenceError(b[n-6 : n+6])
  204. } else {
  205. n += 6
  206. }
  207. }
  208. default:
  209. flags.Join(stringNonCanonical)
  210. return n, NewInvalidEscapeSequenceError(b[n : n+2])
  211. }
  212. // Handle invalid UTF-8.
  213. case r == utf8.RuneError:
  214. if !utf8.FullRune(b[n:]) {
  215. return n, io.ErrUnexpectedEOF
  216. }
  217. flags.Join(stringNonVerbatim | stringNonCanonical)
  218. if validateUTF8 {
  219. return n, ErrInvalidUTF8
  220. }
  221. n++
  222. // Handle invalid control characters.
  223. case r < ' ':
  224. flags.Join(stringNonVerbatim | stringNonCanonical)
  225. return n, NewInvalidCharacterError(b[n:], "in string (expecting non-control character)")
  226. default:
  227. panic("BUG: unhandled character " + QuoteRune(b[n:]))
  228. }
  229. }
  230. return n, io.ErrUnexpectedEOF
  231. }
  232. // AppendUnquote appends the unescaped form of a JSON string in src to dst.
  233. // Any invalid UTF-8 within the string will be replaced with utf8.RuneError,
  234. // but the error will be specified as having encountered such an error.
  235. // The input must be an entire JSON string with no surrounding whitespace.
  236. func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) (v []byte, err error) {
  237. dst = slices.Grow(dst, len(src))
  238. // Consume the leading double quote.
  239. var i, n int
  240. switch {
  241. case uint(len(src)) == 0:
  242. return dst, io.ErrUnexpectedEOF
  243. case src[0] == '"':
  244. i, n = 1, 1
  245. default:
  246. return dst, NewInvalidCharacterError(src, `at start of string (expecting '"')`)
  247. }
  248. // Consume every character in the string.
  249. for uint(len(src)) > uint(n) {
  250. // Optimize for long sequences of unescaped characters.
  251. noEscape := func(c byte) bool {
  252. return c < utf8.RuneSelf && ' ' <= c && c != '\\' && c != '"'
  253. }
  254. for uint(len(src)) > uint(n) && noEscape(src[n]) {
  255. n++
  256. }
  257. if uint(len(src)) <= uint(n) {
  258. dst = append(dst, src[i:n]...)
  259. return dst, io.ErrUnexpectedEOF
  260. }
  261. // Check for terminating double quote.
  262. if src[n] == '"' {
  263. dst = append(dst, src[i:n]...)
  264. n++
  265. if n < len(src) {
  266. err = NewInvalidCharacterError(src[n:], "after string value")
  267. }
  268. return dst, err
  269. }
  270. switch r, rn := utf8.DecodeRuneInString(string(truncateMaxUTF8(src[n:]))); {
  271. // Handle UTF-8 encoded byte sequence.
  272. // Due to specialized handling of ASCII above, we know that
  273. // all normal sequences at this point must be 2 bytes or larger.
  274. case rn > 1:
  275. n += rn
  276. // Handle escape sequence.
  277. case r == '\\':
  278. dst = append(dst, src[i:n]...)
  279. // Handle escape sequence.
  280. if uint(len(src)) < uint(n+2) {
  281. return dst, io.ErrUnexpectedEOF
  282. }
  283. switch r := src[n+1]; r {
  284. case '"', '\\', '/':
  285. dst = append(dst, r)
  286. n += 2
  287. case 'b':
  288. dst = append(dst, '\b')
  289. n += 2
  290. case 'f':
  291. dst = append(dst, '\f')
  292. n += 2
  293. case 'n':
  294. dst = append(dst, '\n')
  295. n += 2
  296. case 'r':
  297. dst = append(dst, '\r')
  298. n += 2
  299. case 't':
  300. dst = append(dst, '\t')
  301. n += 2
  302. case 'u':
  303. if uint(len(src)) < uint(n+6) {
  304. if hasEscapedUTF16Prefix(src[n:], false) {
  305. return dst, io.ErrUnexpectedEOF
  306. }
  307. return dst, NewInvalidEscapeSequenceError(src[n:])
  308. }
  309. v1, ok := parseHexUint16(src[n+2 : n+6])
  310. if !ok {
  311. return dst, NewInvalidEscapeSequenceError(src[n : n+6])
  312. }
  313. n += 6
  314. // Check whether this is a surrogate half.
  315. r := rune(v1)
  316. if utf16.IsSurrogate(r) {
  317. r = utf8.RuneError // assume failure unless the following succeeds
  318. if uint(len(src)) < uint(n+6) {
  319. if hasEscapedUTF16Prefix(src[n:], true) {
  320. return utf8.AppendRune(dst, r), io.ErrUnexpectedEOF
  321. }
  322. err = NewInvalidEscapeSequenceError(src[n-6:])
  323. } else if v2, ok := parseHexUint16(src[n+2 : n+6]); src[n] != '\\' || src[n+1] != 'u' || !ok {
  324. err = NewInvalidEscapeSequenceError(src[n-6 : n+6])
  325. } else if r = utf16.DecodeRune(rune(v1), rune(v2)); r == utf8.RuneError {
  326. err = NewInvalidEscapeSequenceError(src[n-6 : n+6])
  327. } else {
  328. n += 6
  329. }
  330. }
  331. dst = utf8.AppendRune(dst, r)
  332. default:
  333. return dst, NewInvalidEscapeSequenceError(src[n : n+2])
  334. }
  335. i = n
  336. // Handle invalid UTF-8.
  337. case r == utf8.RuneError:
  338. dst = append(dst, src[i:n]...)
  339. if !utf8.FullRuneInString(string(truncateMaxUTF8(src[n:]))) {
  340. return dst, io.ErrUnexpectedEOF
  341. }
  342. // NOTE: An unescaped string may be longer than the escaped string
  343. // because invalid UTF-8 bytes are being replaced.
  344. dst = append(dst, "\uFFFD"...)
  345. n += rn
  346. i = n
  347. err = ErrInvalidUTF8
  348. // Handle invalid control characters.
  349. case r < ' ':
  350. dst = append(dst, src[i:n]...)
  351. return dst, NewInvalidCharacterError(src[n:], "in string (expecting non-control character)")
  352. default:
  353. panic("BUG: unhandled character " + QuoteRune(src[n:]))
  354. }
  355. }
  356. dst = append(dst, src[i:n]...)
  357. return dst, io.ErrUnexpectedEOF
  358. }
  359. // hasEscapedUTF16Prefix reports whether b is possibly
  360. // the truncated prefix of a \uFFFF escape sequence.
  361. func hasEscapedUTF16Prefix[Bytes ~[]byte | ~string](b Bytes, lowerSurrogateHalf bool) bool {
  362. for i := range len(b) {
  363. switch c := b[i]; {
  364. case i == 0 && c != '\\':
  365. return false
  366. case i == 1 && c != 'u':
  367. return false
  368. case i == 2 && lowerSurrogateHalf && c != 'd' && c != 'D':
  369. return false // not within ['\uDC00':'\uDFFF']
  370. case i == 3 && lowerSurrogateHalf && !('c' <= c && c <= 'f') && !('C' <= c && c <= 'F'):
  371. return false // not within ['\uDC00':'\uDFFF']
  372. case i >= 2 && i < 6 && !('0' <= c && c <= '9') && !('a' <= c && c <= 'f') && !('A' <= c && c <= 'F'):
  373. return false
  374. }
  375. }
  376. return true
  377. }
  378. // UnquoteMayCopy returns the unescaped form of b.
  379. // If there are no escaped characters, the output is simply a subslice of
  380. // the input with the surrounding quotes removed.
  381. // Otherwise, a new buffer is allocated for the output.
  382. // It assumes the input is valid.
  383. func UnquoteMayCopy(b []byte, isVerbatim bool) []byte {
  384. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  385. if isVerbatim {
  386. return b[len(`"`) : len(b)-len(`"`)]
  387. }
  388. b, _ = AppendUnquote(nil, b)
  389. return b
  390. }
  391. // ConsumeSimpleNumber consumes the next JSON number per RFC 7159, section 6
  392. // but is limited to the grammar for a positive integer.
  393. // It returns 0 if it is invalid or more complicated than a simple integer,
  394. // in which case consumeNumber should be called.
  395. func ConsumeSimpleNumber(b []byte) (n int) {
  396. // NOTE: The arguments and logic are kept simple to keep this inlinable.
  397. if len(b) > 0 {
  398. if b[0] == '0' {
  399. n++
  400. } else if '1' <= b[0] && b[0] <= '9' {
  401. n++
  402. for len(b) > n && ('0' <= b[n] && b[n] <= '9') {
  403. n++
  404. }
  405. } else {
  406. return 0
  407. }
  408. if uint(len(b)) <= uint(n) || (b[n] != '.' && b[n] != 'e' && b[n] != 'E') {
  409. return n
  410. }
  411. }
  412. return 0
  413. }
  414. type ConsumeNumberState uint
  415. const (
  416. consumeNumberInit ConsumeNumberState = iota
  417. beforeIntegerDigits
  418. withinIntegerDigits
  419. beforeFractionalDigits
  420. withinFractionalDigits
  421. beforeExponentDigits
  422. withinExponentDigits
  423. )
  424. // ConsumeNumber consumes the next JSON number per RFC 7159, section 6.
  425. // It reports the number of bytes consumed and whether an error was encountered.
  426. // If the input appears truncated, it returns io.ErrUnexpectedEOF.
  427. //
  428. // Note that JSON numbers are not self-terminating.
  429. // If the entire input is consumed, then the caller needs to consider whether
  430. // there may be subsequent unread data that may still be part of this number.
  431. func ConsumeNumber(b []byte) (n int, err error) {
  432. n, _, err = ConsumeNumberResumable(b, 0, consumeNumberInit)
  433. return n, err
  434. }
  435. // ConsumeNumberResumable is identical to consumeNumber but supports resuming
  436. // from a previous call that returned io.ErrUnexpectedEOF.
  437. func ConsumeNumberResumable(b []byte, resumeOffset int, state ConsumeNumberState) (n int, _ ConsumeNumberState, err error) {
  438. // Jump to the right state when resuming from a partial consumption.
  439. n = resumeOffset
  440. if state > consumeNumberInit {
  441. switch state {
  442. case withinIntegerDigits, withinFractionalDigits, withinExponentDigits:
  443. // Consume leading digits.
  444. for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') {
  445. n++
  446. }
  447. if uint(len(b)) <= uint(n) {
  448. return n, state, nil // still within the same state
  449. }
  450. state++ // switches "withinX" to "beforeY" where Y is the state after X
  451. }
  452. switch state {
  453. case beforeIntegerDigits:
  454. goto beforeInteger
  455. case beforeFractionalDigits:
  456. goto beforeFractional
  457. case beforeExponentDigits:
  458. goto beforeExponent
  459. default:
  460. return n, state, nil
  461. }
  462. }
  463. // Consume required integer component (with optional minus sign).
  464. beforeInteger:
  465. resumeOffset = n
  466. if uint(len(b)) > 0 && b[0] == '-' {
  467. n++
  468. }
  469. switch {
  470. case uint(len(b)) <= uint(n):
  471. return resumeOffset, beforeIntegerDigits, io.ErrUnexpectedEOF
  472. case b[n] == '0':
  473. n++
  474. state = beforeFractionalDigits
  475. case '1' <= b[n] && b[n] <= '9':
  476. n++
  477. for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') {
  478. n++
  479. }
  480. state = withinIntegerDigits
  481. default:
  482. return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)")
  483. }
  484. // Consume optional fractional component.
  485. beforeFractional:
  486. if uint(len(b)) > uint(n) && b[n] == '.' {
  487. resumeOffset = n
  488. n++
  489. switch {
  490. case uint(len(b)) <= uint(n):
  491. return resumeOffset, beforeFractionalDigits, io.ErrUnexpectedEOF
  492. case '0' <= b[n] && b[n] <= '9':
  493. n++
  494. default:
  495. return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)")
  496. }
  497. for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') {
  498. n++
  499. }
  500. state = withinFractionalDigits
  501. }
  502. // Consume optional exponent component.
  503. beforeExponent:
  504. if uint(len(b)) > uint(n) && (b[n] == 'e' || b[n] == 'E') {
  505. resumeOffset = n
  506. n++
  507. if uint(len(b)) > uint(n) && (b[n] == '-' || b[n] == '+') {
  508. n++
  509. }
  510. switch {
  511. case uint(len(b)) <= uint(n):
  512. return resumeOffset, beforeExponentDigits, io.ErrUnexpectedEOF
  513. case '0' <= b[n] && b[n] <= '9':
  514. n++
  515. default:
  516. return n, state, NewInvalidCharacterError(b[n:], "in number (expecting digit)")
  517. }
  518. for uint(len(b)) > uint(n) && ('0' <= b[n] && b[n] <= '9') {
  519. n++
  520. }
  521. state = withinExponentDigits
  522. }
  523. return n, state, nil
  524. }
  525. // parseHexUint16 is similar to strconv.ParseUint,
  526. // but operates directly on []byte and is optimized for base-16.
  527. // See https://go.dev/issue/42429.
  528. func parseHexUint16[Bytes ~[]byte | ~string](b Bytes) (v uint16, ok bool) {
  529. if len(b) != 4 {
  530. return 0, false
  531. }
  532. for i := range 4 {
  533. c := b[i]
  534. switch {
  535. case '0' <= c && c <= '9':
  536. c = c - '0'
  537. case 'a' <= c && c <= 'f':
  538. c = 10 + c - 'a'
  539. case 'A' <= c && c <= 'F':
  540. c = 10 + c - 'A'
  541. default:
  542. return 0, false
  543. }
  544. v = v*16 + uint16(c)
  545. }
  546. return v, true
  547. }
  548. // ParseUint parses b as a decimal unsigned integer according to
  549. // a strict subset of the JSON number grammar, returning the value if valid.
  550. // It returns (0, false) if there is a syntax error and
  551. // returns (math.MaxUint64, false) if there is an overflow.
  552. func ParseUint(b []byte) (v uint64, ok bool) {
  553. const unsafeWidth = 20 // len(fmt.Sprint(uint64(math.MaxUint64)))
  554. var n int
  555. for ; len(b) > n && ('0' <= b[n] && b[n] <= '9'); n++ {
  556. v = 10*v + uint64(b[n]-'0')
  557. }
  558. switch {
  559. case n == 0 || len(b) != n || (b[0] == '0' && string(b) != "0"):
  560. return 0, false
  561. case n >= unsafeWidth && (b[0] != '1' || v < 1e19 || n > unsafeWidth):
  562. return math.MaxUint64, false
  563. }
  564. return v, true
  565. }
  566. // ParseFloat parses a floating point number according to the Go float grammar.
  567. // Note that the JSON number grammar is a strict subset.
  568. //
  569. // If the number overflows the finite representation of a float,
  570. // then we return MaxFloat since any finite value will always be infinitely
  571. // more accurate at representing another finite value than an infinite value.
  572. func ParseFloat(b []byte, bits int) (v float64, ok bool) {
  573. fv, err := strconv.ParseFloat(string(b), bits)
  574. if math.IsInf(fv, 0) {
  575. switch {
  576. case bits == 32 && math.IsInf(fv, +1):
  577. fv = +math.MaxFloat32
  578. case bits == 64 && math.IsInf(fv, +1):
  579. fv = +math.MaxFloat64
  580. case bits == 32 && math.IsInf(fv, -1):
  581. fv = -math.MaxFloat32
  582. case bits == 64 && math.IsInf(fv, -1):
  583. fv = -math.MaxFloat64
  584. }
  585. }
  586. return fv, err == nil
  587. }