json.go 34 KB

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