json.go 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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.quoteBytes(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. w.writestr(`\u00`)
  195. w.writen1(hex[b>>4])
  196. w.writen1(hex[b&0xF])
  197. }
  198. i++
  199. start = i
  200. continue
  201. }
  202. c, size := utf8.DecodeRuneInString(s[i:])
  203. if c == utf8.RuneError && size == 1 {
  204. if start < i {
  205. w.writestr(s[start:i])
  206. }
  207. w.writestr(`\ufffd`)
  208. i += size
  209. start = i
  210. continue
  211. }
  212. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  213. // Both technically valid JSON, but bomb on JSONP, so fix here.
  214. if c == '\u2028' || c == '\u2029' {
  215. if start < i {
  216. w.writestr(s[start:i])
  217. }
  218. w.writestr(`\u202`)
  219. w.writen1(hex[c&0xF])
  220. i += size
  221. start = i
  222. continue
  223. }
  224. i += size
  225. }
  226. if start < len(s) {
  227. w.writestr(s[start:])
  228. }
  229. w.writen1('"')
  230. }
  231. // keep this in sync with quoteStr above. Needed to elide the str->[]byte allocation.
  232. // This may be automatically called from EncodeStringBytes, called by MarshalText implementers.
  233. func (e *jsonEncDriver) quoteBytes(s []byte) {
  234. // adapted from std pkg encoding/json
  235. const hex = "0123456789abcdef"
  236. w := e.w
  237. w.writen1('"')
  238. start := 0
  239. for i := 0; i < len(s); {
  240. if b := s[i]; b < utf8.RuneSelf {
  241. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  242. i++
  243. continue
  244. }
  245. if start < i {
  246. w.writeb(s[start:i])
  247. }
  248. switch b {
  249. case '\\', '"':
  250. w.writen2('\\', b)
  251. case '\n':
  252. w.writen2('\\', 'n')
  253. case '\r':
  254. w.writen2('\\', 'r')
  255. case '\b':
  256. w.writen2('\\', 'b')
  257. case '\f':
  258. w.writen2('\\', 'f')
  259. case '\t':
  260. w.writen2('\\', 't')
  261. default:
  262. w.writestr(`\u00`)
  263. w.writen1(hex[b>>4])
  264. w.writen1(hex[b&0xF])
  265. }
  266. i++
  267. start = i
  268. continue
  269. }
  270. c, size := utf8.DecodeRune(s[i:])
  271. if c == utf8.RuneError && size == 1 {
  272. if start < i {
  273. w.writeb(s[start:i])
  274. }
  275. w.writestr(`\ufffd`)
  276. i += size
  277. start = i
  278. continue
  279. }
  280. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  281. // Both technically valid JSON, but bomb on JSONP, so fix here.
  282. if c == '\u2028' || c == '\u2029' {
  283. if start < i {
  284. w.writeb(s[start:i])
  285. }
  286. w.writestr(`\u202`)
  287. w.writen1(hex[c&0xF])
  288. i += size
  289. start = i
  290. continue
  291. }
  292. i += size
  293. }
  294. if start < len(s) {
  295. w.writeb(s[start:])
  296. }
  297. w.writen1('"')
  298. }
  299. //--------------------------------
  300. type jsonNum struct {
  301. bytes []byte // may have [+-.eE0-9]
  302. mantissa uint64 // where mantissa ends, and maybe dot begins.
  303. exponent int16 // exponent value.
  304. manOverflow bool
  305. neg bool // started with -. No initial sign in the bytes above.
  306. dot bool // has dot
  307. explicitExponent bool // explicit exponent
  308. }
  309. func (x *jsonNum) reset() {
  310. x.bytes = x.bytes[:0]
  311. x.manOverflow = false
  312. x.neg = false
  313. x.dot = false
  314. x.explicitExponent = false
  315. x.mantissa = 0
  316. x.exponent = 0
  317. }
  318. // uintExp is called only if exponent > 0.
  319. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  320. n = x.mantissa
  321. e := x.exponent
  322. if e >= int16(len(jsonUint64Pow10)) {
  323. overflow = true
  324. return
  325. }
  326. n *= jsonUint64Pow10[e]
  327. if n < x.mantissa || n > jsonNumUintMaxVal {
  328. overflow = true
  329. return
  330. }
  331. return
  332. // for i := int16(0); i < e; i++ {
  333. // if n >= jsonNumUintCutoff {
  334. // overflow = true
  335. // return
  336. // }
  337. // n *= 10
  338. // }
  339. // return
  340. }
  341. func (x *jsonNum) floatVal() (f float64) {
  342. // We do not want to lose precision.
  343. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  344. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  345. // We expect up to 99.... (19 digits)
  346. // - The mantissa cannot fit into a 52 bits of uint64
  347. // - The exponent is beyond our scope ie beyong 22.
  348. const uint64MantissaBits = 52
  349. const maxExponent = int16(len(jsonFloat64Pow10)) - 1
  350. parseUsingStrConv := x.manOverflow ||
  351. x.exponent > maxExponent ||
  352. (x.exponent < 0 && -(x.exponent) > maxExponent) ||
  353. x.mantissa>>uint64MantissaBits != 0
  354. if parseUsingStrConv {
  355. var err error
  356. if f, err = strconv.ParseFloat(stringView(x.bytes), 64); err != nil {
  357. panic(fmt.Errorf("parse float: %s, %v", x.bytes, err))
  358. return
  359. }
  360. if x.neg {
  361. f = -f
  362. }
  363. return
  364. }
  365. // all good. so handle parse here.
  366. f = float64(x.mantissa)
  367. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  368. if x.neg {
  369. f = -f
  370. }
  371. if x.exponent > 0 {
  372. f *= jsonFloat64Pow10[x.exponent]
  373. } else if x.exponent < 0 {
  374. f /= jsonFloat64Pow10[-x.exponent]
  375. }
  376. return
  377. }
  378. type jsonDecDriver struct {
  379. d *Decoder
  380. h *JsonHandle
  381. r decReader // *bytesDecReader decReader
  382. ct valueType // container type. one of unset, array or map.
  383. bstr [8]byte // scratch used for string \UXXX parsing
  384. b [64]byte // scratch
  385. wsSkipped bool // whitespace skipped
  386. n jsonNum
  387. noBuiltInTypes
  388. }
  389. // This will skip whitespace characters and return the next byte to read.
  390. // The next byte determines what the value will be one of.
  391. func (d *jsonDecDriver) skipWhitespace(unread bool) (b byte) {
  392. // as initReadNext is not called all the time, we set ct to unSet whenever
  393. // we skipwhitespace, as this is the signal that something new is about to be read.
  394. d.ct = valueTypeUnset
  395. b = d.r.readn1()
  396. if !jsonTrackSkipWhitespace || !d.wsSkipped {
  397. for ; b == ' ' || b == '\t' || b == '\r' || b == '\n'; b = d.r.readn1() {
  398. }
  399. if jsonTrackSkipWhitespace {
  400. d.wsSkipped = true
  401. }
  402. }
  403. if unread {
  404. d.r.unreadn1()
  405. }
  406. return b
  407. }
  408. func (d *jsonDecDriver) CheckBreak() bool {
  409. b := d.skipWhitespace(true)
  410. return b == '}' || b == ']'
  411. }
  412. // func (d *jsonDecDriver) readStr(s []byte) {
  413. // if jsonValidateSymbols {
  414. // bs := d.b[:len(s)]
  415. // d.r.readb(bs)
  416. // if !bytes.Equal(bs, s) {
  417. // d.d.errorf("json: expecting %s: got %s", s, bs)
  418. // return
  419. // }
  420. // } else {
  421. // d.r.readx(len(s))
  422. // }
  423. // if jsonTrackSkipWhitespace {
  424. // d.wsSkipped = false
  425. // }
  426. // }
  427. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  428. if jsonValidateSymbols {
  429. bs := d.b[:(toIdx - fromIdx)]
  430. d.r.readb(bs)
  431. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  432. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  433. return
  434. }
  435. } else {
  436. d.r.readx(int(toIdx - fromIdx))
  437. }
  438. if jsonTrackSkipWhitespace {
  439. d.wsSkipped = false
  440. }
  441. }
  442. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  443. b := d.skipWhitespace(true)
  444. if b == 'n' {
  445. d.readStrIdx(9, 13) // null
  446. d.ct = valueTypeNil
  447. return true
  448. }
  449. return false
  450. }
  451. func (d *jsonDecDriver) DecodeBool() bool {
  452. b := d.skipWhitespace(false)
  453. if b == 'f' {
  454. d.readStrIdx(5, 9) // alse
  455. return false
  456. }
  457. if b == 't' {
  458. d.readStrIdx(1, 4) // rue
  459. return true
  460. }
  461. d.d.errorf("json: decode bool: got first char %c", b)
  462. return false // "unreachable"
  463. }
  464. func (d *jsonDecDriver) ReadMapStart() int {
  465. d.expectChar('{')
  466. d.ct = valueTypeMap
  467. return -1
  468. }
  469. func (d *jsonDecDriver) ReadArrayStart() int {
  470. d.expectChar('[')
  471. d.ct = valueTypeArray
  472. return -1
  473. }
  474. func (d *jsonDecDriver) ReadMapEnd() {
  475. d.expectChar('}')
  476. }
  477. func (d *jsonDecDriver) ReadArrayEnd() {
  478. d.expectChar(']')
  479. }
  480. func (d *jsonDecDriver) ReadArrayEntrySeparator() {
  481. d.expectChar(',')
  482. }
  483. func (d *jsonDecDriver) ReadMapEntrySeparator() {
  484. d.expectChar(',')
  485. }
  486. func (d *jsonDecDriver) ReadMapKVSeparator() {
  487. d.expectChar(':')
  488. }
  489. func (d *jsonDecDriver) expectChar(c uint8) {
  490. b := d.skipWhitespace(false)
  491. if b != c {
  492. d.d.errorf("json: expect char %c but got char %c", c, b)
  493. return
  494. }
  495. if jsonTrackSkipWhitespace {
  496. d.wsSkipped = false
  497. }
  498. }
  499. func (d *jsonDecDriver) IsContainerType(vt valueType) bool {
  500. // check container type by checking the first char
  501. if d.ct == valueTypeUnset {
  502. b := d.skipWhitespace(true)
  503. if b == '{' {
  504. d.ct = valueTypeMap
  505. } else if b == '[' {
  506. d.ct = valueTypeArray
  507. } else if b == 'n' {
  508. d.ct = valueTypeNil
  509. } else if b == '"' {
  510. d.ct = valueTypeString
  511. }
  512. }
  513. if vt == valueTypeNil || vt == valueTypeBytes || vt == valueTypeString ||
  514. vt == valueTypeArray || vt == valueTypeMap {
  515. return d.ct == vt
  516. }
  517. // ugorji: made switch into conditionals, so that IsContainerType can be inlined.
  518. // switch vt {
  519. // case valueTypeNil, valueTypeBytes, valueTypeString, valueTypeArray, valueTypeMap:
  520. // return d.ct == vt
  521. // }
  522. d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  523. return false // "unreachable"
  524. }
  525. func (d *jsonDecDriver) decNum(storeBytes bool) {
  526. // storeBytes = true // TODO: remove.
  527. // If it is has a . or an e|E, decode as a float; else decode as an int.
  528. b := d.skipWhitespace(false)
  529. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  530. d.d.errorf("json: decNum: got first char '%c'", b)
  531. return
  532. }
  533. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  534. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  535. // var n jsonNum // create stack-copy jsonNum, and set to pointer at end.
  536. // n.bytes = d.n.bytes[:0]
  537. n := &d.n
  538. n.reset()
  539. // The format of a number is as below:
  540. // parsing: sign? digit* dot? digit* e? sign? digit*
  541. // states: 0 1* 2 3* 4 5* 6 7
  542. // We honor this state so we can break correctly.
  543. var state uint8 = 0
  544. var eNeg bool
  545. var e int16
  546. var eof bool
  547. LOOP:
  548. for !eof {
  549. // fmt.Printf("LOOP: b: %q\n", b)
  550. switch b {
  551. case '+':
  552. switch state {
  553. case 0:
  554. state = 2
  555. // do not add sign to the slice ...
  556. b, eof = d.r.readn1eof()
  557. continue
  558. case 6: // typ = jsonNumFloat
  559. state = 7
  560. default:
  561. break LOOP
  562. }
  563. case '-':
  564. switch state {
  565. case 0:
  566. state = 2
  567. n.neg = true
  568. // do not add sign to the slice ...
  569. b, eof = d.r.readn1eof()
  570. continue
  571. case 6: // typ = jsonNumFloat
  572. eNeg = true
  573. state = 7
  574. default:
  575. break LOOP
  576. }
  577. case '.':
  578. switch state {
  579. case 0, 2: // typ = jsonNumFloat
  580. state = 4
  581. n.dot = true
  582. default:
  583. break LOOP
  584. }
  585. case 'e', 'E':
  586. switch state {
  587. case 0, 2, 4: // typ = jsonNumFloat
  588. state = 6
  589. // n.mantissaEndIndex = int16(len(n.bytes))
  590. n.explicitExponent = true
  591. default:
  592. break LOOP
  593. }
  594. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  595. switch state {
  596. case 0:
  597. state = 2
  598. fallthrough
  599. case 2:
  600. fallthrough
  601. case 4:
  602. if n.dot {
  603. n.exponent--
  604. }
  605. if n.mantissa >= jsonNumUintCutoff {
  606. n.manOverflow = true
  607. break
  608. }
  609. v := uint64(b - '0')
  610. n.mantissa *= 10
  611. if v != 0 {
  612. n1 := n.mantissa + v
  613. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  614. n.manOverflow = true // n+v overflows
  615. break
  616. }
  617. n.mantissa = n1
  618. }
  619. case 6:
  620. state = 7
  621. fallthrough
  622. case 7:
  623. if !(b == '0' && e == 0) {
  624. e = e*10 + int16(b-'0')
  625. }
  626. default:
  627. break LOOP
  628. }
  629. default:
  630. break LOOP
  631. }
  632. if storeBytes {
  633. n.bytes = append(n.bytes, b)
  634. }
  635. b, eof = d.r.readn1eof()
  636. }
  637. if jsonTruncateMantissa && n.mantissa != 0 {
  638. for n.mantissa%10 == 0 {
  639. n.mantissa /= 10
  640. n.exponent++
  641. }
  642. }
  643. if e != 0 {
  644. if eNeg {
  645. n.exponent -= e
  646. } else {
  647. n.exponent += e
  648. }
  649. }
  650. // d.n = n
  651. if !eof {
  652. d.r.unreadn1()
  653. }
  654. if jsonTrackSkipWhitespace {
  655. d.wsSkipped = false
  656. }
  657. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  658. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  659. return
  660. }
  661. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  662. d.decNum(false)
  663. n := &d.n
  664. if n.manOverflow {
  665. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  666. return
  667. }
  668. var u uint64
  669. if n.exponent == 0 {
  670. u = n.mantissa
  671. } else if n.exponent < 0 {
  672. d.d.errorf("json: fractional integer")
  673. return
  674. } else if n.exponent > 0 {
  675. var overflow bool
  676. if u, overflow = n.uintExp(); overflow {
  677. d.d.errorf("json: overflow integer")
  678. return
  679. }
  680. }
  681. i = int64(u)
  682. if n.neg {
  683. i = -i
  684. }
  685. if chkOvf.Int(i, bitsize) {
  686. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  687. return
  688. }
  689. // fmt.Printf("DecodeInt: %v\n", i)
  690. return
  691. }
  692. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  693. d.decNum(false)
  694. n := &d.n
  695. if n.neg {
  696. d.d.errorf("json: unsigned integer cannot be negative")
  697. return
  698. }
  699. if n.manOverflow {
  700. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  701. return
  702. }
  703. if n.exponent == 0 {
  704. u = n.mantissa
  705. } else if n.exponent < 0 {
  706. d.d.errorf("json: fractional integer")
  707. return
  708. } else if n.exponent > 0 {
  709. var overflow bool
  710. if u, overflow = n.uintExp(); overflow {
  711. d.d.errorf("json: overflow integer")
  712. return
  713. }
  714. }
  715. if chkOvf.Uint(u, bitsize) {
  716. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  717. return
  718. }
  719. // fmt.Printf("DecodeUint: %v\n", u)
  720. return
  721. }
  722. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  723. d.decNum(true)
  724. n := &d.n
  725. f = n.floatVal()
  726. if chkOverflow32 && chkOvf.Float32(f) {
  727. d.d.errorf("json: overflow float32: %v, %s", f, n.bytes)
  728. return
  729. }
  730. return
  731. }
  732. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  733. if ext == nil {
  734. re := rv.(*RawExt)
  735. re.Tag = xtag
  736. d.d.decode(&re.Value)
  737. } else {
  738. var v interface{}
  739. d.d.decode(&v)
  740. ext.UpdateExt(rv, v)
  741. }
  742. return
  743. }
  744. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  745. // zerocopy doesn't matter for json, as the bytes must be parsed.
  746. bs0 := d.appendStringAsBytes(d.b[:0])
  747. if isstring {
  748. return bs0
  749. }
  750. slen := base64.StdEncoding.DecodedLen(len(bs0))
  751. if cap(bs) >= slen {
  752. bsOut = bs[:slen]
  753. } else {
  754. bsOut = make([]byte, slen)
  755. }
  756. base64.StdEncoding.Decode(bsOut, bs0)
  757. return
  758. }
  759. func (d *jsonDecDriver) DecodeString() (s string) {
  760. return string(d.appendStringAsBytes(d.b[:0]))
  761. }
  762. func (d *jsonDecDriver) appendStringAsBytes(v []byte) []byte {
  763. d.expectChar('"')
  764. for {
  765. c := d.r.readn1()
  766. if c == '"' {
  767. break
  768. } else if c == '\\' {
  769. c = d.r.readn1()
  770. switch c {
  771. case '"', '\\', '/', '\'':
  772. v = append(v, c)
  773. case 'b':
  774. v = append(v, '\b')
  775. case 'f':
  776. v = append(v, '\f')
  777. case 'n':
  778. v = append(v, '\n')
  779. case 'r':
  780. v = append(v, '\r')
  781. case 't':
  782. v = append(v, '\t')
  783. case 'u':
  784. rr := d.jsonU4(false)
  785. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  786. if utf16.IsSurrogate(rr) {
  787. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  788. }
  789. w2 := utf8.EncodeRune(d.bstr[:], rr)
  790. v = append(v, d.bstr[:w2]...)
  791. default:
  792. d.d.errorf("json: unsupported escaped value: %c", c)
  793. return nil
  794. }
  795. } else {
  796. v = append(v, c)
  797. }
  798. }
  799. if jsonTrackSkipWhitespace {
  800. d.wsSkipped = false
  801. }
  802. return v
  803. }
  804. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  805. if checkSlashU && !(d.r.readn1() == '\\' && d.r.readn1() == 'u') {
  806. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  807. return 0
  808. }
  809. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  810. var u uint32
  811. for i := 0; i < 4; i++ {
  812. v := d.r.readn1()
  813. if '0' <= v && v <= '9' {
  814. v = v - '0'
  815. } else if 'a' <= v && v <= 'z' {
  816. v = v - 'a' + 10
  817. } else if 'A' <= v && v <= 'Z' {
  818. v = v - 'A' + 10
  819. } else {
  820. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  821. return 0
  822. }
  823. u = u*10 + uint32(v)
  824. }
  825. return rune(u)
  826. }
  827. func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
  828. n := d.skipWhitespace(true)
  829. switch n {
  830. case 'n':
  831. d.readStrIdx(9, 13) // null
  832. vt = valueTypeNil
  833. case 'f':
  834. d.readStrIdx(4, 9) // false
  835. vt = valueTypeBool
  836. v = false
  837. case 't':
  838. d.readStrIdx(0, 4) // true
  839. vt = valueTypeBool
  840. v = true
  841. case '{':
  842. vt = valueTypeMap
  843. decodeFurther = true
  844. case '[':
  845. vt = valueTypeArray
  846. decodeFurther = true
  847. case '"':
  848. vt = valueTypeString
  849. v = d.DecodeString()
  850. default: // number
  851. d.decNum(true)
  852. n := &d.n
  853. // if the string had a any of [.eE], then decode as float.
  854. switch {
  855. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  856. vt = valueTypeFloat
  857. v = n.floatVal()
  858. case n.exponent == 0:
  859. u := n.mantissa
  860. switch {
  861. case n.neg:
  862. vt = valueTypeInt
  863. v = -int64(u)
  864. case d.h.SignedInteger:
  865. vt = valueTypeInt
  866. v = int64(u)
  867. default:
  868. vt = valueTypeUint
  869. v = u
  870. }
  871. default:
  872. u, overflow := n.uintExp()
  873. switch {
  874. case overflow:
  875. vt = valueTypeFloat
  876. v = n.floatVal()
  877. case n.neg:
  878. vt = valueTypeInt
  879. v = -int64(u)
  880. case d.h.SignedInteger:
  881. vt = valueTypeInt
  882. v = int64(u)
  883. default:
  884. vt = valueTypeUint
  885. v = u
  886. }
  887. }
  888. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  889. }
  890. return
  891. }
  892. //----------------------
  893. // JsonHandle is a handle for JSON encoding format.
  894. //
  895. // Json is comprehensively supported:
  896. // - decodes numbers into interface{} as int, uint or float64
  897. // - encodes and decodes []byte using base64 Std Encoding
  898. // - UTF-8 support for encoding and decoding
  899. //
  900. // It has better performance than the json library in the standard library,
  901. // by leveraging the performance improvements of the codec library and
  902. // minimizing allocations.
  903. //
  904. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  905. // reading multiple values from a stream containing json and non-json content.
  906. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  907. // all from the same stream in sequence.
  908. type JsonHandle struct {
  909. BasicHandle
  910. textEncodingType
  911. }
  912. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  913. return &jsonEncDriver{e: e, w: e.w, h: h}
  914. }
  915. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  916. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  917. hd := jsonDecDriver{d: d, r: d.r, h: h}
  918. hd.n.bytes = d.b[:]
  919. return &hd
  920. }
  921. var jsonEncodeTerminate = []byte{' '}
  922. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  923. return jsonEncodeTerminate
  924. }
  925. var _ decDriver = (*jsonDecDriver)(nil)
  926. var _ encDriver = (*jsonEncDriver)(nil)