json.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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) WriteArrayStart(length int) {
  141. if e.d {
  142. e.dl++
  143. }
  144. e.w.writen1('[')
  145. e.c = containerArrayStart
  146. }
  147. func (e *jsonEncDriver) WriteArrayElem() {
  148. if e.c != containerArrayStart {
  149. e.w.writen1(',')
  150. }
  151. if e.d {
  152. e.writeIndent()
  153. }
  154. e.c = containerArrayElem
  155. }
  156. func (e *jsonEncDriver) WriteArrayEnd() {
  157. if e.d {
  158. e.dl--
  159. if e.c != containerArrayStart {
  160. e.writeIndent()
  161. }
  162. }
  163. e.w.writen1(']')
  164. e.c = containerArrayEnd
  165. }
  166. func (e *jsonEncDriver) WriteMapStart(length int) {
  167. if e.d {
  168. e.dl++
  169. }
  170. e.w.writen1('{')
  171. e.c = containerMapStart
  172. }
  173. func (e *jsonEncDriver) WriteMapElemKey() {
  174. if e.c != containerMapStart {
  175. e.w.writen1(',')
  176. }
  177. if e.d {
  178. e.writeIndent()
  179. }
  180. e.c = containerMapKey
  181. }
  182. func (e *jsonEncDriver) WriteMapElemValue() {
  183. if e.d {
  184. e.w.writen2(':', ' ')
  185. } else {
  186. e.w.writen1(':')
  187. }
  188. e.c = containerMapValue
  189. }
  190. func (e *jsonEncDriver) WriteMapEnd() {
  191. if e.d {
  192. e.dl--
  193. if e.c != containerMapStart {
  194. e.writeIndent()
  195. }
  196. }
  197. e.w.writen1('}')
  198. e.c = containerMapEnd
  199. }
  200. // func (e *jsonEncDriver) sendContainerState(c containerState) {
  201. // // determine whether to output separators
  202. // switch c {
  203. // case containerMapKey:
  204. // if e.c != containerMapStart {
  205. // e.w.writen1(',')
  206. // }
  207. // if e.d {
  208. // e.writeIndent()
  209. // }
  210. // case containerMapValue:
  211. // if e.d {
  212. // e.w.writen2(':', ' ')
  213. // } else {
  214. // e.w.writen1(':')
  215. // }
  216. // case containerMapEnd:
  217. // if e.d {
  218. // e.dl--
  219. // if e.c != containerMapStart {
  220. // e.writeIndent()
  221. // }
  222. // }
  223. // e.w.writen1('}')
  224. // case containerArrayElem:
  225. // if e.c != containerArrayStart {
  226. // e.w.writen1(',')
  227. // }
  228. // if e.d {
  229. // e.writeIndent()
  230. // }
  231. // case containerArrayEnd:
  232. // if e.d {
  233. // e.dl--
  234. // if e.c != containerArrayStart {
  235. // e.writeIndent()
  236. // }
  237. // }
  238. // e.w.writen1(']')
  239. // }
  240. // e.c = c
  241. // }
  242. func (e *jsonEncDriver) writeIndent() {
  243. e.w.writen1('\n')
  244. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  245. if e.dt {
  246. e.w.writestr(jsonTabs[:x])
  247. } else {
  248. e.w.writestr(jsonSpaces[:x])
  249. }
  250. } else {
  251. for i := uint16(0); i < e.dl; i++ {
  252. e.w.writestr(e.ds)
  253. }
  254. }
  255. }
  256. func (e *jsonEncDriver) EncodeNil() {
  257. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null
  258. }
  259. func (e *jsonEncDriver) EncodeBool(b bool) {
  260. if b {
  261. e.w.writen4('t', 'r', 'u', 'e') // e.w.writeb(jsonLiterals[0:4]) // true
  262. } else {
  263. e.w.writen5('f', 'a', 'l', 's', 'e') // e.w.writeb(jsonLiterals[4:9]) // false
  264. }
  265. }
  266. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  267. e.encodeFloat(float64(f), 32)
  268. }
  269. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  270. e.encodeFloat(f, 64)
  271. }
  272. func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
  273. x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
  274. e.w.writeb(x)
  275. if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
  276. e.w.writen2('.', '0')
  277. }
  278. }
  279. func (e *jsonEncDriver) EncodeInt(v int64) {
  280. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  281. e.w.writen1('"')
  282. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  283. e.w.writen1('"')
  284. return
  285. }
  286. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  287. }
  288. func (e *jsonEncDriver) EncodeUint(v uint64) {
  289. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  290. e.w.writen1('"')
  291. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  292. e.w.writen1('"')
  293. return
  294. }
  295. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  296. }
  297. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  298. if v := ext.ConvertExt(rv); v == nil {
  299. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  300. } else {
  301. en.encode(v)
  302. }
  303. }
  304. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  305. // only encodes re.Value (never re.Data)
  306. if re.Value == nil {
  307. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  308. } else {
  309. en.encode(re.Value)
  310. }
  311. }
  312. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  313. e.quoteStr(v)
  314. }
  315. func (e *jsonEncDriver) EncodeSymbol(v string) {
  316. e.quoteStr(v)
  317. }
  318. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  319. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  320. if c == c_RAW && e.se.i != nil {
  321. e.EncodeExt(v, 0, &e.se, e.e)
  322. return
  323. }
  324. if c == c_RAW {
  325. slen := base64.StdEncoding.EncodedLen(len(v))
  326. if cap(e.bs) >= slen {
  327. e.bs = e.bs[:slen]
  328. } else {
  329. e.bs = make([]byte, slen)
  330. }
  331. base64.StdEncoding.Encode(e.bs, v)
  332. e.w.writen1('"')
  333. e.w.writeb(e.bs)
  334. e.w.writen1('"')
  335. } else {
  336. e.quoteStr(stringView(v))
  337. }
  338. }
  339. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  340. e.w.writeb(v)
  341. }
  342. func (e *jsonEncDriver) quoteStr(s string) {
  343. // adapted from std pkg encoding/json
  344. const hex = "0123456789abcdef"
  345. w := e.w
  346. w.writen1('"')
  347. var start int
  348. for i, slen := 0, len(s); i < slen; {
  349. // encode all bytes < 0x20 (except \r, \n).
  350. // also encode < > & to prevent security holes when served to some browsers.
  351. if b := s[i]; b < utf8.RuneSelf {
  352. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  353. if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
  354. i++
  355. continue
  356. }
  357. if start < i {
  358. w.writestr(s[start:i])
  359. }
  360. switch b {
  361. case '\\', '"':
  362. w.writen2('\\', b)
  363. case '\n':
  364. w.writen2('\\', 'n')
  365. case '\r':
  366. w.writen2('\\', 'r')
  367. case '\b':
  368. w.writen2('\\', 'b')
  369. case '\f':
  370. w.writen2('\\', 'f')
  371. case '\t':
  372. w.writen2('\\', 't')
  373. default:
  374. w.writestr(`\u00`)
  375. w.writen2(hex[b>>4], hex[b&0xF])
  376. }
  377. i++
  378. start = i
  379. continue
  380. }
  381. c, size := utf8.DecodeRuneInString(s[i:])
  382. if c == utf8.RuneError && size == 1 {
  383. if start < i {
  384. w.writestr(s[start:i])
  385. }
  386. w.writestr(`\ufffd`)
  387. i += size
  388. start = i
  389. continue
  390. }
  391. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  392. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  393. if c == '\u2028' || c == '\u2029' {
  394. if start < i {
  395. w.writestr(s[start:i])
  396. }
  397. w.writestr(`\u202`)
  398. w.writen1(hex[c&0xF])
  399. i += size
  400. start = i
  401. continue
  402. }
  403. i += size
  404. }
  405. if start < len(s) {
  406. w.writestr(s[start:])
  407. }
  408. w.writen1('"')
  409. }
  410. type jsonDecDriver struct {
  411. noBuiltInTypes
  412. d *Decoder
  413. h *JsonHandle
  414. r decReader
  415. c containerState
  416. // tok is used to store the token read right after skipWhiteSpace.
  417. tok uint8
  418. fnull bool // found null from appendStringAsBytes
  419. bstr [8]byte // scratch used for string \UXXX parsing
  420. b [64]byte // scratch, used for parsing strings or numbers
  421. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  422. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  423. se setExtWrapper
  424. // n jsonNum
  425. }
  426. func jsonIsWS(b byte) bool {
  427. // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  428. return jsonCharWhitespaceSet.isset(b)
  429. }
  430. func (d *jsonDecDriver) uncacheRead() {
  431. if d.tok != 0 {
  432. d.r.unreadn1()
  433. d.tok = 0
  434. }
  435. }
  436. func (d *jsonDecDriver) ReadMapStart() int {
  437. if d.tok == 0 {
  438. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  439. }
  440. if d.tok != '{' {
  441. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  442. }
  443. d.tok = 0
  444. d.c = containerMapStart
  445. return -1
  446. }
  447. func (d *jsonDecDriver) ReadArrayStart() int {
  448. if d.tok == 0 {
  449. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  450. }
  451. if d.tok != '[' {
  452. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  453. }
  454. d.tok = 0
  455. d.c = containerArrayStart
  456. return -1
  457. }
  458. func (d *jsonDecDriver) CheckBreak() bool {
  459. if d.tok == 0 {
  460. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  461. }
  462. return d.tok == '}' || d.tok == ']'
  463. }
  464. func (d *jsonDecDriver) ReadArrayElem() {
  465. if d.tok == 0 {
  466. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  467. }
  468. if d.c != containerArrayStart {
  469. const xc uint8 = ','
  470. if d.tok != xc {
  471. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  472. }
  473. d.tok = 0
  474. }
  475. d.c = containerArrayElem
  476. }
  477. func (d *jsonDecDriver) ReadArrayEnd() {
  478. if d.tok == 0 {
  479. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  480. }
  481. const xc uint8 = ']'
  482. if d.tok != xc {
  483. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  484. }
  485. d.tok = 0
  486. d.c = containerArrayEnd
  487. }
  488. func (d *jsonDecDriver) ReadMapElemKey() {
  489. if d.tok == 0 {
  490. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  491. }
  492. if d.c != containerMapStart {
  493. const xc uint8 = ','
  494. if d.tok != xc {
  495. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  496. }
  497. d.tok = 0
  498. }
  499. d.c = containerMapKey
  500. }
  501. func (d *jsonDecDriver) ReadMapElemValue() {
  502. if d.tok == 0 {
  503. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  504. }
  505. const xc uint8 = ':'
  506. if d.tok != xc {
  507. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  508. }
  509. d.tok = 0
  510. d.c = containerMapValue
  511. }
  512. func (d *jsonDecDriver) ReadMapEnd() {
  513. if d.tok == 0 {
  514. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  515. }
  516. const xc uint8 = '}'
  517. if d.tok != xc {
  518. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  519. }
  520. d.tok = 0
  521. d.c = containerMapEnd
  522. }
  523. // func (d *jsonDecDriver) readContainerState(c containerState, xc uint8, check bool) {
  524. // if d.tok == 0 {
  525. // d.tok = d.r.skip(&jsonCharWhitespaceSet)
  526. // }
  527. // if check {
  528. // if d.tok != xc {
  529. // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  530. // }
  531. // d.tok = 0
  532. // }
  533. // d.c = c
  534. // }
  535. // func (d *jsonDecDriver) sendContainerState(c containerState) {
  536. // if d.tok == 0 {
  537. // d.tok = d.r.skip(&jsonCharWhitespaceSet)
  538. // }
  539. // var xc uint8 // char expected
  540. // switch c {
  541. // case containerMapKey:
  542. // if d.c != containerMapStart {
  543. // xc = ','
  544. // }
  545. // case containerMapValue:
  546. // xc = ':'
  547. // case containerMapEnd:
  548. // xc = '}'
  549. // case containerArrayElem:
  550. // if d.c != containerArrayStart {
  551. // xc = ','
  552. // }
  553. // case containerArrayEnd:
  554. // xc = ']'
  555. // }
  556. // if xc != 0 {
  557. // if d.tok != xc {
  558. // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  559. // }
  560. // d.tok = 0
  561. // }
  562. // d.c = c
  563. // }
  564. // func (d *jsonDecDriver) readLiteralIdx(fromIdx, toIdx uint8) {
  565. // bs := d.r.readx(int(toIdx - fromIdx))
  566. // d.tok = 0
  567. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  568. // d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  569. // return
  570. // }
  571. // }
  572. func (d *jsonDecDriver) readSymbol3(v1, v2, v3 uint8) {
  573. b1, b2, b3 := d.r.readn3()
  574. d.tok = 0
  575. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3) {
  576. d.d.errorf("json: expecting %c, %c, %c: got %c, %c, %c", b1, b2, b3, v1, v2, v3)
  577. return
  578. }
  579. }
  580. func (d *jsonDecDriver) readSymbol4(v1, v2, v3, v4 uint8) {
  581. b1, b2, b3, b4 := d.r.readn4()
  582. d.tok = 0
  583. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3 || b4 != v4) {
  584. d.d.errorf("json: expecting %c, %c, %c, %c: got %c, %c, %c, %c", b1, b2, b3, b4, v1, v2, v3, v4)
  585. return
  586. }
  587. }
  588. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  589. if d.tok == 0 {
  590. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  591. }
  592. if d.tok == 'n' {
  593. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  594. return true
  595. }
  596. return false
  597. }
  598. func (d *jsonDecDriver) DecodeBool() bool {
  599. if d.tok == 0 {
  600. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  601. }
  602. if d.tok == 'f' {
  603. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  604. return false
  605. }
  606. if d.tok == 't' {
  607. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  608. return true
  609. }
  610. d.d.errorf("json: decode bool: got first char %c", d.tok)
  611. return false // "unreachable"
  612. }
  613. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  614. // check container type by checking the first char
  615. if d.tok == 0 {
  616. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  617. }
  618. if b := d.tok; b == '{' {
  619. return valueTypeMap
  620. } else if b == '[' {
  621. return valueTypeArray
  622. } else if b == 'n' {
  623. return valueTypeNil
  624. } else if b == '"' {
  625. return valueTypeString
  626. }
  627. return valueTypeUnset
  628. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  629. // return false // "unreachable"
  630. }
  631. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  632. // stores num bytes in d.bs
  633. if d.tok == 0 {
  634. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  635. }
  636. if d.tok == '"' {
  637. bs = d.r.readUntil(d.b2[:0], '"')
  638. bs = bs[:len(bs)-1]
  639. } else {
  640. d.r.unreadn1()
  641. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  642. }
  643. d.tok = 0
  644. return bs
  645. }
  646. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  647. bs := d.decNumBytes()
  648. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  649. if err != nil {
  650. d.d.errorf("json: decode uint from %s: %v", bs, err)
  651. return
  652. }
  653. return
  654. }
  655. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  656. bs := d.decNumBytes()
  657. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  658. if err != nil {
  659. d.d.errorf("json: decode int from %s: %v", bs, err)
  660. return
  661. }
  662. return
  663. }
  664. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  665. bs := d.decNumBytes()
  666. bitsize := 64
  667. if chkOverflow32 {
  668. bitsize = 32
  669. }
  670. f, err := strconv.ParseFloat(stringView(bs), bitsize)
  671. if err != nil {
  672. d.d.errorf("json: decode float from %s: %v", bs, err)
  673. return
  674. }
  675. return
  676. }
  677. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  678. if ext == nil {
  679. re := rv.(*RawExt)
  680. re.Tag = xtag
  681. d.d.decode(&re.Value)
  682. } else {
  683. var v interface{}
  684. d.d.decode(&v)
  685. ext.UpdateExt(rv, v)
  686. }
  687. return
  688. }
  689. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  690. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  691. if d.se.i != nil {
  692. bsOut = bs
  693. d.DecodeExt(&bsOut, 0, &d.se)
  694. return
  695. }
  696. d.appendStringAsBytes()
  697. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  698. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  699. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  700. // However, it sets a fnull field to true, so we can check if a null was found.
  701. if len(d.bs) == 0 {
  702. if d.fnull {
  703. return nil
  704. }
  705. return []byte{}
  706. }
  707. bs0 := d.bs
  708. slen := base64.StdEncoding.DecodedLen(len(bs0))
  709. if slen <= cap(bs) {
  710. bsOut = bs[:slen]
  711. } else if zerocopy && slen <= cap(d.b2) {
  712. bsOut = d.b2[:slen]
  713. } else {
  714. bsOut = make([]byte, slen)
  715. }
  716. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  717. if err != nil {
  718. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  719. return nil
  720. }
  721. if slen != slen2 {
  722. bsOut = bsOut[:slen2]
  723. }
  724. return
  725. }
  726. const jsonAlwaysReturnInternString = false
  727. func (d *jsonDecDriver) DecodeString() (s string) {
  728. d.appendStringAsBytes()
  729. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  730. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  731. return d.d.string(d.bs)
  732. }
  733. return string(d.bs)
  734. }
  735. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  736. d.appendStringAsBytes()
  737. return d.bs
  738. }
  739. func (d *jsonDecDriver) appendStringAsBytes() {
  740. if d.tok == 0 {
  741. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  742. }
  743. d.fnull = false
  744. if d.tok != '"' {
  745. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  746. // handle non-string scalar: null, true, false or a number
  747. switch d.tok {
  748. case 'n':
  749. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  750. d.bs = d.bs[:0]
  751. d.fnull = true
  752. case 'f':
  753. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  754. d.bs = d.bs[:5]
  755. copy(d.bs, "false")
  756. case 't':
  757. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  758. d.bs = d.bs[:4]
  759. copy(d.bs, "true")
  760. default:
  761. // try to parse a valid number
  762. bs := d.decNumBytes()
  763. d.bs = d.bs[:len(bs)]
  764. copy(d.bs, bs)
  765. }
  766. return
  767. }
  768. d.tok = 0
  769. r := d.r
  770. var cs = r.readUntil(d.b2[:0], '"')
  771. var cslen = len(cs)
  772. var c uint8
  773. v := d.bs[:0]
  774. // append on each byte seen can be expensive, so we just
  775. // keep track of where we last read a contiguous set of
  776. // non-special bytes (using cursor variable),
  777. // and when we see a special byte
  778. // e.g. end-of-slice, " or \,
  779. // we will append the full range into the v slice before proceeding
  780. for i, cursor := 0, 0; ; {
  781. if i == cslen {
  782. v = append(v, cs[cursor:]...)
  783. cs = r.readUntil(d.b2[:0], '"')
  784. cslen = len(cs)
  785. i, cursor = 0, 0
  786. }
  787. c = cs[i]
  788. if c == '"' {
  789. v = append(v, cs[cursor:i]...)
  790. break
  791. }
  792. if c != '\\' {
  793. i++
  794. continue
  795. }
  796. v = append(v, cs[cursor:i]...)
  797. i++
  798. c = cs[i]
  799. switch c {
  800. case '"', '\\', '/', '\'':
  801. v = append(v, c)
  802. case 'b':
  803. v = append(v, '\b')
  804. case 'f':
  805. v = append(v, '\f')
  806. case 'n':
  807. v = append(v, '\n')
  808. case 'r':
  809. v = append(v, '\r')
  810. case 't':
  811. v = append(v, '\t')
  812. case 'u':
  813. var r rune
  814. var rr uint32
  815. c = cs[i+4] // may help reduce bounds-checking
  816. for j := 1; j < 5; j++ {
  817. c = jsonU4Set[cs[i+j]]
  818. if c == jsonU4SetErrVal {
  819. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  820. }
  821. rr = rr*16 + uint32(c)
  822. }
  823. r = rune(rr)
  824. i += 4
  825. if utf16.IsSurrogate(r) {
  826. if !(cs[i+2] == 'u' && cs[i+i] == '\\') {
  827. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  828. return
  829. }
  830. i += 2
  831. c = cs[i+4] // may help reduce bounds-checking
  832. var rr1 uint32
  833. for j := 1; j < 5; j++ {
  834. c = jsonU4Set[cs[i+j]]
  835. if c == jsonU4SetErrVal {
  836. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  837. }
  838. rr1 = rr1*16 + uint32(c)
  839. }
  840. r = utf16.DecodeRune(r, rune(rr1))
  841. i += 4
  842. }
  843. w2 := utf8.EncodeRune(d.bstr[:], r)
  844. v = append(v, d.bstr[:w2]...)
  845. default:
  846. d.d.errorf("json: unsupported escaped value: %c", c)
  847. }
  848. i++
  849. cursor = i
  850. }
  851. d.bs = v
  852. }
  853. // func (d *jsonDecDriver) jsonU4Arr(bs [4]byte) (r rune) {
  854. // // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  855. // var u uint32
  856. // for _, v := range bs {
  857. // if '0' <= v && v <= '9' {
  858. // v = v - '0'
  859. // } else if 'a' <= v && v <= 'f' {
  860. // v = v - 'a' + 10
  861. // } else if 'A' <= v && v <= 'f' {
  862. // v = v - 'A' + 10
  863. // } else {
  864. // // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  865. // return utf8.RuneError
  866. // }
  867. // u = u*16 + uint32(v)
  868. // }
  869. // return rune(u)
  870. // }
  871. func (d *jsonDecDriver) DecodeNaked() {
  872. z := d.d.n
  873. // var decodeFurther bool
  874. if d.tok == 0 {
  875. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  876. }
  877. switch d.tok {
  878. case 'n':
  879. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  880. z.v = valueTypeNil
  881. case 'f':
  882. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  883. z.v = valueTypeBool
  884. z.b = false
  885. case 't':
  886. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  887. z.v = valueTypeBool
  888. z.b = true
  889. case '{':
  890. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  891. case '[':
  892. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  893. case '"':
  894. z.v = valueTypeString
  895. z.s = d.DecodeString()
  896. default: // number
  897. bs := d.decNumBytes()
  898. var err error
  899. if len(bs) == 0 {
  900. d.d.errorf("json: decode number from empty string")
  901. return
  902. } else if d.h.PreferFloat || jsonIsFloatBytes(bs) { // bytes.IndexByte(bs, '.') != -1 ||...
  903. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  904. z.v = valueTypeFloat
  905. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  906. } else if d.h.SignedInteger || bs[0] == '-' {
  907. z.v = valueTypeInt
  908. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  909. } else {
  910. z.v = valueTypeUint
  911. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  912. }
  913. if err != nil {
  914. if z.v == valueTypeInt || z.v == valueTypeUint {
  915. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  916. z.v = valueTypeFloat
  917. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  918. }
  919. }
  920. if err != nil {
  921. d.d.errorf("json: decode number from %s: %v", bs, err)
  922. return
  923. }
  924. }
  925. }
  926. // if decodeFurther {
  927. // d.s.sc.retryRead()
  928. // }
  929. return
  930. }
  931. //----------------------
  932. // JsonHandle is a handle for JSON encoding format.
  933. //
  934. // Json is comprehensively supported:
  935. // - decodes numbers into interface{} as int, uint or float64
  936. // - configurable way to encode/decode []byte .
  937. // by default, encodes and decodes []byte using base64 Std Encoding
  938. // - UTF-8 support for encoding and decoding
  939. //
  940. // It has better performance than the json library in the standard library,
  941. // by leveraging the performance improvements of the codec library and
  942. // minimizing allocations.
  943. //
  944. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  945. // reading multiple values from a stream containing json and non-json content.
  946. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  947. // all from the same stream in sequence.
  948. type JsonHandle struct {
  949. textEncodingType
  950. BasicHandle
  951. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  952. // If not configured, raw bytes are encoded to/from base64 text.
  953. RawBytesExt InterfaceExt
  954. // Indent indicates how a value is encoded.
  955. // - If positive, indent by that number of spaces.
  956. // - If negative, indent by that number of tabs.
  957. Indent int8
  958. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  959. //
  960. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  961. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  962. // This can be mitigated by configuring how to encode integers.
  963. //
  964. // IntegerAsString interpretes the following values:
  965. // - if 'L', then encode integers > 2^53 as a json string.
  966. // - if 'A', then encode all integers as a json string
  967. // containing the exact integer representation as a decimal.
  968. // - else encode all integers as a json number (default)
  969. IntegerAsString uint8
  970. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  971. //
  972. // By default, we encode them as \uXXX
  973. // to prevent security holes when served from some browsers.
  974. HTMLCharsAsIs bool
  975. // PreferFloat says that we will default to decoding a number as a float.
  976. // If not set, we will examine the characters of the number and decode as an
  977. // integer type if it doesn't have any of the characters [.eE].
  978. PreferFloat bool
  979. }
  980. func (h *JsonHandle) hasElemSeparators() bool { return true }
  981. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  982. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  983. }
  984. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  985. hd := jsonEncDriver{e: e, h: h}
  986. hd.bs = hd.b[:0]
  987. hd.reset()
  988. return &hd
  989. }
  990. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  991. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  992. hd := jsonDecDriver{d: d, h: h}
  993. hd.bs = hd.b[:0]
  994. hd.reset()
  995. return &hd
  996. }
  997. func (e *jsonEncDriver) reset() {
  998. e.w = e.e.w
  999. e.se.i = e.h.RawBytesExt
  1000. if e.bs != nil {
  1001. e.bs = e.bs[:0]
  1002. }
  1003. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1004. e.c = 0
  1005. if e.h.Indent > 0 {
  1006. e.d = true
  1007. e.ds = jsonSpaces[:e.h.Indent]
  1008. } else if e.h.Indent < 0 {
  1009. e.d = true
  1010. e.dt = true
  1011. e.ds = jsonTabs[:-(e.h.Indent)]
  1012. }
  1013. }
  1014. func (d *jsonDecDriver) reset() {
  1015. d.r = d.d.r
  1016. d.se.i = d.h.RawBytesExt
  1017. if d.bs != nil {
  1018. d.bs = d.bs[:0]
  1019. }
  1020. d.c, d.tok = 0, 0
  1021. // d.n.reset()
  1022. }
  1023. func jsonIsFloatBytes(bs []byte) bool {
  1024. for _, v := range bs {
  1025. if v == '.' || v == 'e' || v == 'E' {
  1026. return true
  1027. }
  1028. }
  1029. return false
  1030. }
  1031. var jsonEncodeTerminate = []byte{' '}
  1032. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1033. return jsonEncodeTerminate
  1034. }
  1035. var _ decDriver = (*jsonDecDriver)(nil)
  1036. var _ encDriver = (*jsonEncDriver)(nil)