json.go 39 KB

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