json.go 40 KB

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