json.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  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 // 64
  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(jsonLiterals[jsonLitTrue : jsonLitTrue+4])
  142. } else {
  143. e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5])
  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 int
  241. if e.ks && e.e.c == containerMapKey {
  242. blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, int(prec), int(bitsize)))
  243. e.b[0] = '"'
  244. e.b[blen-1] = '"'
  245. } else {
  246. blen = len(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), int(bitsize)))
  247. }
  248. e.w.writeb(e.b[:blen])
  249. }
  250. func (e *jsonEncDriverGeneric) EncodeFloat64(f float64) {
  251. fmt, prec := jsonFloatStrconvFmtPrec64(f)
  252. e.encodeFloat(f, 64, fmt, prec)
  253. }
  254. func (e *jsonEncDriverGeneric) EncodeFloat32(f float32) {
  255. fmt, prec := jsonFloatStrconvFmtPrec32(f)
  256. e.encodeFloat(float64(f), 32, fmt, prec)
  257. }
  258. func (e *jsonEncDriverGeneric) EncodeInt(v int64) {
  259. x := e.is
  260. if x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) || (e.ks && e.e.c == containerMapKey) {
  261. blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
  262. e.b[0] = '"'
  263. e.b[blen-1] = '"'
  264. e.w.writeb(e.b[:blen])
  265. return
  266. }
  267. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  268. }
  269. func (e *jsonEncDriverGeneric) EncodeUint(v uint64) {
  270. x := e.is
  271. if x == 'A' || x == '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 [jsonScratchArrayLen - 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. // xdebugf("WriteArrayElem: e.e.c: %d", e.e.c)
  339. if e.e.c != containerArrayStart {
  340. e.w.writen1(',')
  341. }
  342. if e.d {
  343. e.writeIndent()
  344. }
  345. }
  346. func (e *jsonEncDriver) WriteMapElemKey() {
  347. if e.e.c != containerMapStart {
  348. e.w.writen1(',')
  349. }
  350. if e.d {
  351. e.writeIndent()
  352. }
  353. }
  354. func (e *jsonEncDriver) WriteMapElemValue() {
  355. if e.d {
  356. e.w.writen2(':', ' ')
  357. } else {
  358. e.w.writen1(':')
  359. }
  360. }
  361. func (e *jsonEncDriver) EncodeNil() {
  362. // We always encode nil as just null (never in quotes)
  363. // This allows us to easily decode if a nil in the json stream
  364. // ie if initial token is n.
  365. e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
  366. // if e.h.MapKeyAsString && e.e.c == containerMapKey {
  367. // e.w.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6])
  368. // } else {
  369. // e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
  370. // }
  371. }
  372. func (e *jsonEncDriver) EncodeTime(t time.Time) {
  373. // Do NOT use MarshalJSON, as it allocates internally.
  374. // instead, we call AppendFormat directly, using our scratch buffer (e.b)
  375. if t.IsZero() {
  376. e.EncodeNil()
  377. } else {
  378. e.b[0] = '"'
  379. b := t.AppendFormat(e.b[1:1], time.RFC3339Nano)
  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. se interfaceExtWrapper
  523. bs []byte // scratch, initialized from b. For parsing strings or numbers.
  524. // ---- writable fields during execution --- *try* to keep in sep cache line
  525. // ---- cpu cache line boundary?
  526. b [jsonScratchArrayLen]byte // scratch 1, used for parsing strings or numbers or time.Time
  527. // ---- cpu cache line boundary?
  528. // c containerState
  529. tok uint8 // used to store the token read right after skipWhiteSpace
  530. fnull bool // found null from appendStringAsBytes
  531. _ [2]byte // padding
  532. bstr [4]byte // scratch used for string \UXXX parsing
  533. b2 [jsonScratchArrayLen - 8]byte // scratch 2, used only for readUntil, decNumBytes
  534. // _ [3]uint64 // padding
  535. // n jsonNum
  536. }
  537. // func jsonIsWS(b byte) bool {
  538. // // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  539. // return jsonCharWhitespaceSet.isset(b)
  540. // }
  541. func (d *jsonDecDriver) uncacheRead() {
  542. if d.tok != 0 {
  543. d.r.unreadn1()
  544. d.tok = 0
  545. }
  546. }
  547. func (d *jsonDecDriver) ReadMapStart() int {
  548. if d.tok == 0 {
  549. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  550. }
  551. const xc uint8 = '{'
  552. if d.tok != xc {
  553. d.d.errorf("read map - expect char '%c' but got char '%c'", xc, d.tok)
  554. }
  555. d.tok = 0
  556. return -1
  557. }
  558. func (d *jsonDecDriver) ReadArrayStart() int {
  559. if d.tok == 0 {
  560. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  561. }
  562. const xc uint8 = '['
  563. if d.tok != xc {
  564. d.d.errorf("read array - expect char '%c' but got char '%c'", xc, d.tok)
  565. }
  566. d.tok = 0
  567. return -1
  568. }
  569. func (d *jsonDecDriver) CheckBreak() bool {
  570. if d.tok == 0 {
  571. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  572. }
  573. return d.tok == '}' || d.tok == ']'
  574. }
  575. // For the ReadXXX methods below, we could just delegate to helper functions
  576. // readContainerState(c containerState, xc uint8, check bool)
  577. // - ReadArrayElem would become:
  578. // readContainerState(containerArrayElem, ',', d.d.c != containerArrayStart)
  579. //
  580. // However, until mid-stack inlining comes in go1.11 which supports inlining of
  581. // one-liners, we explicitly write them all 5 out to elide the extra func call.
  582. //
  583. // TODO: For Go 1.11, if inlined, consider consolidating these.
  584. func (d *jsonDecDriver) ReadArrayElem() {
  585. const xc uint8 = ','
  586. if d.tok == 0 {
  587. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  588. }
  589. // xdebugf("ReadArrayElem: d.d.c: %d, token: %c", d.d.c, d.tok)
  590. if d.d.c != containerArrayStart {
  591. if d.tok != xc {
  592. d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok)
  593. }
  594. d.tok = 0
  595. }
  596. }
  597. func (d *jsonDecDriver) ReadArrayEnd() {
  598. const xc uint8 = ']'
  599. if d.tok == 0 {
  600. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  601. }
  602. if d.tok != xc {
  603. d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok)
  604. }
  605. d.tok = 0
  606. }
  607. func (d *jsonDecDriver) ReadMapElemKey() {
  608. const xc uint8 = ','
  609. if d.tok == 0 {
  610. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  611. }
  612. if d.d.c != containerMapStart {
  613. if d.tok != xc {
  614. d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok)
  615. }
  616. d.tok = 0
  617. }
  618. }
  619. func (d *jsonDecDriver) ReadMapElemValue() {
  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 value - expect char '%c' but got char '%c'", xc, d.tok)
  626. }
  627. d.tok = 0
  628. }
  629. func (d *jsonDecDriver) ReadMapEnd() {
  630. const xc uint8 = '}'
  631. if d.tok == 0 {
  632. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  633. }
  634. if d.tok != xc {
  635. d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok)
  636. }
  637. d.tok = 0
  638. }
  639. // func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
  640. // // length here is always less than 8 (literals are: null, true, false)
  641. // bs := d.r.readx(int(length))
  642. // d.tok = 0
  643. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  644. // d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  645. // }
  646. // }
  647. func (d *jsonDecDriver) readLit4True() {
  648. bs := d.r.readx(3)
  649. d.tok = 0
  650. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4True) {
  651. d.d.errorf("expecting %s: got %s", jsonLiteral4True, bs)
  652. }
  653. }
  654. func (d *jsonDecDriver) readLit4False() {
  655. bs := d.r.readx(4)
  656. d.tok = 0
  657. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4False) {
  658. d.d.errorf("expecting %s: got %s", jsonLiteral4False, bs)
  659. }
  660. }
  661. func (d *jsonDecDriver) readLit4Null() {
  662. bs := d.r.readx(3)
  663. d.tok = 0
  664. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4Null) {
  665. d.d.errorf("expecting %s: got %s", jsonLiteral4Null, bs)
  666. }
  667. }
  668. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  669. if d.tok == 0 {
  670. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  671. }
  672. // we shouldn't try to see if "null" was here, right?
  673. // only the plain string: `null` denotes a nil (ie not quotes)
  674. if d.tok == 'n' {
  675. d.readLit4Null()
  676. return true
  677. }
  678. return false
  679. }
  680. func (d *jsonDecDriver) DecodeBool() (v bool) {
  681. if d.tok == 0 {
  682. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  683. }
  684. fquot := d.d.c == containerMapKey && d.tok == '"'
  685. if fquot {
  686. d.tok = d.r.readn1()
  687. }
  688. switch d.tok {
  689. case 'f':
  690. d.readLit4False()
  691. // v = false
  692. case 't':
  693. d.readLit4True()
  694. v = true
  695. default:
  696. d.d.errorf("decode bool: got first char %c", d.tok)
  697. // v = false // "unreachable"
  698. }
  699. if fquot {
  700. d.r.readn1()
  701. }
  702. return
  703. }
  704. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  705. // read string, and pass the string into json.unmarshal
  706. d.appendStringAsBytes()
  707. if d.fnull {
  708. return
  709. }
  710. t, err := time.Parse(time.RFC3339, stringView(d.bs))
  711. if err != nil {
  712. d.d.errorv(err)
  713. }
  714. return
  715. }
  716. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  717. // check container type by checking the first char
  718. if d.tok == 0 {
  719. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  720. }
  721. // optimize this, so we don't do 4 checks but do one computation.
  722. // return jsonContainerSet[d.tok]
  723. // ContainerType is mostly called for Map and Array,
  724. // so this conditional is good enough (max 2 checks typically)
  725. if b := d.tok; b == '{' {
  726. return valueTypeMap
  727. } else if b == '[' {
  728. return valueTypeArray
  729. } else if b == 'n' {
  730. return valueTypeNil
  731. } else if b == '"' {
  732. return valueTypeString
  733. }
  734. return valueTypeUnset
  735. }
  736. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  737. // stores num bytes in d.bs
  738. if d.tok == 0 {
  739. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  740. }
  741. if d.tok == '"' {
  742. bs = d.r.readUntil(d.b2[:0], '"')
  743. bs = bs[:len(bs)-1]
  744. } else {
  745. d.r.unreadn1()
  746. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  747. }
  748. d.tok = 0
  749. return bs
  750. }
  751. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  752. bs := d.decNumBytes()
  753. if len(bs) == 0 {
  754. return
  755. }
  756. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  757. if overflow {
  758. d.d.errorf("overflow parsing unsigned integer: %s", bs)
  759. } else if neg {
  760. d.d.errorf("minus found parsing unsigned integer: %s", bs)
  761. } else if badsyntax {
  762. // fallback: try to decode as float, and cast
  763. n = d.decUint64ViaFloat(bs)
  764. }
  765. return n
  766. }
  767. func (d *jsonDecDriver) DecodeInt64() (i int64) {
  768. const cutoff = uint64(1 << uint(64-1))
  769. bs := d.decNumBytes()
  770. if len(bs) == 0 {
  771. return
  772. }
  773. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  774. if overflow {
  775. d.d.errorf("overflow parsing integer: %s", bs)
  776. } else if badsyntax {
  777. // d.d.errorf("invalid syntax for integer: %s", bs)
  778. // fallback: try to decode as float, and cast
  779. if neg {
  780. n = d.decUint64ViaFloat(bs[1:])
  781. } else {
  782. n = d.decUint64ViaFloat(bs)
  783. }
  784. }
  785. if neg {
  786. if n > cutoff {
  787. d.d.errorf("overflow parsing integer: %s", bs)
  788. }
  789. i = -(int64(n))
  790. } else {
  791. if n >= cutoff {
  792. d.d.errorf("overflow parsing integer: %s", bs)
  793. }
  794. i = int64(n)
  795. }
  796. return
  797. }
  798. func (d *jsonDecDriver) decUint64ViaFloat(s []byte) (u uint64) {
  799. if len(s) == 0 {
  800. return
  801. }
  802. f, err := parseFloat64(s)
  803. if err != nil {
  804. d.d.errorf("invalid syntax for integer: %s", s)
  805. // d.d.errorv(err)
  806. }
  807. fi, ff := math.Modf(f)
  808. if ff > 0 {
  809. d.d.errorf("fractional part found parsing integer: %s", s)
  810. } else if fi > float64(math.MaxUint64) {
  811. d.d.errorf("overflow parsing integer: %s", s)
  812. }
  813. return uint64(fi)
  814. }
  815. // func (d *jsonDecDriver) decodeFloat(bitsize int) (f float64) {
  816. // bs := d.decNumBytes()
  817. // if len(bs) == 0 {
  818. // return
  819. // }
  820. // f, err := parseFloat(bs, bitsize)
  821. // if err != nil {
  822. // d.d.errorv(err)
  823. // }
  824. // return
  825. // }
  826. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  827. // return d.decodeFloat(64)
  828. var err error
  829. if bs := d.decNumBytes(); len(bs) > 0 {
  830. if f, err = parseFloat64(bs); err != nil {
  831. d.d.errorv(err)
  832. }
  833. }
  834. return
  835. }
  836. func (d *jsonDecDriver) DecodeFloat32() (f float32) {
  837. var err error
  838. if bs := d.decNumBytes(); len(bs) > 0 {
  839. if f, err = parseFloat32(bs); err != nil {
  840. d.d.errorv(err)
  841. }
  842. }
  843. return
  844. }
  845. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  846. if ext == nil {
  847. re := rv.(*RawExt)
  848. re.Tag = xtag
  849. d.d.decode(&re.Value)
  850. } else if ext == SelfExt {
  851. rv2 := baseRV(rv)
  852. d.d.decodeValue(rv2, d.h.fnNoExt(rv2.Type()))
  853. } else {
  854. d.d.interfaceExtConvertAndDecode(rv, ext)
  855. }
  856. return
  857. }
  858. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  859. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  860. if d.se.InterfaceExt != nil {
  861. bsOut = bs
  862. d.DecodeExt(&bsOut, 0, &d.se)
  863. return
  864. }
  865. if d.tok == 0 {
  866. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  867. }
  868. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  869. if d.tok == '[' {
  870. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  871. if zerocopy && len(bs) == 0 {
  872. bs = d.d.b[:]
  873. }
  874. if bs == nil {
  875. bs = []byte{}
  876. } else {
  877. bs = bs[:0]
  878. }
  879. d.tok = 0
  880. bs = append(bs, uint8(d.DecodeUint64()))
  881. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  882. for d.tok != ']' {
  883. if d.tok != ',' {
  884. d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
  885. }
  886. d.tok = 0
  887. bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
  888. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  889. }
  890. d.tok = 0
  891. // xdebug2f("bytes from array: returning: %v", bs)
  892. return bs
  893. }
  894. d.appendStringAsBytes()
  895. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  896. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  897. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  898. // However, it sets a fnull field to true, so we can check if a null was found.
  899. if len(d.bs) == 0 {
  900. if d.fnull {
  901. return nil
  902. }
  903. return []byte{}
  904. }
  905. bs0 := d.bs
  906. slen := base64.StdEncoding.DecodedLen(len(bs0))
  907. if slen <= cap(bs) {
  908. bsOut = bs[:slen]
  909. } else if zerocopy && slen <= cap(d.b2) {
  910. bsOut = d.b2[:slen]
  911. } else {
  912. bsOut = make([]byte, slen)
  913. }
  914. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  915. if err != nil {
  916. d.d.errorf("error decoding base64 binary '%s': %v", bs0, err)
  917. return nil
  918. }
  919. if slen != slen2 {
  920. bsOut = bsOut[:slen2]
  921. }
  922. return
  923. }
  924. // func (d *jsonDecDriver) DecodeString() (s string) {
  925. // d.appendStringAsBytes()
  926. // return d.bsToString()
  927. // }
  928. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  929. d.appendStringAsBytes()
  930. return d.bs
  931. }
  932. func (d *jsonDecDriver) appendStringAsBytes() {
  933. if d.tok == 0 {
  934. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  935. }
  936. d.fnull = false
  937. if d.tok != '"' {
  938. // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
  939. // handle non-string scalar: null, true, false or a number
  940. switch d.tok {
  941. case 'n':
  942. d.readLit4Null()
  943. d.bs = d.bs[:0]
  944. d.fnull = true
  945. case 'f':
  946. d.readLit4False()
  947. d.bs = d.bs[:5]
  948. copy(d.bs, "false")
  949. case 't':
  950. d.readLit4True()
  951. d.bs = d.bs[:4]
  952. copy(d.bs, "true")
  953. default:
  954. // try to parse a valid number
  955. bs := d.decNumBytes()
  956. if len(bs) <= cap(d.bs) {
  957. d.bs = d.bs[:len(bs)]
  958. } else {
  959. d.bs = make([]byte, len(bs))
  960. }
  961. copy(d.bs, bs)
  962. }
  963. return
  964. }
  965. d.tok = 0
  966. r := d.r
  967. var cs = r.readUntil(d.b2[:0], '"')
  968. var cslen = uint(len(cs))
  969. var c uint8
  970. v := d.bs[:0]
  971. // append on each byte seen can be expensive, so we just
  972. // keep track of where we last read a contiguous set of
  973. // non-special bytes (using cursor variable),
  974. // and when we see a special byte
  975. // e.g. end-of-slice, " or \,
  976. // we will append the full range into the v slice before proceeding
  977. var i, cursor uint
  978. for {
  979. if i == cslen {
  980. v = append(v, cs[cursor:]...)
  981. cs = r.readUntil(d.b2[:0], '"')
  982. cslen = uint(len(cs))
  983. i, cursor = 0, 0
  984. }
  985. c = cs[i]
  986. if c == '"' {
  987. v = append(v, cs[cursor:i]...)
  988. break
  989. }
  990. if c != '\\' {
  991. i++
  992. continue
  993. }
  994. v = append(v, cs[cursor:i]...)
  995. i++
  996. c = cs[i]
  997. switch c {
  998. case '"', '\\', '/', '\'':
  999. v = append(v, c)
  1000. case 'b':
  1001. v = append(v, '\b')
  1002. case 'f':
  1003. v = append(v, '\f')
  1004. case 'n':
  1005. v = append(v, '\n')
  1006. case 'r':
  1007. v = append(v, '\r')
  1008. case 't':
  1009. v = append(v, '\t')
  1010. case 'u':
  1011. var r rune
  1012. var rr uint32
  1013. if cslen < i+4 {
  1014. d.d.errorf("need at least 4 more bytes for unicode sequence")
  1015. }
  1016. var j uint
  1017. for _, c = range cs[i+1 : i+5] { // bounds-check-elimination
  1018. // best to use explicit if-else
  1019. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  1020. if c >= '0' && c <= '9' {
  1021. rr = rr*16 + uint32(c-jsonU4Chk2)
  1022. } else if c >= 'a' && c <= 'f' {
  1023. rr = rr*16 + uint32(c-jsonU4Chk1)
  1024. } else if c >= 'A' && c <= 'F' {
  1025. rr = rr*16 + uint32(c-jsonU4Chk0)
  1026. } else {
  1027. r = unicode.ReplacementChar
  1028. i += 4
  1029. goto encode_rune
  1030. }
  1031. }
  1032. r = rune(rr)
  1033. i += 4
  1034. if utf16.IsSurrogate(r) {
  1035. if len(cs) >= int(i+6) {
  1036. var cx = cs[i+1:][:6:6] // [:6] affords bounds-check-elimination
  1037. if cx[0] == '\\' && cx[1] == 'u' {
  1038. i += 2
  1039. var rr1 uint32
  1040. for j = 2; j < 6; j++ {
  1041. c = cx[j]
  1042. if c >= '0' && c <= '9' {
  1043. rr = rr*16 + uint32(c-jsonU4Chk2)
  1044. } else if c >= 'a' && c <= 'f' {
  1045. rr = rr*16 + uint32(c-jsonU4Chk1)
  1046. } else if c >= 'A' && c <= 'F' {
  1047. rr = rr*16 + uint32(c-jsonU4Chk0)
  1048. } else {
  1049. r = unicode.ReplacementChar
  1050. i += 4
  1051. goto encode_rune
  1052. }
  1053. }
  1054. r = utf16.DecodeRune(r, rune(rr1))
  1055. i += 4
  1056. goto encode_rune
  1057. }
  1058. }
  1059. r = unicode.ReplacementChar
  1060. }
  1061. encode_rune:
  1062. w2 := utf8.EncodeRune(d.bstr[:], r)
  1063. v = append(v, d.bstr[:w2]...)
  1064. default:
  1065. d.d.errorf("unsupported escaped value: %c", c)
  1066. }
  1067. i++
  1068. cursor = i
  1069. }
  1070. d.bs = v
  1071. }
  1072. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  1073. const cutoff = uint64(1 << uint(64-1))
  1074. var n uint64
  1075. var neg, badsyntax, overflow bool
  1076. if len(bs) == 0 {
  1077. if d.h.PreferFloat {
  1078. z.v = valueTypeFloat
  1079. z.f = 0
  1080. } else if d.h.SignedInteger {
  1081. z.v = valueTypeInt
  1082. z.i = 0
  1083. } else {
  1084. z.v = valueTypeUint
  1085. z.u = 0
  1086. }
  1087. return
  1088. }
  1089. if d.h.PreferFloat {
  1090. goto F
  1091. }
  1092. n, neg, badsyntax, overflow = jsonParseInteger(bs)
  1093. if badsyntax || overflow {
  1094. goto F
  1095. }
  1096. if neg {
  1097. if n > cutoff {
  1098. goto F
  1099. }
  1100. z.v = valueTypeInt
  1101. z.i = -(int64(n))
  1102. } else if d.h.SignedInteger {
  1103. if n >= cutoff {
  1104. goto F
  1105. }
  1106. z.v = valueTypeInt
  1107. z.i = int64(n)
  1108. } else {
  1109. z.v = valueTypeUint
  1110. z.u = n
  1111. }
  1112. return
  1113. F:
  1114. z.v = valueTypeFloat
  1115. z.f, err = parseFloat64(bs)
  1116. return
  1117. }
  1118. func (d *jsonDecDriver) bsToString() string {
  1119. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  1120. if jsonAlwaysReturnInternString || d.d.c == containerMapKey {
  1121. return d.d.string(d.bs)
  1122. }
  1123. return string(d.bs)
  1124. }
  1125. func (d *jsonDecDriver) DecodeNaked() {
  1126. z := d.d.naked()
  1127. // var decodeFurther bool
  1128. if d.tok == 0 {
  1129. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  1130. }
  1131. switch d.tok {
  1132. case 'n':
  1133. d.readLit4Null()
  1134. z.v = valueTypeNil
  1135. case 'f':
  1136. d.readLit4False()
  1137. z.v = valueTypeBool
  1138. z.b = false
  1139. case 't':
  1140. d.readLit4True()
  1141. z.v = valueTypeBool
  1142. z.b = true
  1143. case '{':
  1144. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  1145. case '[':
  1146. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  1147. case '"':
  1148. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  1149. d.appendStringAsBytes()
  1150. if len(d.bs) > 0 && d.d.c == containerMapKey && d.h.MapKeyAsString {
  1151. if bytes.Equal(d.bs, jsonLiteralNull) {
  1152. z.v = valueTypeNil
  1153. } else if bytes.Equal(d.bs, jsonLiteralTrue) {
  1154. z.v = valueTypeBool
  1155. z.b = true
  1156. } else if bytes.Equal(d.bs, jsonLiteralFalse) {
  1157. z.v = valueTypeBool
  1158. z.b = false
  1159. } else {
  1160. // check if a number: float, int or uint
  1161. if err := d.nakedNum(z, d.bs); err != nil {
  1162. z.v = valueTypeString
  1163. z.s = d.bsToString()
  1164. }
  1165. }
  1166. } else {
  1167. z.v = valueTypeString
  1168. z.s = d.bsToString()
  1169. }
  1170. default: // number
  1171. bs := d.decNumBytes()
  1172. if len(bs) == 0 {
  1173. d.d.errorf("decode number from empty string")
  1174. return
  1175. }
  1176. if err := d.nakedNum(z, bs); err != nil {
  1177. d.d.errorf("decode number from %s: %v", bs, err)
  1178. return
  1179. }
  1180. }
  1181. // if decodeFurther {
  1182. // d.s.sc.retryRead()
  1183. // }
  1184. }
  1185. //----------------------
  1186. // JsonHandle is a handle for JSON encoding format.
  1187. //
  1188. // Json is comprehensively supported:
  1189. // - decodes numbers into interface{} as int, uint or float64
  1190. // based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
  1191. // - decode integers from float formatted numbers e.g. 1.27e+8
  1192. // - decode any json value (numbers, bool, etc) from quoted strings
  1193. // - configurable way to encode/decode []byte .
  1194. // by default, encodes and decodes []byte using base64 Std Encoding
  1195. // - UTF-8 support for encoding and decoding
  1196. //
  1197. // It has better performance than the json library in the standard library,
  1198. // by leveraging the performance improvements of the codec library.
  1199. //
  1200. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1201. // reading multiple values from a stream containing json and non-json content.
  1202. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1203. // all from the same stream in sequence.
  1204. //
  1205. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are
  1206. // not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
  1207. type JsonHandle struct {
  1208. textEncodingType
  1209. BasicHandle
  1210. // Indent indicates how a value is encoded.
  1211. // - If positive, indent by that number of spaces.
  1212. // - If negative, indent by that number of tabs.
  1213. Indent int8
  1214. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1215. //
  1216. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1217. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1218. // This can be mitigated by configuring how to encode integers.
  1219. //
  1220. // IntegerAsString interpretes the following values:
  1221. // - if 'L', then encode integers > 2^53 as a json string.
  1222. // - if 'A', then encode all integers as a json string
  1223. // containing the exact integer representation as a decimal.
  1224. // - else encode all integers as a json number (default)
  1225. IntegerAsString byte
  1226. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1227. //
  1228. // By default, we encode them as \uXXX
  1229. // to prevent security holes when served from some browsers.
  1230. HTMLCharsAsIs bool
  1231. // PreferFloat says that we will default to decoding a number as a float.
  1232. // If not set, we will examine the characters of the number and decode as an
  1233. // integer type if it doesn't have any of the characters [.eE].
  1234. PreferFloat bool
  1235. // TermWhitespace says that we add a whitespace character
  1236. // at the end of an encoding.
  1237. //
  1238. // The whitespace is important, especially if using numbers in a context
  1239. // where multiple items are written to a stream.
  1240. TermWhitespace bool
  1241. // MapKeyAsString says to encode all map keys as strings.
  1242. //
  1243. // Use this to enforce strict json output.
  1244. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1245. MapKeyAsString bool
  1246. // _ uint64 // padding (cache line)
  1247. // Note: below, we store hardly-used items
  1248. // e.g. RawBytesExt (which is already cached in the (en|de)cDriver).
  1249. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1250. // If not configured, raw bytes are encoded to/from base64 text.
  1251. RawBytesExt InterfaceExt
  1252. // _ [2]uint64 // padding
  1253. }
  1254. // Name returns the name of the handle: json
  1255. func (h *JsonHandle) Name() string { return "json" }
  1256. func (h *JsonHandle) hasElemSeparators() bool { return true }
  1257. func (h *JsonHandle) typical() bool {
  1258. return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L'
  1259. }
  1260. func (h *JsonHandle) recreateEncDriver(ed encDriver) (v bool) {
  1261. _, v = ed.(*jsonEncDriverTypical)
  1262. return v != h.typical()
  1263. }
  1264. // SetInterfaceExt sets an extension
  1265. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1266. return h.SetExt(rt, tag, makeExt(ext))
  1267. }
  1268. func (h *JsonHandle) newEncDriver(e *Encoder) (ee encDriver) {
  1269. var hd *jsonEncDriver
  1270. if h.typical() {
  1271. var v jsonEncDriverTypical
  1272. ee = &v
  1273. hd = &v.jsonEncDriver
  1274. } else {
  1275. var v jsonEncDriverGeneric
  1276. ee = &v
  1277. hd = &v.jsonEncDriver
  1278. }
  1279. hd.e, hd.h, hd.bs = e, h, hd.b[:0]
  1280. ee.reset()
  1281. return
  1282. }
  1283. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1284. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1285. hd := jsonDecDriver{d: d, h: h}
  1286. hd.bs = hd.b[:0]
  1287. hd.reset()
  1288. return &hd
  1289. }
  1290. func (e *jsonEncDriver) reset() {
  1291. e.w = e.e.w()
  1292. // (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b)
  1293. if e.h.HTMLCharsAsIs {
  1294. e.s = &jsonCharSafeSet
  1295. } else {
  1296. e.s = &jsonCharHtmlSafeSet
  1297. }
  1298. e.se.InterfaceExt = e.h.RawBytesExt
  1299. if e.bs == nil {
  1300. e.bs = e.b[:0]
  1301. } else {
  1302. e.bs = e.bs[:0]
  1303. }
  1304. }
  1305. func (d *jsonDecDriver) reset() {
  1306. d.r = d.d.r()
  1307. d.se.InterfaceExt = d.h.RawBytesExt
  1308. if d.bs != nil {
  1309. d.bs = d.bs[:0]
  1310. }
  1311. d.tok = 0
  1312. // d.n.reset()
  1313. }
  1314. func (d *jsonDecDriver) atEndOfDecode() {}
  1315. // jsonFloatStrconvFmtPrec ...
  1316. //
  1317. // ensure that every float has an 'e' or '.' in it,/ for easy differentiation from integers.
  1318. // this is better/faster than checking if encoded value has [e.] and appending if needed.
  1319. // func jsonFloatStrconvFmtPrec(f float64, bits32 bool) (fmt byte, prec int) {
  1320. // fmt = 'f'
  1321. // prec = -1
  1322. // var abs = math.Abs(f)
  1323. // if abs == 0 || abs == 1 {
  1324. // prec = 1
  1325. // } else if !bits32 && (abs < 1e-6 || abs >= 1e21) ||
  1326. // bits32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
  1327. // fmt = 'e'
  1328. // } else if _, frac := math.Modf(abs); frac == 0 {
  1329. // // ensure that floats have a .0 at the end, for easy identification as floats
  1330. // prec = 1
  1331. // }
  1332. // return
  1333. // }
  1334. func jsonFloatStrconvFmtPrec64(f float64) (fmt byte, prec int8) {
  1335. fmt = 'f'
  1336. prec = -1
  1337. var abs = math.Abs(f)
  1338. if abs == 0 || abs == 1 {
  1339. prec = 1
  1340. } else if abs < 1e-6 || abs >= 1e21 {
  1341. fmt = 'e'
  1342. } else if noFrac64(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1343. prec = 1
  1344. }
  1345. return
  1346. }
  1347. func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) {
  1348. fmt = 'f'
  1349. prec = -1
  1350. var abs = abs32(f)
  1351. if abs == 0 || abs == 1 {
  1352. prec = 1
  1353. } else if abs < 1e-6 || abs >= 1e21 {
  1354. fmt = 'e'
  1355. } else if noFrac32(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1356. prec = 1
  1357. }
  1358. return
  1359. }
  1360. // custom-fitted version of strconv.Parse(Ui|I)nt.
  1361. // Also ensures we don't have to search for .eE to determine if a float or not.
  1362. // Note: s CANNOT be a zero-length slice.
  1363. func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) {
  1364. const maxUint64 = (1<<64 - 1)
  1365. const cutoff = maxUint64/10 + 1
  1366. if len(s) == 0 { // bounds-check-elimination
  1367. // treat empty string as zero value
  1368. // badSyntax = true
  1369. return
  1370. }
  1371. switch s[0] {
  1372. case '+':
  1373. s = s[1:]
  1374. case '-':
  1375. s = s[1:]
  1376. neg = true
  1377. }
  1378. for _, c := range s {
  1379. if c < '0' || c > '9' {
  1380. badSyntax = true
  1381. return
  1382. }
  1383. // unsigned integers don't overflow well on multiplication, so check cutoff here
  1384. // e.g. (maxUint64-5)*10 doesn't overflow well ...
  1385. if n >= cutoff {
  1386. overflow = true
  1387. return
  1388. }
  1389. n *= 10
  1390. n1 := n + uint64(c-'0')
  1391. if n1 < n || n1 > maxUint64 {
  1392. overflow = true
  1393. return
  1394. }
  1395. n = n1
  1396. }
  1397. return
  1398. }
  1399. var _ decDriverContainerTracker = (*jsonDecDriver)(nil)
  1400. var _ encDriverContainerTracker = (*jsonEncDriver)(nil)
  1401. var _ decDriver = (*jsonDecDriver)(nil)
  1402. var _ encDriver = (*jsonEncDriverGeneric)(nil)
  1403. var _ encDriver = (*jsonEncDriverTypical)(nil)
  1404. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverTypical)(nil)
  1405. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverGeneric)(nil)
  1406. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriver)(nil)
  1407. // var _ encDriver = (*jsonEncDriver)(nil)