json.go 29 KB

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