json.go 28 KB

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