json.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // By default, this json support uses base64 encoding for bytes, because you cannot
  5. // store and read any arbitrary string in json (only unicode).
  6. // However, the user can configre how to encode/decode bytes.
  7. //
  8. // This library specifically supports UTF-8 for encoding and decoding only.
  9. //
  10. // Note that the library will happily encode/decode things which are not valid
  11. // json e.g. a map[int64]string. We do it for consistency. With valid json,
  12. // we will encode and decode appropriately.
  13. // Users can specify their map type if necessary to force it.
  14. //
  15. // Note:
  16. // - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently.
  17. // We implement it here.
  18. // - Also, strconv.ParseXXX for floats and integers
  19. // - only works on strings resulting in unnecessary allocation and []byte-string conversion.
  20. // - it does a lot of redundant checks, because json numbers are simpler that what it supports.
  21. // - We parse numbers (floats and integers) directly here.
  22. // We only delegate parsing floats if it is a hairy float which could cause a loss of precision.
  23. // In that case, we delegate to strconv.ParseFloat.
  24. //
  25. // Note:
  26. // - encode does not beautify. There is no whitespace when encoding.
  27. // - rpc calls which take single integer arguments or write single numeric arguments will need care.
  28. // Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver
  29. // MUST not call one-another.
  30. import (
  31. "bytes"
  32. "encoding/base64"
  33. "reflect"
  34. "strconv"
  35. "unicode/utf16"
  36. "unicode/utf8"
  37. )
  38. //--------------------------------
  39. var (
  40. // jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
  41. jsonFloat64Pow10 = [...]float64{
  42. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  43. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  44. 1e20, 1e21, 1e22,
  45. }
  46. jsonUint64Pow10 = [...]uint64{
  47. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  48. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  49. }
  50. // jsonTabs and jsonSpaces are used as caches for indents
  51. jsonTabs, jsonSpaces string
  52. jsonCharHtmlSafeSet bitset128
  53. jsonCharSafeSet bitset128
  54. jsonCharWhitespaceSet bitset256
  55. jsonNumSet bitset256
  56. jsonU4Set [256]byte
  57. )
  58. const (
  59. // jsonUnreadAfterDecNum controls whether we unread after decoding a number.
  60. //
  61. // instead of unreading, just update d.tok (iff it's not a whitespace char)
  62. // However, doing this means that we may HOLD onto some data which belongs to another stream.
  63. // Thus, it is safest to unread the data when done.
  64. // keep behind a constant flag for now.
  65. jsonUnreadAfterDecNum = true
  66. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  67. // - If we see first character of null, false or true,
  68. // do not validate subsequent characters.
  69. // - e.g. if we see a n, assume null and skip next 3 characters,
  70. // and do not validate they are ull.
  71. // P.S. Do not expect a significant decoding boost from this.
  72. jsonValidateSymbols = true
  73. jsonSpacesOrTabsLen = 128
  74. jsonU4SetErrVal = 128
  75. )
  76. func init() {
  77. var bs [jsonSpacesOrTabsLen]byte
  78. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  79. bs[i] = ' '
  80. }
  81. jsonSpaces = string(bs[:])
  82. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  83. bs[i] = '\t'
  84. }
  85. jsonTabs = string(bs[:])
  86. // populate the safe values as true: note: ASCII control characters are (0-31)
  87. // jsonCharSafeSet: all true except (0-31) " \
  88. // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
  89. var i byte
  90. for i = 32; i < utf8.RuneSelf; i++ {
  91. switch i {
  92. case '"', '\\':
  93. case '<', '>', '&':
  94. jsonCharSafeSet.set(i) // = true
  95. default:
  96. jsonCharSafeSet.set(i)
  97. jsonCharHtmlSafeSet.set(i)
  98. }
  99. }
  100. for i = 0; i <= utf8.RuneSelf; i++ {
  101. switch i {
  102. case ' ', '\t', '\r', '\n':
  103. jsonCharWhitespaceSet.set(i)
  104. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
  105. jsonNumSet.set(i)
  106. }
  107. }
  108. for j := range jsonU4Set {
  109. switch i = byte(j); i {
  110. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  111. jsonU4Set[i] = i - '0'
  112. case 'a', 'b', 'c', 'd', 'e', 'f':
  113. jsonU4Set[i] = i - 'a' + 10
  114. case 'A', 'B', 'C', 'D', 'E', 'F':
  115. jsonU4Set[i] = i - 'A' + 10
  116. default:
  117. jsonU4Set[i] = jsonU4SetErrVal
  118. }
  119. }
  120. // jsonU4Set[255] = jsonU4SetErrVal
  121. }
  122. type jsonEncDriver struct {
  123. e *Encoder
  124. w encWriter
  125. h *JsonHandle
  126. b [64]byte // scratch
  127. bs []byte // scratch
  128. se setExtWrapper
  129. ds string // indent string
  130. dl uint16 // indent level
  131. dt bool // indent using tabs
  132. d bool // indent
  133. c containerState
  134. noBuiltInTypes
  135. }
  136. // indent is done as below:
  137. // - newline and indent are added before each mapKey or arrayElem
  138. // - newline and indent are added before each ending,
  139. // except there was no entry (so we can have {} or [])
  140. func (e *jsonEncDriver) sendContainerState(c containerState) {
  141. // determine whether to output separators
  142. switch c {
  143. case containerMapKey:
  144. if e.c != containerMapStart {
  145. e.w.writen1(',')
  146. }
  147. if e.d {
  148. e.writeIndent()
  149. }
  150. case containerMapValue:
  151. if e.d {
  152. e.w.writen2(':', ' ')
  153. } else {
  154. e.w.writen1(':')
  155. }
  156. case containerMapEnd:
  157. if e.d {
  158. e.dl--
  159. if e.c != containerMapStart {
  160. e.writeIndent()
  161. }
  162. }
  163. e.w.writen1('}')
  164. case containerArrayElem:
  165. if e.c != containerArrayStart {
  166. e.w.writen1(',')
  167. }
  168. if e.d {
  169. e.writeIndent()
  170. }
  171. case containerArrayEnd:
  172. if e.d {
  173. e.dl--
  174. if e.c != containerArrayStart {
  175. e.writeIndent()
  176. }
  177. }
  178. e.w.writen1(']')
  179. }
  180. e.c = c
  181. }
  182. func (e *jsonEncDriver) writeIndent() {
  183. e.w.writen1('\n')
  184. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  185. if e.dt {
  186. e.w.writestr(jsonTabs[:x])
  187. } else {
  188. e.w.writestr(jsonSpaces[:x])
  189. }
  190. } else {
  191. for i := uint16(0); i < e.dl; i++ {
  192. e.w.writestr(e.ds)
  193. }
  194. }
  195. }
  196. func (e *jsonEncDriver) EncodeNil() {
  197. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null
  198. }
  199. func (e *jsonEncDriver) EncodeBool(b bool) {
  200. if b {
  201. e.w.writen4('t', 'r', 'u', 'e') // e.w.writeb(jsonLiterals[0:4]) // true
  202. } else {
  203. e.w.writen5('f', 'a', 'l', 's', 'e') // e.w.writeb(jsonLiterals[4:9]) // false
  204. }
  205. }
  206. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  207. e.encodeFloat(float64(f), 32)
  208. }
  209. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  210. e.encodeFloat(f, 64)
  211. }
  212. func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
  213. x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
  214. e.w.writeb(x)
  215. if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
  216. e.w.writen2('.', '0')
  217. }
  218. }
  219. func (e *jsonEncDriver) EncodeInt(v int64) {
  220. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  221. e.w.writen1('"')
  222. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  223. e.w.writen1('"')
  224. return
  225. }
  226. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  227. }
  228. func (e *jsonEncDriver) EncodeUint(v uint64) {
  229. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  230. e.w.writen1('"')
  231. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  232. e.w.writen1('"')
  233. return
  234. }
  235. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  236. }
  237. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  238. if v := ext.ConvertExt(rv); v == nil {
  239. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  240. } else {
  241. en.encode(v)
  242. }
  243. }
  244. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  245. // only encodes re.Value (never re.Data)
  246. if re.Value == nil {
  247. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  248. } else {
  249. en.encode(re.Value)
  250. }
  251. }
  252. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  253. if e.d {
  254. e.dl++
  255. }
  256. e.w.writen1('[')
  257. e.c = containerArrayStart
  258. }
  259. func (e *jsonEncDriver) EncodeMapStart(length int) {
  260. if e.d {
  261. e.dl++
  262. }
  263. e.w.writen1('{')
  264. e.c = containerMapStart
  265. }
  266. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  267. e.quoteStr(v)
  268. }
  269. func (e *jsonEncDriver) EncodeSymbol(v string) {
  270. e.quoteStr(v)
  271. }
  272. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  273. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  274. if c == c_RAW && e.se.i != nil {
  275. e.EncodeExt(v, 0, &e.se, e.e)
  276. return
  277. }
  278. if c == c_RAW {
  279. slen := base64.StdEncoding.EncodedLen(len(v))
  280. if cap(e.bs) >= slen {
  281. e.bs = e.bs[:slen]
  282. } else {
  283. e.bs = make([]byte, slen)
  284. }
  285. base64.StdEncoding.Encode(e.bs, v)
  286. e.w.writen1('"')
  287. e.w.writeb(e.bs)
  288. e.w.writen1('"')
  289. } else {
  290. e.quoteStr(stringView(v))
  291. }
  292. }
  293. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  294. e.w.writeb(v)
  295. }
  296. func (e *jsonEncDriver) quoteStr(s string) {
  297. // adapted from std pkg encoding/json
  298. const hex = "0123456789abcdef"
  299. w := e.w
  300. w.writen1('"')
  301. var start int
  302. for i, slen := 0, len(s); i < slen; {
  303. // encode all bytes < 0x20 (except \r, \n).
  304. // also encode < > & to prevent security holes when served to some browsers.
  305. if b := s[i]; b < utf8.RuneSelf {
  306. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  307. if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
  308. i++
  309. continue
  310. }
  311. if start < i {
  312. w.writestr(s[start:i])
  313. }
  314. switch b {
  315. case '\\', '"':
  316. w.writen2('\\', b)
  317. case '\n':
  318. w.writen2('\\', 'n')
  319. case '\r':
  320. w.writen2('\\', 'r')
  321. case '\b':
  322. w.writen2('\\', 'b')
  323. case '\f':
  324. w.writen2('\\', 'f')
  325. case '\t':
  326. w.writen2('\\', 't')
  327. default:
  328. w.writestr(`\u00`)
  329. w.writen2(hex[b>>4], hex[b&0xF])
  330. }
  331. i++
  332. start = i
  333. continue
  334. }
  335. c, size := utf8.DecodeRuneInString(s[i:])
  336. if c == utf8.RuneError && size == 1 {
  337. if start < i {
  338. w.writestr(s[start:i])
  339. }
  340. w.writestr(`\ufffd`)
  341. i += size
  342. start = i
  343. continue
  344. }
  345. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  346. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  347. if c == '\u2028' || c == '\u2029' {
  348. if start < i {
  349. w.writestr(s[start:i])
  350. }
  351. w.writestr(`\u202`)
  352. w.writen1(hex[c&0xF])
  353. i += size
  354. start = i
  355. continue
  356. }
  357. i += size
  358. }
  359. if start < len(s) {
  360. w.writestr(s[start:])
  361. }
  362. w.writen1('"')
  363. }
  364. type jsonDecDriver struct {
  365. noBuiltInTypes
  366. d *Decoder
  367. h *JsonHandle
  368. r decReader
  369. c containerState
  370. // tok is used to store the token read right after skipWhiteSpace.
  371. tok uint8
  372. fnull bool // found null from appendStringAsBytes
  373. bstr [8]byte // scratch used for string \UXXX parsing
  374. b [64]byte // scratch, used for parsing strings or numbers
  375. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  376. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  377. se setExtWrapper
  378. // n jsonNum
  379. }
  380. func jsonIsWS(b byte) bool {
  381. // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  382. return jsonCharWhitespaceSet.isset(b)
  383. }
  384. func (d *jsonDecDriver) uncacheRead() {
  385. if d.tok != 0 {
  386. d.r.unreadn1()
  387. d.tok = 0
  388. }
  389. }
  390. func (d *jsonDecDriver) sendContainerState(c containerState) {
  391. if d.tok == 0 {
  392. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  393. }
  394. var xc uint8 // char expected
  395. switch c {
  396. case containerMapKey:
  397. if d.c != containerMapStart {
  398. xc = ','
  399. }
  400. case containerMapValue:
  401. xc = ':'
  402. case containerMapEnd:
  403. xc = '}'
  404. case containerArrayElem:
  405. if d.c != containerArrayStart {
  406. xc = ','
  407. }
  408. case containerArrayEnd:
  409. xc = ']'
  410. }
  411. if xc != 0 {
  412. if d.tok != xc {
  413. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  414. }
  415. d.tok = 0
  416. }
  417. d.c = c
  418. }
  419. func (d *jsonDecDriver) CheckBreak() bool {
  420. if d.tok == 0 {
  421. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  422. }
  423. return d.tok == '}' || d.tok == ']'
  424. }
  425. // func (d *jsonDecDriver) readLiteralIdx(fromIdx, toIdx uint8) {
  426. // bs := d.r.readx(int(toIdx - fromIdx))
  427. // d.tok = 0
  428. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  429. // d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  430. // return
  431. // }
  432. // }
  433. func (d *jsonDecDriver) readSymbol3(v1, v2, v3 uint8) {
  434. b1, b2, b3 := d.r.readn3()
  435. d.tok = 0
  436. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3) {
  437. d.d.errorf("json: expecting %c, %c, %c: got %c, %c, %c", b1, b2, b3, v1, v2, v3)
  438. return
  439. }
  440. }
  441. func (d *jsonDecDriver) readSymbol4(v1, v2, v3, v4 uint8) {
  442. b1, b2, b3, b4 := d.r.readn4()
  443. d.tok = 0
  444. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3 || b4 != v4) {
  445. d.d.errorf("json: expecting %c, %c, %c, %c: got %c, %c, %c, %c", b1, b2, b3, b4, v1, v2, v3, v4)
  446. return
  447. }
  448. }
  449. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  450. if d.tok == 0 {
  451. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  452. }
  453. if d.tok == 'n' {
  454. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  455. return true
  456. }
  457. return false
  458. }
  459. func (d *jsonDecDriver) DecodeBool() bool {
  460. if d.tok == 0 {
  461. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  462. }
  463. if d.tok == 'f' {
  464. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  465. return false
  466. }
  467. if d.tok == 't' {
  468. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  469. return true
  470. }
  471. d.d.errorf("json: decode bool: got first char %c", d.tok)
  472. return false // "unreachable"
  473. }
  474. func (d *jsonDecDriver) ReadMapStart() int {
  475. if d.tok == 0 {
  476. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  477. }
  478. if d.tok != '{' {
  479. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  480. }
  481. d.tok = 0
  482. d.c = containerMapStart
  483. return -1
  484. }
  485. func (d *jsonDecDriver) ReadArrayStart() int {
  486. if d.tok == 0 {
  487. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  488. }
  489. if d.tok != '[' {
  490. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  491. }
  492. d.tok = 0
  493. d.c = containerArrayStart
  494. return -1
  495. }
  496. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  497. // check container type by checking the first char
  498. if d.tok == 0 {
  499. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  500. }
  501. if b := d.tok; b == '{' {
  502. return valueTypeMap
  503. } else if b == '[' {
  504. return valueTypeArray
  505. } else if b == 'n' {
  506. return valueTypeNil
  507. } else if b == '"' {
  508. return valueTypeString
  509. }
  510. return valueTypeUnset
  511. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  512. // return false // "unreachable"
  513. }
  514. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  515. // stores num bytes in d.bs
  516. if d.tok == 0 {
  517. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  518. }
  519. if d.tok == '"' {
  520. bs = d.r.readUntil(d.b2[:0], '"')
  521. bs = bs[:len(bs)-1]
  522. } else {
  523. d.r.unreadn1()
  524. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  525. }
  526. d.tok = 0
  527. return bs
  528. }
  529. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  530. bs := d.decNumBytes()
  531. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  532. if err != nil {
  533. d.d.errorf("json: decode uint from %s: %v", bs, err)
  534. return
  535. }
  536. return
  537. }
  538. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  539. bs := d.decNumBytes()
  540. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  541. if err != nil {
  542. d.d.errorf("json: decode int from %s: %v", bs, err)
  543. return
  544. }
  545. return
  546. }
  547. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  548. bs := d.decNumBytes()
  549. bitsize := 64
  550. if chkOverflow32 {
  551. bitsize = 32
  552. }
  553. f, err := strconv.ParseFloat(stringView(bs), bitsize)
  554. if err != nil {
  555. d.d.errorf("json: decode float from %s: %v", bs, err)
  556. return
  557. }
  558. return
  559. }
  560. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  561. if ext == nil {
  562. re := rv.(*RawExt)
  563. re.Tag = xtag
  564. d.d.decode(&re.Value)
  565. } else {
  566. var v interface{}
  567. d.d.decode(&v)
  568. ext.UpdateExt(rv, v)
  569. }
  570. return
  571. }
  572. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  573. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  574. if d.se.i != nil {
  575. bsOut = bs
  576. d.DecodeExt(&bsOut, 0, &d.se)
  577. return
  578. }
  579. d.appendStringAsBytes()
  580. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  581. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  582. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  583. // However, it sets a fnull field to true, so we can check if a null was found.
  584. if len(d.bs) == 0 {
  585. if d.fnull {
  586. return nil
  587. }
  588. return []byte{}
  589. }
  590. bs0 := d.bs
  591. slen := base64.StdEncoding.DecodedLen(len(bs0))
  592. if slen <= cap(bs) {
  593. bsOut = bs[:slen]
  594. } else if zerocopy && slen <= cap(d.b2) {
  595. bsOut = d.b2[:slen]
  596. } else {
  597. bsOut = make([]byte, slen)
  598. }
  599. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  600. if err != nil {
  601. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  602. return nil
  603. }
  604. if slen != slen2 {
  605. bsOut = bsOut[:slen2]
  606. }
  607. return
  608. }
  609. const jsonAlwaysReturnInternString = false
  610. func (d *jsonDecDriver) DecodeString() (s string) {
  611. d.appendStringAsBytes()
  612. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  613. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  614. return d.d.string(d.bs)
  615. }
  616. return string(d.bs)
  617. }
  618. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  619. d.appendStringAsBytes()
  620. return d.bs
  621. }
  622. func (d *jsonDecDriver) appendStringAsBytes() {
  623. if d.tok == 0 {
  624. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  625. }
  626. d.fnull = false
  627. if d.tok != '"' {
  628. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  629. // handle non-string scalar: null, true, false or a number
  630. switch d.tok {
  631. case 'n':
  632. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  633. d.bs = d.bs[:0]
  634. d.fnull = true
  635. case 'f':
  636. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  637. d.bs = d.bs[:5]
  638. copy(d.bs, "false")
  639. case 't':
  640. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  641. d.bs = d.bs[:4]
  642. copy(d.bs, "true")
  643. default:
  644. // try to parse a valid number
  645. bs := d.decNumBytes()
  646. d.bs = d.bs[:len(bs)]
  647. copy(d.bs, bs)
  648. }
  649. return
  650. }
  651. d.tok = 0
  652. r := d.r
  653. var cs = r.readUntil(d.b2[:0], '"')
  654. var cslen = len(cs)
  655. var c uint8
  656. v := d.bs[:0]
  657. // append on each byte seen can be expensive, so we just
  658. // keep track of where we last read a contiguous set of
  659. // non-special bytes (using cursor variable),
  660. // and when we see a special byte
  661. // e.g. end-of-slice, " or \,
  662. // we will append the full range into the v slice before proceeding
  663. for i, cursor := 0, 0; ; {
  664. if i == cslen {
  665. v = append(v, cs[cursor:]...)
  666. cs = r.readUntil(d.b2[:0], '"')
  667. cslen = len(cs)
  668. i, cursor = 0, 0
  669. }
  670. c = cs[i]
  671. if c == '"' {
  672. v = append(v, cs[cursor:i]...)
  673. break
  674. }
  675. if c != '\\' {
  676. i++
  677. continue
  678. }
  679. v = append(v, cs[cursor:i]...)
  680. i++
  681. c = cs[i]
  682. switch c {
  683. case '"', '\\', '/', '\'':
  684. v = append(v, c)
  685. case 'b':
  686. v = append(v, '\b')
  687. case 'f':
  688. v = append(v, '\f')
  689. case 'n':
  690. v = append(v, '\n')
  691. case 'r':
  692. v = append(v, '\r')
  693. case 't':
  694. v = append(v, '\t')
  695. case 'u':
  696. var r rune
  697. var rr uint32
  698. c = cs[i+4] // may help reduce bounds-checking
  699. for j := 1; j < 5; j++ {
  700. c = jsonU4Set[cs[i+j]]
  701. if c == jsonU4SetErrVal {
  702. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  703. }
  704. rr = rr*16 + uint32(c)
  705. }
  706. r = rune(rr)
  707. i += 4
  708. if utf16.IsSurrogate(r) {
  709. if !(cs[i+2] == 'u' && cs[i+i] == '\\') {
  710. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  711. return
  712. }
  713. i += 2
  714. c = cs[i+4] // may help reduce bounds-checking
  715. var rr1 uint32
  716. for j := 1; j < 5; j++ {
  717. c = jsonU4Set[cs[i+j]]
  718. if c == jsonU4SetErrVal {
  719. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  720. }
  721. rr1 = rr1*16 + uint32(c)
  722. }
  723. r = utf16.DecodeRune(r, rune(rr1))
  724. i += 4
  725. }
  726. w2 := utf8.EncodeRune(d.bstr[:], r)
  727. v = append(v, d.bstr[:w2]...)
  728. default:
  729. d.d.errorf("json: unsupported escaped value: %c", c)
  730. }
  731. i++
  732. cursor = i
  733. }
  734. d.bs = v
  735. }
  736. // func (d *jsonDecDriver) jsonU4Arr(bs [4]byte) (r rune) {
  737. // // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  738. // var u uint32
  739. // for _, v := range bs {
  740. // if '0' <= v && v <= '9' {
  741. // v = v - '0'
  742. // } else if 'a' <= v && v <= 'f' {
  743. // v = v - 'a' + 10
  744. // } else if 'A' <= v && v <= 'f' {
  745. // v = v - 'A' + 10
  746. // } else {
  747. // // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  748. // return utf8.RuneError
  749. // }
  750. // u = u*16 + uint32(v)
  751. // }
  752. // return rune(u)
  753. // }
  754. func (d *jsonDecDriver) DecodeNaked() {
  755. z := d.d.n
  756. // var decodeFurther bool
  757. if d.tok == 0 {
  758. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  759. }
  760. switch d.tok {
  761. case 'n':
  762. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  763. z.v = valueTypeNil
  764. case 'f':
  765. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  766. z.v = valueTypeBool
  767. z.b = false
  768. case 't':
  769. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  770. z.v = valueTypeBool
  771. z.b = true
  772. case '{':
  773. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  774. case '[':
  775. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  776. case '"':
  777. z.v = valueTypeString
  778. z.s = d.DecodeString()
  779. default: // number
  780. bs := d.decNumBytes()
  781. var err error
  782. if len(bs) == 0 {
  783. d.d.errorf("json: decode number from empty string")
  784. return
  785. } else if d.h.PreferFloat || jsonIsFloatBytes(bs) { // bytes.IndexByte(bs, '.') != -1 ||...
  786. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  787. z.v = valueTypeFloat
  788. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  789. } else if d.h.SignedInteger || bs[0] == '-' {
  790. z.v = valueTypeInt
  791. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  792. } else {
  793. z.v = valueTypeUint
  794. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  795. }
  796. if err != nil {
  797. if z.v == valueTypeInt || z.v == valueTypeUint {
  798. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  799. z.v = valueTypeFloat
  800. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  801. }
  802. }
  803. if err != nil {
  804. d.d.errorf("json: decode number from %s: %v", bs, err)
  805. return
  806. }
  807. }
  808. }
  809. // if decodeFurther {
  810. // d.s.sc.retryRead()
  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. // - configurable way to encode/decode []byte .
  820. // by default, encodes and decodes []byte using base64 Std Encoding
  821. // - UTF-8 support for encoding and decoding
  822. //
  823. // It has better performance than the json library in the standard library,
  824. // by leveraging the performance improvements of the codec library and
  825. // minimizing allocations.
  826. //
  827. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  828. // reading multiple values from a stream containing json and non-json content.
  829. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  830. // all from the same stream in sequence.
  831. type JsonHandle struct {
  832. textEncodingType
  833. BasicHandle
  834. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  835. // If not configured, raw bytes are encoded to/from base64 text.
  836. RawBytesExt InterfaceExt
  837. // Indent indicates how a value is encoded.
  838. // - If positive, indent by that number of spaces.
  839. // - If negative, indent by that number of tabs.
  840. Indent int8
  841. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  842. //
  843. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  844. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  845. // This can be mitigated by configuring how to encode integers.
  846. //
  847. // IntegerAsString interpretes the following values:
  848. // - if 'L', then encode integers > 2^53 as a json string.
  849. // - if 'A', then encode all integers as a json string
  850. // containing the exact integer representation as a decimal.
  851. // - else encode all integers as a json number (default)
  852. IntegerAsString uint8
  853. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  854. //
  855. // By default, we encode them as \uXXX
  856. // to prevent security holes when served from some browsers.
  857. HTMLCharsAsIs bool
  858. // PreferFloat says that we will default to decoding a number as a float.
  859. // If not set, we will examine the characters of the number and decode as an
  860. // integer type if it doesn't have any of the characters [.eE].
  861. PreferFloat bool
  862. }
  863. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  864. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  865. }
  866. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  867. hd := jsonEncDriver{e: e, h: h}
  868. hd.bs = hd.b[:0]
  869. hd.reset()
  870. return &hd
  871. }
  872. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  873. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  874. hd := jsonDecDriver{d: d, h: h}
  875. hd.bs = hd.b[:0]
  876. hd.reset()
  877. return &hd
  878. }
  879. func (e *jsonEncDriver) reset() {
  880. e.w = e.e.w
  881. e.se.i = e.h.RawBytesExt
  882. if e.bs != nil {
  883. e.bs = e.bs[:0]
  884. }
  885. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  886. e.c = 0
  887. if e.h.Indent > 0 {
  888. e.d = true
  889. e.ds = jsonSpaces[:e.h.Indent]
  890. } else if e.h.Indent < 0 {
  891. e.d = true
  892. e.dt = true
  893. e.ds = jsonTabs[:-(e.h.Indent)]
  894. }
  895. }
  896. func (d *jsonDecDriver) reset() {
  897. d.r = d.d.r
  898. d.se.i = d.h.RawBytesExt
  899. if d.bs != nil {
  900. d.bs = d.bs[:0]
  901. }
  902. d.c, d.tok = 0, 0
  903. // d.n.reset()
  904. }
  905. func jsonIsFloatBytes(bs []byte) bool {
  906. for _, v := range bs {
  907. if v == '.' || v == 'e' || v == 'E' {
  908. return true
  909. }
  910. }
  911. return false
  912. }
  913. var jsonEncodeTerminate = []byte{' '}
  914. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  915. return jsonEncodeTerminate
  916. }
  917. var _ decDriver = (*jsonDecDriver)(nil)
  918. var _ encDriver = (*jsonEncDriver)(nil)