json.go 41 KB

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