json.go 29 KB

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