json.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license found in the LICENSE file.
  3. package codec
  4. // This json support uses base64 encoding for bytes, because you cannot
  5. // store and read any arbitrary string in json (only unicode).
  6. //
  7. // This library specifically supports UTF-8 for encoding and decoding only.
  8. //
  9. // Note that the library will happily encode/decode things which are not valid
  10. // json e.g. a map[int64]string. We do it for consistency. With valid json,
  11. // we will encode and decode appropriately.
  12. // Users can specify their map type if necessary to force it.
  13. //
  14. // Note:
  15. // - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently.
  16. // We implement it here.
  17. // - Also, strconv.ParseXXX for floats and integers
  18. // - only works on strings resulting in unnecessary allocation and []byte-string conversion.
  19. // - it does a lot of redundant checks, because json numbers are simpler that what it supports.
  20. // - We parse numbers (floats and integers) directly here.
  21. // We only delegate parsing floats if it is a hairy float which could cause a loss of precision.
  22. // In that case, we delegate to strconv.ParseFloat.
  23. //
  24. // Note:
  25. // - encode does not beautify. There is no whitespace when encoding.
  26. // - rpc calls which take single integer arguments or write single numeric arguments will need care.
  27. import (
  28. "bytes"
  29. "encoding/base64"
  30. "fmt"
  31. "strconv"
  32. "unicode/utf16"
  33. "unicode/utf8"
  34. )
  35. //--------------------------------
  36. var jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
  37. var jsonFloat64Pow10 = [...]float64{
  38. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  39. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  40. 1e20, 1e21, 1e22,
  41. }
  42. var jsonUint64Pow10 = [...]uint64{
  43. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  44. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  45. }
  46. const (
  47. // if jsonTrackSkipWhitespace, we track Whitespace and reduce the number of redundant checks.
  48. // Make it a const flag, so that it can be elided during linking if false.
  49. //
  50. // It is not a clear win, because we continually set a flag behind a pointer
  51. // and then check it each time, as opposed to just 4 conditionals on a stack variable.
  52. jsonTrackSkipWhitespace = true
  53. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  54. // - If we see first character of null, false or true,
  55. // do not validate subsequent characters.
  56. // - e.g. if we see a n, assume null and skip next 3 characters,
  57. // and do not validate they are ull.
  58. // P.S. Do not expect a significant decoding boost from this.
  59. jsonValidateSymbols = true
  60. // if jsonTruncateMantissa, truncate mantissa if trailing 0's.
  61. // This is important because it could allow some floats to be decoded without
  62. // deferring to strconv.ParseFloat.
  63. jsonTruncateMantissa = true
  64. // if mantissa >= jsonNumUintCutoff before multiplying by 10, this is an overflow
  65. jsonNumUintCutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  66. // if mantissa >= jsonNumUintMaxVal, this is an overflow
  67. jsonNumUintMaxVal = 1<<uint64(64) - 1
  68. // jsonNumDigitsUint64Largest = 19
  69. )
  70. type jsonEncDriver struct {
  71. e *Encoder
  72. w encWriter
  73. h *JsonHandle
  74. b [64]byte // scratch
  75. bs []byte // scratch
  76. noBuiltInTypes
  77. }
  78. func (e *jsonEncDriver) EncodeNil() {
  79. e.w.writeb(jsonLiterals[9:13]) // null
  80. }
  81. func (e *jsonEncDriver) EncodeBool(b bool) {
  82. if b {
  83. e.w.writeb(jsonLiterals[0:4]) // true
  84. } else {
  85. e.w.writeb(jsonLiterals[4:9]) // false
  86. }
  87. }
  88. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  89. e.w.writeb(strconv.AppendFloat(e.b[:0], float64(f), 'E', -1, 32))
  90. }
  91. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  92. // e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64))
  93. e.w.writeb(strconv.AppendFloat(e.b[:0], f, 'E', -1, 64))
  94. }
  95. func (e *jsonEncDriver) EncodeInt(v int64) {
  96. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  97. }
  98. func (e *jsonEncDriver) EncodeUint(v uint64) {
  99. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  100. }
  101. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  102. if v := ext.ConvertExt(rv); v == nil {
  103. e.EncodeNil()
  104. } else {
  105. en.encode(v)
  106. }
  107. }
  108. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  109. // only encodes re.Value (never re.Data)
  110. if re.Value == nil {
  111. e.EncodeNil()
  112. } else {
  113. en.encode(re.Value)
  114. }
  115. }
  116. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  117. e.w.writen1('[')
  118. }
  119. func (e *jsonEncDriver) EncodeArrayEntrySeparator() {
  120. e.w.writen1(',')
  121. }
  122. func (e *jsonEncDriver) EncodeArrayEnd() {
  123. e.w.writen1(']')
  124. }
  125. func (e *jsonEncDriver) EncodeMapStart(length int) {
  126. e.w.writen1('{')
  127. }
  128. func (e *jsonEncDriver) EncodeMapEntrySeparator() {
  129. e.w.writen1(',')
  130. }
  131. func (e *jsonEncDriver) EncodeMapKVSeparator() {
  132. e.w.writen1(':')
  133. }
  134. func (e *jsonEncDriver) EncodeMapEnd() {
  135. e.w.writen1('}')
  136. }
  137. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  138. // e.w.writestr(strconv.Quote(v))
  139. e.quoteStr(v)
  140. }
  141. func (e *jsonEncDriver) EncodeSymbol(v string) {
  142. // e.EncodeString(c_UTF8, v)
  143. e.quoteStr(v)
  144. }
  145. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  146. if c == c_RAW {
  147. slen := base64.StdEncoding.EncodedLen(len(v))
  148. if e.bs == nil {
  149. e.bs = e.b[:]
  150. }
  151. if cap(e.bs) >= slen {
  152. e.bs = e.bs[:slen]
  153. } else {
  154. e.bs = make([]byte, slen)
  155. }
  156. base64.StdEncoding.Encode(e.bs, v)
  157. e.w.writen1('"')
  158. e.w.writeb(e.bs)
  159. e.w.writen1('"')
  160. } else {
  161. // e.EncodeString(c, string(v))
  162. e.quoteStr(stringView(v))
  163. }
  164. }
  165. func (e *jsonEncDriver) quoteStr(s string) {
  166. // adapted from std pkg encoding/json
  167. const hex = "0123456789abcdef"
  168. w := e.w
  169. w.writen1('"')
  170. start := 0
  171. for i := 0; i < len(s); {
  172. if b := s[i]; b < utf8.RuneSelf {
  173. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  174. i++
  175. continue
  176. }
  177. if start < i {
  178. w.writestr(s[start:i])
  179. }
  180. switch b {
  181. case '\\', '"':
  182. w.writen2('\\', b)
  183. case '\n':
  184. w.writen2('\\', 'n')
  185. case '\r':
  186. w.writen2('\\', 'r')
  187. case '\b':
  188. w.writen2('\\', 'b')
  189. case '\f':
  190. w.writen2('\\', 'f')
  191. case '\t':
  192. w.writen2('\\', 't')
  193. default:
  194. // encode all bytes < 0x20 (except \r, \n).
  195. // also encode < > & to prevent security holes when served to some browsers.
  196. w.writestr(`\u00`)
  197. w.writen2(hex[b>>4], hex[b&0xF])
  198. }
  199. i++
  200. start = i
  201. continue
  202. }
  203. c, size := utf8.DecodeRuneInString(s[i:])
  204. if c == utf8.RuneError && size == 1 {
  205. if start < i {
  206. w.writestr(s[start:i])
  207. }
  208. w.writestr(`\ufffd`)
  209. i += size
  210. start = i
  211. continue
  212. }
  213. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  214. // Both technically valid JSON, but bomb on JSONP, so fix here.
  215. if c == '\u2028' || c == '\u2029' {
  216. if start < i {
  217. w.writestr(s[start:i])
  218. }
  219. w.writestr(`\u202`)
  220. w.writen1(hex[c&0xF])
  221. i += size
  222. start = i
  223. continue
  224. }
  225. i += size
  226. }
  227. if start < len(s) {
  228. w.writestr(s[start:])
  229. }
  230. w.writen1('"')
  231. }
  232. //--------------------------------
  233. type jsonNum struct {
  234. bytes []byte // may have [+-.eE0-9]
  235. mantissa uint64 // where mantissa ends, and maybe dot begins.
  236. exponent int16 // exponent value.
  237. manOverflow bool
  238. neg bool // started with -. No initial sign in the bytes above.
  239. dot bool // has dot
  240. explicitExponent bool // explicit exponent
  241. }
  242. func (x *jsonNum) reset() {
  243. x.bytes = x.bytes[:0]
  244. x.manOverflow = false
  245. x.neg = false
  246. x.dot = false
  247. x.explicitExponent = false
  248. x.mantissa = 0
  249. x.exponent = 0
  250. }
  251. // uintExp is called only if exponent > 0.
  252. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  253. n = x.mantissa
  254. e := x.exponent
  255. if e >= int16(len(jsonUint64Pow10)) {
  256. overflow = true
  257. return
  258. }
  259. n *= jsonUint64Pow10[e]
  260. if n < x.mantissa || n > jsonNumUintMaxVal {
  261. overflow = true
  262. return
  263. }
  264. return
  265. // for i := int16(0); i < e; i++ {
  266. // if n >= jsonNumUintCutoff {
  267. // overflow = true
  268. // return
  269. // }
  270. // n *= 10
  271. // }
  272. // return
  273. }
  274. func (x *jsonNum) floatVal() (f float64) {
  275. // We do not want to lose precision.
  276. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  277. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  278. // We expect up to 99.... (19 digits)
  279. // - The mantissa cannot fit into a 52 bits of uint64
  280. // - The exponent is beyond our scope ie beyong 22.
  281. const uint64MantissaBits = 52
  282. const maxExponent = int16(len(jsonFloat64Pow10)) - 1
  283. parseUsingStrConv := x.manOverflow ||
  284. x.exponent > maxExponent ||
  285. (x.exponent < 0 && -(x.exponent) > maxExponent) ||
  286. x.mantissa>>uint64MantissaBits != 0
  287. if parseUsingStrConv {
  288. var err error
  289. if f, err = strconv.ParseFloat(stringView(x.bytes), 64); err != nil {
  290. panic(fmt.Errorf("parse float: %s, %v", x.bytes, err))
  291. return
  292. }
  293. if x.neg {
  294. f = -f
  295. }
  296. return
  297. }
  298. // all good. so handle parse here.
  299. f = float64(x.mantissa)
  300. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  301. if x.neg {
  302. f = -f
  303. }
  304. if x.exponent > 0 {
  305. f *= jsonFloat64Pow10[x.exponent]
  306. } else if x.exponent < 0 {
  307. f /= jsonFloat64Pow10[-x.exponent]
  308. }
  309. return
  310. }
  311. type jsonDecDriver struct {
  312. d *Decoder
  313. h *JsonHandle
  314. r decReader // *bytesDecReader decReader
  315. ct valueType // container type. one of unset, array or map.
  316. bstr [8]byte // scratch used for string \UXXX parsing
  317. b [64]byte // scratch
  318. wsSkipped bool // whitespace skipped
  319. n jsonNum
  320. noBuiltInTypes
  321. }
  322. // This will skip whitespace characters and return the next byte to read.
  323. // The next byte determines what the value will be one of.
  324. func (d *jsonDecDriver) skipWhitespace(unread bool) (b byte) {
  325. // as initReadNext is not called all the time, we set ct to unSet whenever
  326. // we skipwhitespace, as this is the signal that something new is about to be read.
  327. d.ct = valueTypeUnset
  328. b = d.r.readn1()
  329. if !jsonTrackSkipWhitespace || !d.wsSkipped {
  330. for ; b == ' ' || b == '\t' || b == '\r' || b == '\n'; b = d.r.readn1() {
  331. }
  332. if jsonTrackSkipWhitespace {
  333. d.wsSkipped = true
  334. }
  335. }
  336. if unread {
  337. d.r.unreadn1()
  338. }
  339. return b
  340. }
  341. func (d *jsonDecDriver) CheckBreak() bool {
  342. b := d.skipWhitespace(true)
  343. return b == '}' || b == ']'
  344. }
  345. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  346. bs := d.r.readx(int(toIdx - fromIdx))
  347. if jsonValidateSymbols {
  348. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  349. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  350. return
  351. }
  352. }
  353. if jsonTrackSkipWhitespace {
  354. d.wsSkipped = false
  355. }
  356. }
  357. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  358. b := d.skipWhitespace(true)
  359. if b == 'n' {
  360. d.readStrIdx(9, 13) // null
  361. d.ct = valueTypeNil
  362. return true
  363. }
  364. return false
  365. }
  366. func (d *jsonDecDriver) DecodeBool() bool {
  367. b := d.skipWhitespace(false)
  368. if b == 'f' {
  369. d.readStrIdx(5, 9) // alse
  370. return false
  371. }
  372. if b == 't' {
  373. d.readStrIdx(1, 4) // rue
  374. return true
  375. }
  376. d.d.errorf("json: decode bool: got first char %c", b)
  377. return false // "unreachable"
  378. }
  379. func (d *jsonDecDriver) ReadMapStart() int {
  380. d.expectChar('{')
  381. d.ct = valueTypeMap
  382. return -1
  383. }
  384. func (d *jsonDecDriver) ReadArrayStart() int {
  385. d.expectChar('[')
  386. d.ct = valueTypeArray
  387. return -1
  388. }
  389. func (d *jsonDecDriver) ReadMapEnd() {
  390. d.expectChar('}')
  391. }
  392. func (d *jsonDecDriver) ReadArrayEnd() {
  393. d.expectChar(']')
  394. }
  395. func (d *jsonDecDriver) ReadArrayEntrySeparator() {
  396. d.expectChar(',')
  397. }
  398. func (d *jsonDecDriver) ReadMapEntrySeparator() {
  399. d.expectChar(',')
  400. }
  401. func (d *jsonDecDriver) ReadMapKVSeparator() {
  402. d.expectChar(':')
  403. }
  404. func (d *jsonDecDriver) expectChar(c uint8) {
  405. b := d.skipWhitespace(false)
  406. if b != c {
  407. d.d.errorf("json: expect char %c but got char %c", c, b)
  408. return
  409. }
  410. if jsonTrackSkipWhitespace {
  411. d.wsSkipped = false
  412. }
  413. }
  414. func (d *jsonDecDriver) IsContainerType(vt valueType) bool {
  415. // check container type by checking the first char
  416. if d.ct == valueTypeUnset {
  417. b := d.skipWhitespace(true)
  418. if b == '{' {
  419. d.ct = valueTypeMap
  420. } else if b == '[' {
  421. d.ct = valueTypeArray
  422. } else if b == 'n' {
  423. d.ct = valueTypeNil
  424. } else if b == '"' {
  425. d.ct = valueTypeString
  426. }
  427. }
  428. if vt == valueTypeNil || vt == valueTypeBytes || vt == valueTypeString ||
  429. vt == valueTypeArray || vt == valueTypeMap {
  430. return d.ct == vt
  431. }
  432. // ugorji: made switch into conditionals, so that IsContainerType can be inlined.
  433. // switch vt {
  434. // case valueTypeNil, valueTypeBytes, valueTypeString, valueTypeArray, valueTypeMap:
  435. // return d.ct == vt
  436. // }
  437. d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  438. return false // "unreachable"
  439. }
  440. func (d *jsonDecDriver) decNum(storeBytes bool) {
  441. // storeBytes = true // TODO: remove.
  442. // If it is has a . or an e|E, decode as a float; else decode as an int.
  443. b := d.skipWhitespace(false)
  444. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  445. d.d.errorf("json: decNum: got first char '%c'", b)
  446. return
  447. }
  448. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  449. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  450. // var n jsonNum // create stack-copy jsonNum, and set to pointer at end.
  451. // n.bytes = d.n.bytes[:0]
  452. n := &d.n
  453. n.reset()
  454. // The format of a number is as below:
  455. // parsing: sign? digit* dot? digit* e? sign? digit*
  456. // states: 0 1* 2 3* 4 5* 6 7
  457. // We honor this state so we can break correctly.
  458. var state uint8 = 0
  459. var eNeg bool
  460. var e int16
  461. var eof bool
  462. LOOP:
  463. for !eof {
  464. // fmt.Printf("LOOP: b: %q\n", b)
  465. switch b {
  466. case '+':
  467. switch state {
  468. case 0:
  469. state = 2
  470. // do not add sign to the slice ...
  471. b, eof = d.r.readn1eof()
  472. continue
  473. case 6: // typ = jsonNumFloat
  474. state = 7
  475. default:
  476. break LOOP
  477. }
  478. case '-':
  479. switch state {
  480. case 0:
  481. state = 2
  482. n.neg = true
  483. // do not add sign to the slice ...
  484. b, eof = d.r.readn1eof()
  485. continue
  486. case 6: // typ = jsonNumFloat
  487. eNeg = true
  488. state = 7
  489. default:
  490. break LOOP
  491. }
  492. case '.':
  493. switch state {
  494. case 0, 2: // typ = jsonNumFloat
  495. state = 4
  496. n.dot = true
  497. default:
  498. break LOOP
  499. }
  500. case 'e', 'E':
  501. switch state {
  502. case 0, 2, 4: // typ = jsonNumFloat
  503. state = 6
  504. // n.mantissaEndIndex = int16(len(n.bytes))
  505. n.explicitExponent = true
  506. default:
  507. break LOOP
  508. }
  509. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  510. switch state {
  511. case 0:
  512. state = 2
  513. fallthrough
  514. case 2:
  515. fallthrough
  516. case 4:
  517. if n.dot {
  518. n.exponent--
  519. }
  520. if n.mantissa >= jsonNumUintCutoff {
  521. n.manOverflow = true
  522. break
  523. }
  524. v := uint64(b - '0')
  525. n.mantissa *= 10
  526. if v != 0 {
  527. n1 := n.mantissa + v
  528. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  529. n.manOverflow = true // n+v overflows
  530. break
  531. }
  532. n.mantissa = n1
  533. }
  534. case 6:
  535. state = 7
  536. fallthrough
  537. case 7:
  538. if !(b == '0' && e == 0) {
  539. e = e*10 + int16(b-'0')
  540. }
  541. default:
  542. break LOOP
  543. }
  544. default:
  545. break LOOP
  546. }
  547. if storeBytes {
  548. n.bytes = append(n.bytes, b)
  549. }
  550. b, eof = d.r.readn1eof()
  551. }
  552. if jsonTruncateMantissa && n.mantissa != 0 {
  553. for n.mantissa%10 == 0 {
  554. n.mantissa /= 10
  555. n.exponent++
  556. }
  557. }
  558. if e != 0 {
  559. if eNeg {
  560. n.exponent -= e
  561. } else {
  562. n.exponent += e
  563. }
  564. }
  565. // d.n = n
  566. if !eof {
  567. d.r.unreadn1()
  568. }
  569. if jsonTrackSkipWhitespace {
  570. d.wsSkipped = false
  571. }
  572. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  573. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  574. return
  575. }
  576. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  577. d.decNum(false)
  578. n := &d.n
  579. if n.manOverflow {
  580. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  581. return
  582. }
  583. var u uint64
  584. if n.exponent == 0 {
  585. u = n.mantissa
  586. } else if n.exponent < 0 {
  587. d.d.errorf("json: fractional integer")
  588. return
  589. } else if n.exponent > 0 {
  590. var overflow bool
  591. if u, overflow = n.uintExp(); overflow {
  592. d.d.errorf("json: overflow integer")
  593. return
  594. }
  595. }
  596. i = int64(u)
  597. if n.neg {
  598. i = -i
  599. }
  600. if chkOvf.Int(i, bitsize) {
  601. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  602. return
  603. }
  604. // fmt.Printf("DecodeInt: %v\n", i)
  605. return
  606. }
  607. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  608. d.decNum(false)
  609. n := &d.n
  610. if n.neg {
  611. d.d.errorf("json: unsigned integer cannot be negative")
  612. return
  613. }
  614. if n.manOverflow {
  615. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  616. return
  617. }
  618. if n.exponent == 0 {
  619. u = n.mantissa
  620. } else if n.exponent < 0 {
  621. d.d.errorf("json: fractional integer")
  622. return
  623. } else if n.exponent > 0 {
  624. var overflow bool
  625. if u, overflow = n.uintExp(); overflow {
  626. d.d.errorf("json: overflow integer")
  627. return
  628. }
  629. }
  630. if chkOvf.Uint(u, bitsize) {
  631. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  632. return
  633. }
  634. // fmt.Printf("DecodeUint: %v\n", u)
  635. return
  636. }
  637. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  638. d.decNum(true)
  639. n := &d.n
  640. f = n.floatVal()
  641. if chkOverflow32 && chkOvf.Float32(f) {
  642. d.d.errorf("json: overflow float32: %v, %s", f, n.bytes)
  643. return
  644. }
  645. return
  646. }
  647. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  648. if ext == nil {
  649. re := rv.(*RawExt)
  650. re.Tag = xtag
  651. d.d.decode(&re.Value)
  652. } else {
  653. var v interface{}
  654. d.d.decode(&v)
  655. ext.UpdateExt(rv, v)
  656. }
  657. return
  658. }
  659. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  660. // zerocopy doesn't matter for json, as the bytes must be parsed.
  661. bs0 := d.appendStringAsBytes(d.b[:0])
  662. if isstring {
  663. return bs0
  664. }
  665. slen := base64.StdEncoding.DecodedLen(len(bs0))
  666. if cap(bs) >= slen {
  667. bsOut = bs[:slen]
  668. } else {
  669. bsOut = make([]byte, slen)
  670. }
  671. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  672. if err != nil {
  673. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  674. return nil
  675. }
  676. if slen != slen2 {
  677. bsOut = bsOut[:slen2]
  678. }
  679. return
  680. }
  681. func (d *jsonDecDriver) DecodeString() (s string) {
  682. return string(d.appendStringAsBytes(d.b[:0]))
  683. }
  684. func (d *jsonDecDriver) appendStringAsBytes(v []byte) []byte {
  685. d.expectChar('"')
  686. for {
  687. c := d.r.readn1()
  688. if c == '"' {
  689. break
  690. } else if c == '\\' {
  691. c = d.r.readn1()
  692. switch c {
  693. case '"', '\\', '/', '\'':
  694. v = append(v, c)
  695. case 'b':
  696. v = append(v, '\b')
  697. case 'f':
  698. v = append(v, '\f')
  699. case 'n':
  700. v = append(v, '\n')
  701. case 'r':
  702. v = append(v, '\r')
  703. case 't':
  704. v = append(v, '\t')
  705. case 'u':
  706. rr := d.jsonU4(false)
  707. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  708. if utf16.IsSurrogate(rr) {
  709. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  710. }
  711. w2 := utf8.EncodeRune(d.bstr[:], rr)
  712. v = append(v, d.bstr[:w2]...)
  713. default:
  714. d.d.errorf("json: unsupported escaped value: %c", c)
  715. return nil
  716. }
  717. } else {
  718. v = append(v, c)
  719. }
  720. }
  721. if jsonTrackSkipWhitespace {
  722. d.wsSkipped = false
  723. }
  724. return v
  725. }
  726. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  727. if checkSlashU && !(d.r.readn1() == '\\' && d.r.readn1() == 'u') {
  728. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  729. return 0
  730. }
  731. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  732. var u uint32
  733. for i := 0; i < 4; i++ {
  734. v := d.r.readn1()
  735. if '0' <= v && v <= '9' {
  736. v = v - '0'
  737. } else if 'a' <= v && v <= 'z' {
  738. v = v - 'a' + 10
  739. } else if 'A' <= v && v <= 'Z' {
  740. v = v - 'A' + 10
  741. } else {
  742. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  743. return 0
  744. }
  745. u = u*16 + uint32(v)
  746. }
  747. return rune(u)
  748. }
  749. func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
  750. n := d.skipWhitespace(true)
  751. switch n {
  752. case 'n':
  753. d.readStrIdx(9, 13) // null
  754. vt = valueTypeNil
  755. case 'f':
  756. d.readStrIdx(4, 9) // false
  757. vt = valueTypeBool
  758. v = false
  759. case 't':
  760. d.readStrIdx(0, 4) // true
  761. vt = valueTypeBool
  762. v = true
  763. case '{':
  764. vt = valueTypeMap
  765. decodeFurther = true
  766. case '[':
  767. vt = valueTypeArray
  768. decodeFurther = true
  769. case '"':
  770. vt = valueTypeString
  771. v = d.DecodeString()
  772. default: // number
  773. d.decNum(true)
  774. n := &d.n
  775. // if the string had a any of [.eE], then decode as float.
  776. switch {
  777. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  778. vt = valueTypeFloat
  779. v = n.floatVal()
  780. case n.exponent == 0:
  781. u := n.mantissa
  782. switch {
  783. case n.neg:
  784. vt = valueTypeInt
  785. v = -int64(u)
  786. case d.h.SignedInteger:
  787. vt = valueTypeInt
  788. v = int64(u)
  789. default:
  790. vt = valueTypeUint
  791. v = u
  792. }
  793. default:
  794. u, overflow := n.uintExp()
  795. switch {
  796. case overflow:
  797. vt = valueTypeFloat
  798. v = n.floatVal()
  799. case n.neg:
  800. vt = valueTypeInt
  801. v = -int64(u)
  802. case d.h.SignedInteger:
  803. vt = valueTypeInt
  804. v = int64(u)
  805. default:
  806. vt = valueTypeUint
  807. v = u
  808. }
  809. }
  810. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  811. }
  812. return
  813. }
  814. //----------------------
  815. // JsonHandle is a handle for JSON encoding format.
  816. //
  817. // Json is comprehensively supported:
  818. // - decodes numbers into interface{} as int, uint or float64
  819. // - encodes and decodes []byte using base64 Std Encoding
  820. // - UTF-8 support for encoding and decoding
  821. //
  822. // It has better performance than the json library in the standard library,
  823. // by leveraging the performance improvements of the codec library and
  824. // minimizing allocations.
  825. //
  826. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  827. // reading multiple values from a stream containing json and non-json content.
  828. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  829. // all from the same stream in sequence.
  830. type JsonHandle struct {
  831. BasicHandle
  832. textEncodingType
  833. }
  834. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  835. return &jsonEncDriver{e: e, w: e.w, h: h}
  836. }
  837. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  838. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  839. hd := jsonDecDriver{d: d, r: d.r, h: h}
  840. hd.n.bytes = d.b[:]
  841. return &hd
  842. }
  843. var jsonEncodeTerminate = []byte{' '}
  844. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  845. return jsonEncodeTerminate
  846. }
  847. var _ decDriver = (*jsonDecDriver)(nil)
  848. var _ encDriver = (*jsonEncDriver)(nil)