json.go 38 KB

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