json.go 31 KB

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