json.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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 c == cRAW {
  348. if e.se.i != nil {
  349. e.EncodeExt(v, 0, &e.se, e.e)
  350. return
  351. }
  352. slen := base64.StdEncoding.EncodedLen(len(v))
  353. if cap(e.bs) >= slen {
  354. e.bs = e.bs[:slen]
  355. } else {
  356. e.bs = make([]byte, slen)
  357. }
  358. base64.StdEncoding.Encode(e.bs, v)
  359. e.w.writen1('"')
  360. e.w.writeb(e.bs)
  361. e.w.writen1('"')
  362. } else {
  363. e.quoteStr(stringView(v))
  364. }
  365. }
  366. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  367. e.w.writeb(v)
  368. }
  369. func (e *jsonEncDriver) quoteStr(s string) {
  370. // adapted from std pkg encoding/json
  371. const hex = "0123456789abcdef"
  372. w := e.w
  373. w.writen1('"')
  374. var start int
  375. for i, slen := 0, len(s); i < slen; {
  376. // encode all bytes < 0x20 (except \r, \n).
  377. // also encode < > & to prevent security holes when served to some browsers.
  378. if b := s[i]; b < utf8.RuneSelf {
  379. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  380. if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
  381. i++
  382. continue
  383. }
  384. if start < i {
  385. w.writestr(s[start:i])
  386. }
  387. switch b {
  388. case '\\', '"':
  389. w.writen2('\\', b)
  390. case '\n':
  391. w.writen2('\\', 'n')
  392. case '\r':
  393. w.writen2('\\', 'r')
  394. case '\b':
  395. w.writen2('\\', 'b')
  396. case '\f':
  397. w.writen2('\\', 'f')
  398. case '\t':
  399. w.writen2('\\', 't')
  400. default:
  401. w.writestr(`\u00`)
  402. w.writen2(hex[b>>4], hex[b&0xF])
  403. }
  404. i++
  405. start = i
  406. continue
  407. }
  408. c, size := utf8.DecodeRuneInString(s[i:])
  409. if c == utf8.RuneError && size == 1 {
  410. if start < i {
  411. w.writestr(s[start:i])
  412. }
  413. w.writestr(`\ufffd`)
  414. i += size
  415. start = i
  416. continue
  417. }
  418. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  419. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  420. if c == '\u2028' || c == '\u2029' {
  421. if start < i {
  422. w.writestr(s[start:i])
  423. }
  424. w.writestr(`\u202`)
  425. w.writen1(hex[c&0xF])
  426. i += size
  427. start = i
  428. continue
  429. }
  430. i += size
  431. }
  432. if start < len(s) {
  433. w.writestr(s[start:])
  434. }
  435. w.writen1('"')
  436. }
  437. func (e *jsonEncDriver) atEndOfEncode() {
  438. if e.h.TermWhitespace {
  439. if e.d {
  440. e.w.writen1('\n')
  441. } else {
  442. e.w.writen1(' ')
  443. }
  444. }
  445. }
  446. type jsonDecDriver struct {
  447. noBuiltInTypes
  448. d *Decoder
  449. h *JsonHandle
  450. r decReader
  451. c containerState
  452. // tok is used to store the token read right after skipWhiteSpace.
  453. tok uint8
  454. fnull bool // found null from appendStringAsBytes
  455. bstr [8]byte // scratch used for string \UXXX parsing
  456. b [64]byte // scratch, used for parsing strings or numbers or time.Time
  457. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  458. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  459. se setExtWrapper
  460. // n jsonNum
  461. }
  462. func jsonIsWS(b byte) bool {
  463. // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  464. return jsonCharWhitespaceSet.isset(b)
  465. }
  466. func (d *jsonDecDriver) uncacheRead() {
  467. if d.tok != 0 {
  468. d.r.unreadn1()
  469. d.tok = 0
  470. }
  471. }
  472. func (d *jsonDecDriver) ReadMapStart() int {
  473. if d.tok == 0 {
  474. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  475. }
  476. if d.tok != '{' {
  477. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  478. }
  479. d.tok = 0
  480. d.c = containerMapStart
  481. return -1
  482. }
  483. func (d *jsonDecDriver) ReadArrayStart() int {
  484. if d.tok == 0 {
  485. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  486. }
  487. if d.tok != '[' {
  488. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  489. }
  490. d.tok = 0
  491. d.c = containerArrayStart
  492. return -1
  493. }
  494. func (d *jsonDecDriver) CheckBreak() bool {
  495. if d.tok == 0 {
  496. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  497. }
  498. return d.tok == '}' || d.tok == ']'
  499. }
  500. func (d *jsonDecDriver) ReadArrayElem() {
  501. if d.tok == 0 {
  502. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  503. }
  504. if d.c != containerArrayStart {
  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. }
  511. d.c = containerArrayElem
  512. }
  513. func (d *jsonDecDriver) ReadArrayEnd() {
  514. if d.tok == 0 {
  515. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  516. }
  517. const xc uint8 = ']'
  518. if d.tok != xc {
  519. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  520. }
  521. d.tok = 0
  522. d.c = containerArrayEnd
  523. }
  524. func (d *jsonDecDriver) ReadMapElemKey() {
  525. if d.tok == 0 {
  526. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  527. }
  528. if d.c != containerMapStart {
  529. const xc uint8 = ','
  530. if d.tok != xc {
  531. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  532. }
  533. d.tok = 0
  534. }
  535. d.c = containerMapKey
  536. }
  537. func (d *jsonDecDriver) ReadMapElemValue() {
  538. if d.tok == 0 {
  539. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  540. }
  541. const xc uint8 = ':'
  542. if d.tok != xc {
  543. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  544. }
  545. d.tok = 0
  546. d.c = containerMapValue
  547. }
  548. func (d *jsonDecDriver) ReadMapEnd() {
  549. if d.tok == 0 {
  550. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  551. }
  552. const xc uint8 = '}'
  553. if d.tok != xc {
  554. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  555. }
  556. d.tok = 0
  557. d.c = containerMapEnd
  558. }
  559. // func (d *jsonDecDriver) readContainerState(c containerState, xc uint8, check bool) {
  560. // if d.tok == 0 {
  561. // d.tok = d.r.skip(&jsonCharWhitespaceSet)
  562. // }
  563. // if check {
  564. // if d.tok != xc {
  565. // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  566. // }
  567. // d.tok = 0
  568. // }
  569. // d.c = c
  570. // }
  571. func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
  572. bs := d.r.readx(int(length))
  573. d.tok = 0
  574. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  575. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  576. return
  577. }
  578. }
  579. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  580. if d.tok == 0 {
  581. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  582. }
  583. // TODO: we shouldn't try to see if "null" was here, right?
  584. // only "null" denotes a nil
  585. if d.tok == 'n' {
  586. d.readLit(3, jsonLitNull+1) // (n)ull
  587. return true
  588. }
  589. return false
  590. }
  591. func (d *jsonDecDriver) DecodeBool() (v bool) {
  592. if d.tok == 0 {
  593. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  594. }
  595. fquot := d.c == containerMapKey && d.tok == '"'
  596. if fquot {
  597. d.tok = d.r.readn1()
  598. }
  599. switch d.tok {
  600. case 'f':
  601. d.readLit(4, jsonLitFalse+1) // (f)alse
  602. // v = false
  603. case 't':
  604. d.readLit(3, jsonLitTrue+1) // (t)rue
  605. v = true
  606. default:
  607. d.d.errorf("json: decode bool: got first char %c", d.tok)
  608. // v = false // "unreachable"
  609. }
  610. if fquot {
  611. d.r.readn1()
  612. }
  613. return
  614. }
  615. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  616. // read string, and pass the string into json.unmarshal
  617. d.appendStringAsBytes()
  618. t, err := time.Parse(time.RFC3339, stringView(d.bs))
  619. if err != nil {
  620. d.d.error(err)
  621. }
  622. return
  623. }
  624. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  625. // check container type by checking the first char
  626. if d.tok == 0 {
  627. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  628. }
  629. if b := d.tok; b == '{' {
  630. return valueTypeMap
  631. } else if b == '[' {
  632. return valueTypeArray
  633. } else if b == 'n' {
  634. return valueTypeNil
  635. } else if b == '"' {
  636. return valueTypeString
  637. }
  638. return valueTypeUnset
  639. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  640. // return false // "unreachable"
  641. }
  642. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  643. // stores num bytes in d.bs
  644. if d.tok == 0 {
  645. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  646. }
  647. if d.tok == '"' {
  648. bs = d.r.readUntil(d.b2[:0], '"')
  649. bs = bs[:len(bs)-1]
  650. } else {
  651. d.r.unreadn1()
  652. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  653. }
  654. d.tok = 0
  655. return bs
  656. }
  657. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  658. bs := d.decNumBytes()
  659. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  660. if err != nil {
  661. d.d.errorf("json: decode uint from %s: %v", bs, err)
  662. return
  663. }
  664. return
  665. }
  666. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  667. bs := d.decNumBytes()
  668. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  669. if err != nil {
  670. d.d.errorf("json: decode int from %s: %v", bs, err)
  671. return
  672. }
  673. return
  674. }
  675. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  676. bs := d.decNumBytes()
  677. bitsize := 64
  678. if chkOverflow32 {
  679. bitsize = 32
  680. }
  681. f, err := strconv.ParseFloat(stringView(bs), bitsize)
  682. if err != nil {
  683. d.d.errorf("json: decode float from %s: %v", bs, err)
  684. return
  685. }
  686. return
  687. }
  688. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  689. if ext == nil {
  690. re := rv.(*RawExt)
  691. re.Tag = xtag
  692. d.d.decode(&re.Value)
  693. } else {
  694. var v interface{}
  695. d.d.decode(&v)
  696. ext.UpdateExt(rv, v)
  697. }
  698. return
  699. }
  700. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  701. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  702. if d.se.i != nil {
  703. bsOut = bs
  704. d.DecodeExt(&bsOut, 0, &d.se)
  705. return
  706. }
  707. d.appendStringAsBytes()
  708. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  709. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  710. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  711. // However, it sets a fnull field to true, so we can check if a null was found.
  712. if len(d.bs) == 0 {
  713. if d.fnull {
  714. return nil
  715. }
  716. return []byte{}
  717. }
  718. bs0 := d.bs
  719. slen := base64.StdEncoding.DecodedLen(len(bs0))
  720. if slen <= cap(bs) {
  721. bsOut = bs[:slen]
  722. } else if zerocopy && slen <= cap(d.b2) {
  723. bsOut = d.b2[:slen]
  724. } else {
  725. bsOut = make([]byte, slen)
  726. }
  727. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  728. if err != nil {
  729. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  730. return nil
  731. }
  732. if slen != slen2 {
  733. bsOut = bsOut[:slen2]
  734. }
  735. return
  736. }
  737. func (d *jsonDecDriver) DecodeString() (s string) {
  738. d.appendStringAsBytes()
  739. return d.bsToString()
  740. }
  741. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  742. d.appendStringAsBytes()
  743. return d.bs
  744. }
  745. func (d *jsonDecDriver) appendStringAsBytes() {
  746. if d.tok == 0 {
  747. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  748. }
  749. d.fnull = false
  750. if d.tok != '"' {
  751. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  752. // handle non-string scalar: null, true, false or a number
  753. switch d.tok {
  754. case 'n':
  755. d.readLit(3, jsonLitNull+1) // (n)ull
  756. d.bs = d.bs[:0]
  757. d.fnull = true
  758. case 'f':
  759. d.readLit(4, jsonLitFalse+1) // (f)alse
  760. d.bs = d.bs[:5]
  761. copy(d.bs, "false")
  762. case 't':
  763. d.readLit(3, jsonLitTrue+1) // (t)rue
  764. d.bs = d.bs[:4]
  765. copy(d.bs, "true")
  766. default:
  767. // try to parse a valid number
  768. bs := d.decNumBytes()
  769. d.bs = d.bs[:len(bs)]
  770. copy(d.bs, bs)
  771. }
  772. return
  773. }
  774. d.tok = 0
  775. r := d.r
  776. var cs = r.readUntil(d.b2[:0], '"')
  777. var cslen = len(cs)
  778. var c uint8
  779. v := d.bs[:0]
  780. // append on each byte seen can be expensive, so we just
  781. // keep track of where we last read a contiguous set of
  782. // non-special bytes (using cursor variable),
  783. // and when we see a special byte
  784. // e.g. end-of-slice, " or \,
  785. // we will append the full range into the v slice before proceeding
  786. for i, cursor := 0, 0; ; {
  787. if i == cslen {
  788. v = append(v, cs[cursor:]...)
  789. cs = r.readUntil(d.b2[:0], '"')
  790. cslen = len(cs)
  791. i, cursor = 0, 0
  792. }
  793. c = cs[i]
  794. if c == '"' {
  795. v = append(v, cs[cursor:i]...)
  796. break
  797. }
  798. if c != '\\' {
  799. i++
  800. continue
  801. }
  802. v = append(v, cs[cursor:i]...)
  803. i++
  804. c = cs[i]
  805. switch c {
  806. case '"', '\\', '/', '\'':
  807. v = append(v, c)
  808. case 'b':
  809. v = append(v, '\b')
  810. case 'f':
  811. v = append(v, '\f')
  812. case 'n':
  813. v = append(v, '\n')
  814. case 'r':
  815. v = append(v, '\r')
  816. case 't':
  817. v = append(v, '\t')
  818. case 'u':
  819. var r rune
  820. var rr uint32
  821. if len(cs) < i+4 { // may help reduce bounds-checking
  822. d.d.errorf(`json: need at least 4 more bytes for unicode sequence`)
  823. }
  824. // c = cs[i+4] // may help reduce bounds-checking
  825. for j := 1; j < 5; j++ {
  826. c = jsonU4Set[cs[i+j]]
  827. if c == jsonU4SetErrVal {
  828. // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  829. r = unicode.ReplacementChar
  830. i += 4
  831. goto encode_rune
  832. }
  833. rr = rr*16 + uint32(c)
  834. }
  835. r = rune(rr)
  836. i += 4
  837. if utf16.IsSurrogate(r) {
  838. if len(cs) >= i+6 && cs[i+2] == 'u' && cs[i+1] == '\\' {
  839. i += 2
  840. // c = cs[i+4] // may help reduce bounds-checking
  841. var rr1 uint32
  842. for j := 1; j < 5; j++ {
  843. c = jsonU4Set[cs[i+j]]
  844. if c == jsonU4SetErrVal {
  845. // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  846. r = unicode.ReplacementChar
  847. i += 4
  848. goto encode_rune
  849. }
  850. rr1 = rr1*16 + uint32(c)
  851. }
  852. r = utf16.DecodeRune(r, rune(rr1))
  853. i += 4
  854. } else {
  855. r = unicode.ReplacementChar
  856. goto encode_rune
  857. }
  858. }
  859. encode_rune:
  860. w2 := utf8.EncodeRune(d.bstr[:], r)
  861. v = append(v, d.bstr[:w2]...)
  862. default:
  863. d.d.errorf("json: unsupported escaped value: %c", c)
  864. }
  865. i++
  866. cursor = i
  867. }
  868. d.bs = v
  869. }
  870. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  871. if d.h.PreferFloat || jsonIsFloatBytesB3(bs) { // bytes.IndexByte(bs, '.') != -1 ||...
  872. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  873. z.v = valueTypeFloat
  874. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  875. } else if d.h.SignedInteger || bs[0] == '-' {
  876. z.v = valueTypeInt
  877. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  878. } else {
  879. z.v = valueTypeUint
  880. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  881. }
  882. if err != nil && z.v != valueTypeFloat {
  883. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  884. z.v = valueTypeFloat
  885. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  886. }
  887. }
  888. return
  889. }
  890. func (d *jsonDecDriver) bsToString() string {
  891. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  892. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  893. return d.d.string(d.bs)
  894. }
  895. return string(d.bs)
  896. }
  897. func (d *jsonDecDriver) DecodeNaked() {
  898. z := d.d.n
  899. // var decodeFurther bool
  900. if d.tok == 0 {
  901. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  902. }
  903. switch d.tok {
  904. case 'n':
  905. d.readLit(3, jsonLitNull+1) // (n)ull
  906. z.v = valueTypeNil
  907. case 'f':
  908. d.readLit(4, jsonLitFalse+1) // (f)alse
  909. z.v = valueTypeBool
  910. z.b = false
  911. case 't':
  912. d.readLit(3, jsonLitTrue+1) // (t)rue
  913. z.v = valueTypeBool
  914. z.b = true
  915. case '{':
  916. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  917. case '[':
  918. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  919. case '"':
  920. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  921. d.appendStringAsBytes()
  922. if len(d.bs) > 0 && d.c == containerMapKey && d.h.MapKeyAsString {
  923. switch stringView(d.bs) {
  924. case "null":
  925. z.v = valueTypeNil
  926. case "true":
  927. z.v = valueTypeBool
  928. z.b = true
  929. case "false":
  930. z.v = valueTypeBool
  931. z.b = false
  932. default:
  933. // check if a number: float, int or uint
  934. if err := d.nakedNum(z, d.bs); err != nil {
  935. z.v = valueTypeString
  936. z.s = d.bsToString()
  937. }
  938. }
  939. } else {
  940. z.v = valueTypeString
  941. z.s = d.bsToString()
  942. }
  943. default: // number
  944. bs := d.decNumBytes()
  945. if len(bs) == 0 {
  946. d.d.errorf("json: decode number from empty string")
  947. return
  948. }
  949. if err := d.nakedNum(z, bs); err != nil {
  950. d.d.errorf("json: decode number from %s: %v", bs, err)
  951. return
  952. }
  953. }
  954. // if decodeFurther {
  955. // d.s.sc.retryRead()
  956. // }
  957. return
  958. }
  959. //----------------------
  960. // JsonHandle is a handle for JSON encoding format.
  961. //
  962. // Json is comprehensively supported:
  963. // - decodes numbers into interface{} as int, uint or float64
  964. // - configurable way to encode/decode []byte .
  965. // by default, encodes and decodes []byte using base64 Std Encoding
  966. // - UTF-8 support for encoding and decoding
  967. //
  968. // It has better performance than the json library in the standard library,
  969. // by leveraging the performance improvements of the codec library and
  970. // minimizing allocations.
  971. //
  972. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  973. // reading multiple values from a stream containing json and non-json content.
  974. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  975. // all from the same stream in sequence.
  976. //
  977. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs
  978. // are not treated as an error.
  979. // Instead, they are replaced by the Unicode replacement character U+FFFD.
  980. type JsonHandle struct {
  981. textEncodingType
  982. BasicHandle
  983. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  984. // If not configured, raw bytes are encoded to/from base64 text.
  985. RawBytesExt InterfaceExt
  986. // Indent indicates how a value is encoded.
  987. // - If positive, indent by that number of spaces.
  988. // - If negative, indent by that number of tabs.
  989. Indent int8
  990. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  991. //
  992. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  993. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  994. // This can be mitigated by configuring how to encode integers.
  995. //
  996. // IntegerAsString interpretes the following values:
  997. // - if 'L', then encode integers > 2^53 as a json string.
  998. // - if 'A', then encode all integers as a json string
  999. // containing the exact integer representation as a decimal.
  1000. // - else encode all integers as a json number (default)
  1001. IntegerAsString uint8
  1002. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1003. //
  1004. // By default, we encode them as \uXXX
  1005. // to prevent security holes when served from some browsers.
  1006. HTMLCharsAsIs bool
  1007. // PreferFloat says that we will default to decoding a number as a float.
  1008. // If not set, we will examine the characters of the number and decode as an
  1009. // integer type if it doesn't have any of the characters [.eE].
  1010. PreferFloat bool
  1011. // TermWhitespace says that we add a whitespace character
  1012. // at the end of an encoding.
  1013. //
  1014. // The whitespace is important, especially if using numbers in a context
  1015. // where multiple items are written to a stream.
  1016. TermWhitespace bool
  1017. // MapKeyAsString says to encode all map keys as strings.
  1018. //
  1019. // Use this to enforce strict json output.
  1020. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1021. MapKeyAsString bool
  1022. }
  1023. func (h *JsonHandle) hasElemSeparators() bool { return true }
  1024. // SetInterfaceExt sets an extension
  1025. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1026. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1027. }
  1028. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1029. hd := jsonEncDriver{e: e, h: h}
  1030. hd.bs = hd.b[:0]
  1031. hd.reset()
  1032. return &hd
  1033. }
  1034. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1035. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1036. hd := jsonDecDriver{d: d, h: h}
  1037. hd.bs = hd.b[:0]
  1038. hd.reset()
  1039. return &hd
  1040. }
  1041. func (e *jsonEncDriver) reset() {
  1042. e.w = e.e.w
  1043. e.se.i = e.h.RawBytesExt
  1044. if e.bs != nil {
  1045. e.bs = e.bs[:0]
  1046. }
  1047. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1048. e.c = 0
  1049. if e.h.Indent > 0 {
  1050. e.d = true
  1051. e.ds = jsonSpaces[:e.h.Indent]
  1052. } else if e.h.Indent < 0 {
  1053. e.d = true
  1054. e.dt = true
  1055. e.ds = jsonTabs[:-(e.h.Indent)]
  1056. }
  1057. }
  1058. func (d *jsonDecDriver) reset() {
  1059. d.r = d.d.r
  1060. d.se.i = d.h.RawBytesExt
  1061. if d.bs != nil {
  1062. d.bs = d.bs[:0]
  1063. }
  1064. d.c, d.tok = 0, 0
  1065. // d.n.reset()
  1066. }
  1067. // func jsonIsFloatBytes(bs []byte) bool {
  1068. // for _, v := range bs {
  1069. // // if v == '.' || v == 'e' || v == 'E' {
  1070. // if jsonIsFloatSet.isset(v) {
  1071. // return true
  1072. // }
  1073. // }
  1074. // return false
  1075. // }
  1076. func jsonIsFloatBytesB2(bs []byte) bool {
  1077. return bytes.IndexByte(bs, '.') != -1 ||
  1078. bytes.IndexByte(bs, 'E') != -1
  1079. }
  1080. func jsonIsFloatBytesB3(bs []byte) bool {
  1081. return bytes.IndexByte(bs, '.') != -1 ||
  1082. bytes.IndexByte(bs, 'E') != -1 ||
  1083. bytes.IndexByte(bs, 'e') != -1
  1084. }
  1085. var _ decDriver = (*jsonDecDriver)(nil)
  1086. var _ encDriver = (*jsonEncDriver)(nil)