json.go 39 KB

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