json.go 28 KB

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