json.go 41 KB

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