json.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  1. // Copyright (c) 2012-2020 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. // We cannot use strconv.(Q|Unq)uote because json quotes/unquotes differently.
  16. import (
  17. "bytes"
  18. "encoding/base64"
  19. "math"
  20. "reflect"
  21. "strconv"
  22. "time"
  23. "unicode"
  24. "unicode/utf16"
  25. "unicode/utf8"
  26. )
  27. //--------------------------------
  28. var jsonLiterals = [...]byte{
  29. '"', 't', 'r', 'u', 'e', '"',
  30. '"', 'f', 'a', 'l', 's', 'e', '"',
  31. '"', 'n', 'u', 'l', 'l', '"',
  32. }
  33. const (
  34. jsonLitTrueQ = 0
  35. jsonLitTrue = 1
  36. jsonLitFalseQ = 6
  37. jsonLitFalse = 7
  38. jsonLitNullQ = 13
  39. jsonLitNull = 14
  40. )
  41. var (
  42. // jsonLiteralTrueQ = jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6]
  43. // jsonLiteralFalseQ = jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7]
  44. // jsonLiteralNullQ = jsonLiterals[jsonLitNullQ : jsonLitNullQ+6]
  45. jsonLiteralTrue = jsonLiterals[jsonLitTrue : jsonLitTrue+4]
  46. jsonLiteralFalse = jsonLiterals[jsonLitFalse : jsonLitFalse+5]
  47. jsonLiteralNull = jsonLiterals[jsonLitNull : jsonLitNull+4]
  48. // these are used, after consuming the first char
  49. jsonLiteral4True = jsonLiterals[jsonLitTrue+1 : jsonLitTrue+4]
  50. jsonLiteral4False = jsonLiterals[jsonLitFalse+1 : jsonLitFalse+5]
  51. jsonLiteral4Null = jsonLiterals[jsonLitNull+1 : jsonLitNull+4]
  52. )
  53. const (
  54. jsonU4Chk2 = '0'
  55. jsonU4Chk1 = 'a' - 10
  56. jsonU4Chk0 = 'A' - 10
  57. )
  58. const (
  59. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  60. // - If we see first character of null, false or true,
  61. // do not validate subsequent characters.
  62. // - e.g. if we see a n, assume null and skip next 3 characters,
  63. // and do not validate they are ull.
  64. // P.S. Do not expect a significant decoding boost from this.
  65. jsonValidateSymbols = true
  66. // jsonEscapeMultiByteUnicodeSep controls whether some unicode characters
  67. // that are valid json but may bomb in some contexts are escaped during encoeing.
  68. //
  69. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  70. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  71. jsonEscapeMultiByteUnicodeSep = true
  72. // jsonManualInlineDecRdInHotZones controls whether we manually inline some decReader calls.
  73. //
  74. // encode performance is at par with libraries that just iterate over bytes directly,
  75. // because encWr (with inlined bytesEncAppender calls) is inlined.
  76. // Conversely, decode performance suffers because decRd (with inlined bytesDecReader calls)
  77. // isn't inlinable.
  78. //
  79. // To improve decode performamnce from json:
  80. // - readn1 is only called for \u
  81. // - consequently, to optimize json decoding, we specifically need inlining
  82. // for bytes use-case of some other decReader methods:
  83. // - jsonReadAsisChars, skipWhitespace (advance) and jsonReadNum
  84. // - AND THEN readn3, readn4 (for ull, rue and alse).
  85. // - (readn1 is only called when a char is escaped).
  86. // - without inlining, we still pay the cost of a method invocationK, and this dominates time
  87. // - To mitigate, we manually inline in hot zones
  88. // *excluding places where used sparingly (e.g. nextValueBytes, and other atypical cases)*.
  89. // - jsonReadAsisChars *only* called in: appendStringAsBytes
  90. // - advance called: everywhere
  91. // - jsonReadNum: decNumBytes, DecodeNaked
  92. // - From running go test (our anecdotal findings):
  93. // - calling jsonReadAsisChars in appendStringAsBytes: 23431
  94. // - calling jsonReadNum in decNumBytes: 15251
  95. // - calling jsonReadNum in DecodeNaked: 612
  96. // Consequently, we manually inline jsonReadAsisChars (in appendStringAsBytes)
  97. // and jsonReadNum (in decNumbytes)
  98. jsonManualInlineDecRdInHotZones = true
  99. jsonSpacesOrTabsLen = 128
  100. // jsonAlwaysReturnInternString = false
  101. )
  102. var (
  103. // jsonTabs and jsonSpaces are used as caches for indents
  104. jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte
  105. jsonCharHtmlSafeSet bitset256
  106. jsonCharSafeSet bitset256
  107. )
  108. func init() {
  109. var i byte
  110. for i = 0; i < jsonSpacesOrTabsLen; i++ {
  111. jsonSpaces[i] = ' '
  112. jsonTabs[i] = '\t'
  113. }
  114. // populate the safe values as true: note: ASCII control characters are (0-31)
  115. // jsonCharSafeSet: all true except (0-31) " \
  116. // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
  117. for i = 32; i < utf8.RuneSelf; i++ {
  118. switch i {
  119. case '"', '\\':
  120. case '<', '>', '&':
  121. jsonCharSafeSet.set(i) // = true
  122. default:
  123. jsonCharSafeSet.set(i)
  124. jsonCharHtmlSafeSet.set(i)
  125. }
  126. }
  127. }
  128. // ----------------
  129. type jsonEncState struct {
  130. di int8 // indent per: if negative, use tabs
  131. d bool // indenting?
  132. dl uint16 // indent level
  133. }
  134. func (x jsonEncState) captureState() interface{} { return x }
  135. func (x *jsonEncState) restoreState(v interface{}) { *x = v.(jsonEncState) }
  136. type jsonEncDriver struct {
  137. noBuiltInTypes
  138. h *JsonHandle
  139. // se interfaceExtWrapper
  140. // ---- cpu cache line boundary?
  141. jsonEncState
  142. ks bool // map key as string
  143. is byte // integer as string
  144. typical bool
  145. rawext bool // rawext configured on the handle
  146. s *bitset256 // safe set for characters (taking h.HTMLAsIs into consideration)
  147. // buf *[]byte // used mostly for encoding []byte
  148. // scratch buffer for: encode time, numbers, etc
  149. //
  150. // RFC3339Nano uses 35 chars: 2006-01-02T15:04:05.999999999Z07:00
  151. // MaxUint64 uses 20 chars: 18446744073709551615
  152. // floats are encoded using: f/e fmt, and -1 precision, or 1 if no fractions.
  153. // This means we are limited by the number of characters for the
  154. // mantissa (up to 17), exponent (up to 3), signs (up to 3), dot (up to 1), E (up to 1)
  155. // for a total of 24 characters.
  156. // -xxx.yyyyyyyyyyyye-zzz
  157. // Consequently, 35 characters should be sufficient for encoding time, integers or floats.
  158. // We use up all the remaining bytes to make this use full cache lines.
  159. b [56]byte
  160. e Encoder
  161. }
  162. func (e *jsonEncDriver) encoder() *Encoder { return &e.e }
  163. func (e *jsonEncDriver) writeIndent() {
  164. e.e.encWr.writen1('\n')
  165. x := int(e.di) * int(e.dl)
  166. if e.di < 0 {
  167. x = -x
  168. for x > jsonSpacesOrTabsLen {
  169. e.e.encWr.writeb(jsonTabs[:])
  170. x -= jsonSpacesOrTabsLen
  171. }
  172. e.e.encWr.writeb(jsonTabs[:x])
  173. } else {
  174. for x > jsonSpacesOrTabsLen {
  175. e.e.encWr.writeb(jsonSpaces[:])
  176. x -= jsonSpacesOrTabsLen
  177. }
  178. e.e.encWr.writeb(jsonSpaces[:x])
  179. }
  180. }
  181. func (e *jsonEncDriver) WriteArrayElem() {
  182. if e.e.c != containerArrayStart {
  183. e.e.encWr.writen1(',')
  184. }
  185. if e.d {
  186. e.writeIndent()
  187. }
  188. }
  189. func (e *jsonEncDriver) WriteMapElemKey() {
  190. if e.e.c != containerMapStart {
  191. e.e.encWr.writen1(',')
  192. }
  193. if e.d {
  194. e.writeIndent()
  195. }
  196. }
  197. func (e *jsonEncDriver) WriteMapElemValue() {
  198. if e.d {
  199. e.e.encWr.writen2(':', ' ')
  200. } else {
  201. e.e.encWr.writen1(':')
  202. }
  203. }
  204. func (e *jsonEncDriver) EncodeNil() {
  205. // We always encode nil as just null (never in quotes)
  206. // This allows us to easily decode if a nil in the json stream
  207. // ie if initial token is n.
  208. // e.e.encWr.writeb(jsonLiteralNull)
  209. e.e.encWr.writen4([4]byte{'n', 'u', 'l', 'l'})
  210. }
  211. func (e *jsonEncDriver) EncodeTime(t time.Time) {
  212. // Do NOT use MarshalJSON, as it allocates internally.
  213. // instead, we call AppendFormat directly, using our scratch buffer (e.b)
  214. if t.IsZero() {
  215. e.EncodeNil()
  216. } else {
  217. e.b[0] = '"'
  218. b := fmtTime(t, time.RFC3339Nano, e.b[1:1])
  219. e.b[len(b)+1] = '"'
  220. e.e.encWr.writeb(e.b[:len(b)+2])
  221. }
  222. }
  223. func (e *jsonEncDriver) EncodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
  224. if ext == SelfExt {
  225. e.e.encodeValue(baseRV(rv), e.h.fnNoExt(basetype))
  226. } else if v := ext.ConvertExt(rv); v == nil {
  227. e.EncodeNil()
  228. } else {
  229. e.e.encode(v)
  230. }
  231. }
  232. func (e *jsonEncDriver) EncodeRawExt(re *RawExt) {
  233. // only encodes re.Value (never re.Data)
  234. if re.Value == nil {
  235. e.EncodeNil()
  236. } else {
  237. e.e.encode(re.Value)
  238. }
  239. }
  240. func (e *jsonEncDriver) EncodeBool(b bool) {
  241. // Use writen with an array instead of writeb with a slice
  242. // i.e. in place of e.e.encWr.writeb(jsonLiteralTrueQ)
  243. // OR jsonLiteralTrue, jsonLiteralFalse, jsonLiteralFalseQ, etc
  244. if e.ks && e.e.c == containerMapKey {
  245. if b {
  246. e.e.encWr.writen4([4]byte{'"', 't', 'r', 'u'})
  247. e.e.encWr.writen2('e', '"')
  248. } else {
  249. e.e.encWr.writen4([4]byte{'"', 'f', 'a', 'l'})
  250. e.e.encWr.writen2('s', 'e')
  251. e.e.encWr.writen1('"')
  252. }
  253. } else {
  254. if b {
  255. e.e.encWr.writen4([4]byte{'t', 'r', 'u', 'e'})
  256. } else {
  257. e.e.encWr.writen4([4]byte{'f', 'a', 'l', 's'})
  258. e.e.encWr.writen1('e')
  259. }
  260. }
  261. }
  262. func (e *jsonEncDriver) encodeFloat(f float64, bitsize, fmt byte, prec int8) {
  263. var blen uint
  264. if e.ks && e.e.c == containerMapKey {
  265. blen = 2 + uint(len(strconv.AppendFloat(e.b[1:1], f, fmt, int(prec), int(bitsize))))
  266. // _ = e.b[:blen]
  267. e.b[0] = '"'
  268. e.b[blen-1] = '"'
  269. e.e.encWr.writeb(e.b[:blen])
  270. } else {
  271. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), int(bitsize)))
  272. }
  273. }
  274. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  275. if math.IsNaN(f) || math.IsInf(f, 0) {
  276. e.EncodeNil()
  277. return
  278. }
  279. fmt, prec := jsonFloatStrconvFmtPrec64(f)
  280. e.encodeFloat(f, 64, fmt, prec)
  281. }
  282. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  283. if math.IsNaN(float64(f)) || math.IsInf(float64(f), 0) {
  284. e.EncodeNil()
  285. return
  286. }
  287. fmt, prec := jsonFloatStrconvFmtPrec32(f)
  288. e.encodeFloat(float64(f), 32, fmt, prec)
  289. }
  290. func (e *jsonEncDriver) encodeUint(neg bool, quotes bool, u uint64) {
  291. // copied mostly from std library: strconv
  292. // this should only be called on 64bit OS.
  293. const smallsString = "00010203040506070809" +
  294. "10111213141516171819" +
  295. "20212223242526272829" +
  296. "30313233343536373839" +
  297. "40414243444546474849" +
  298. "50515253545556575859" +
  299. "60616263646566676869" +
  300. "70717273747576777879" +
  301. "80818283848586878889" +
  302. "90919293949596979899"
  303. // typically, 19 or 20 bytes sufficient for decimal encoding a uint64
  304. // var a [24]byte
  305. var a = e.b[0:24]
  306. var i = uint8(len(a))
  307. if quotes {
  308. i--
  309. a[i] = '"'
  310. }
  311. // u guaranteed to fit into a uint (as we are not 32bit OS)
  312. var is uint
  313. var us = uint(u)
  314. for us >= 100 {
  315. is = us % 100 * 2
  316. us /= 100
  317. i -= 2
  318. a[i+1] = smallsString[is+1]
  319. a[i+0] = smallsString[is+0]
  320. }
  321. // us < 100
  322. is = us * 2
  323. i--
  324. a[i] = smallsString[is+1]
  325. if us >= 10 {
  326. i--
  327. a[i] = smallsString[is]
  328. }
  329. if neg {
  330. i--
  331. a[i] = '-'
  332. }
  333. if quotes {
  334. i--
  335. a[i] = '"'
  336. }
  337. e.e.encWr.writeb(a[i:])
  338. }
  339. func (e *jsonEncDriver) EncodeInt(v int64) {
  340. quotes := e.is == 'A' || e.is == 'L' && (v > 1<<53 || v < -(1<<53)) ||
  341. (e.ks && e.e.c == containerMapKey)
  342. if cpu32Bit {
  343. if quotes {
  344. blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
  345. e.b[0] = '"'
  346. e.b[blen-1] = '"'
  347. e.e.encWr.writeb(e.b[:blen])
  348. } else {
  349. e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
  350. }
  351. return
  352. }
  353. if v < 0 {
  354. e.encodeUint(true, quotes, uint64(-v))
  355. } else {
  356. e.encodeUint(false, quotes, uint64(v))
  357. }
  358. }
  359. func (e *jsonEncDriver) EncodeUint(v uint64) {
  360. quotes := e.is == 'A' || e.is == 'L' && v > 1<<53 || (e.ks && e.e.c == containerMapKey)
  361. if cpu32Bit {
  362. // use strconv directly, as optimized encodeUint only works on 64-bit alone
  363. if quotes {
  364. blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
  365. e.b[0] = '"'
  366. e.b[blen-1] = '"'
  367. e.e.encWr.writeb(e.b[:blen])
  368. } else {
  369. e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
  370. }
  371. return
  372. }
  373. e.encodeUint(false, quotes, v)
  374. }
  375. func (e *jsonEncDriver) EncodeString(v string) {
  376. if e.h.StringToRaw {
  377. e.EncodeStringBytesRaw(bytesView(v))
  378. return
  379. }
  380. e.quoteStr(v)
  381. }
  382. func (e *jsonEncDriver) EncodeStringBytesRaw(v []byte) {
  383. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  384. if v == nil {
  385. e.EncodeNil()
  386. return
  387. }
  388. if e.rawext {
  389. iv := e.h.RawBytesExt.ConvertExt(v)
  390. if iv == nil {
  391. e.EncodeNil()
  392. } else {
  393. e.e.encode(iv)
  394. }
  395. return
  396. }
  397. slen := base64.StdEncoding.EncodedLen(len(v)) + 2
  398. // bs := e.e.blist.check(*e.buf, n)[:slen]
  399. // *e.buf = bs
  400. bs := e.e.blist.peek(slen, false)[:slen]
  401. bs[0] = '"'
  402. base64.StdEncoding.Encode(bs[1:], v)
  403. bs[len(bs)-1] = '"'
  404. e.e.encWr.writeb(bs)
  405. }
  406. // indent is done as below:
  407. // - newline and indent are added before each mapKey or arrayElem
  408. // - newline and indent are added before each ending,
  409. // except there was no entry (so we can have {} or [])
  410. func (e *jsonEncDriver) WriteArrayStart(length int) {
  411. if e.d {
  412. e.dl++
  413. }
  414. e.e.encWr.writen1('[')
  415. }
  416. func (e *jsonEncDriver) WriteArrayEnd() {
  417. if e.d {
  418. e.dl--
  419. e.writeIndent()
  420. }
  421. e.e.encWr.writen1(']')
  422. }
  423. func (e *jsonEncDriver) WriteMapStart(length int) {
  424. if e.d {
  425. e.dl++
  426. }
  427. e.e.encWr.writen1('{')
  428. }
  429. func (e *jsonEncDriver) WriteMapEnd() {
  430. if e.d {
  431. e.dl--
  432. if e.e.c != containerMapStart {
  433. e.writeIndent()
  434. }
  435. }
  436. e.e.encWr.writen1('}')
  437. }
  438. func (e *jsonEncDriver) quoteStr(s string) {
  439. // adapted from std pkg encoding/json
  440. const hex = "0123456789abcdef"
  441. w := e.e.w()
  442. w.writen1('"')
  443. var i, start uint
  444. for i < uint(len(s)) {
  445. // encode all bytes < 0x20 (except \r, \n).
  446. // also encode < > & to prevent security holes when served to some browsers.
  447. // We optimize for ascii, by assumining that most characters are in the BMP
  448. // and natively consumed by json without much computation.
  449. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  450. // if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) {
  451. if e.s.isset(s[i]) {
  452. i++
  453. continue
  454. }
  455. // b := s[i]
  456. if s[i] < utf8.RuneSelf {
  457. if start < i {
  458. w.writestr(s[start:i])
  459. }
  460. switch s[i] {
  461. case '\\', '"':
  462. w.writen2('\\', s[i])
  463. case '\n':
  464. w.writen2('\\', 'n')
  465. case '\r':
  466. w.writen2('\\', 'r')
  467. case '\b':
  468. w.writen2('\\', 'b')
  469. case '\f':
  470. w.writen2('\\', 'f')
  471. case '\t':
  472. w.writen2('\\', 't')
  473. default:
  474. w.writestr(`\u00`)
  475. w.writen2(hex[s[i]>>4], hex[s[i]&0xF])
  476. }
  477. i++
  478. start = i
  479. continue
  480. }
  481. c, size := utf8.DecodeRuneInString(s[i:])
  482. if c == utf8.RuneError && size == 1 { // meaning invalid encoding (so output as-is)
  483. if start < i {
  484. w.writestr(s[start:i])
  485. }
  486. w.writestr(`\uFFFD`)
  487. i++
  488. start = i
  489. continue
  490. }
  491. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  492. // Both technically valid JSON, but bomb on JSONP, so fix here *unconditionally*.
  493. if jsonEscapeMultiByteUnicodeSep && (c == '\u2028' || c == '\u2029') {
  494. if start < i {
  495. w.writestr(s[start:i])
  496. }
  497. w.writestr(`\u202`)
  498. w.writen1(hex[c&0xF])
  499. i += uint(size)
  500. start = i
  501. continue
  502. }
  503. i += uint(size)
  504. }
  505. if start < uint(len(s)) {
  506. w.writestr(s[start:])
  507. }
  508. w.writen1('"')
  509. }
  510. func (e *jsonEncDriver) atEndOfEncode() {
  511. if e.h.TermWhitespace {
  512. var c byte = ' ' // default is that scalar is written, so output space
  513. if e.e.c != 0 {
  514. c = '\n' // for containers (map/list), output a newline
  515. }
  516. e.e.encWr.writen1(c)
  517. }
  518. }
  519. // ----------
  520. type jsonDecState struct {
  521. rawext bool // rawext configured on the handle
  522. tok uint8 // used to store the token read right after skipWhiteSpace
  523. _ bool // found null
  524. _ byte // padding
  525. bstr [4]byte // scratch used for string \UXXX parsing
  526. // scratch buffer used for base64 decoding (DecodeBytes in reuseBuf mode),
  527. // or reading doubleQuoted string (DecodeStringAsBytes, DecodeNaked)
  528. buf *[]byte
  529. }
  530. func (x jsonDecState) captureState() interface{} { return x }
  531. func (x *jsonDecState) restoreState(v interface{}) { *x = v.(jsonDecState) }
  532. type jsonDecDriver struct {
  533. noBuiltInTypes
  534. decDriverNoopNumberHelper
  535. h *JsonHandle
  536. jsonDecState
  537. // se interfaceExtWrapper
  538. // ---- cpu cache line boundary?
  539. d Decoder
  540. }
  541. func (d *jsonDecDriver) descBd() (s string) { panic("descBd unsupported") }
  542. func (d *jsonDecDriver) decoder() *Decoder {
  543. return &d.d
  544. }
  545. func (d *jsonDecDriver) ReadMapStart() int {
  546. d.advance()
  547. if d.tok == 'n' {
  548. d.readLit4Null(d.d.decRd.readn3())
  549. return containerLenNil
  550. }
  551. if d.tok != '{' {
  552. d.d.errorf("read map - expect char '%c' but got char '%c'", '{', d.tok)
  553. }
  554. d.tok = 0
  555. return containerLenUnknown
  556. }
  557. func (d *jsonDecDriver) ReadArrayStart() int {
  558. d.advance()
  559. if d.tok == 'n' {
  560. d.readLit4Null(d.d.decRd.readn3())
  561. return containerLenNil
  562. }
  563. if d.tok != '[' {
  564. d.d.errorf("read array - expect char '%c' but got char '%c'", '[', d.tok)
  565. }
  566. d.tok = 0
  567. return containerLenUnknown
  568. }
  569. func (d *jsonDecDriver) CheckBreak() bool {
  570. d.advance()
  571. return d.tok == '}' || d.tok == ']'
  572. }
  573. func (d *jsonDecDriver) ReadArrayElem() {
  574. const xc uint8 = ','
  575. if d.d.c != containerArrayStart {
  576. d.advance()
  577. if d.tok != xc {
  578. d.readDelimError(xc)
  579. }
  580. d.tok = 0
  581. }
  582. }
  583. func (d *jsonDecDriver) ReadArrayEnd() {
  584. const xc uint8 = ']'
  585. d.advance()
  586. if d.tok != xc {
  587. d.readDelimError(xc)
  588. }
  589. d.tok = 0
  590. }
  591. func (d *jsonDecDriver) ReadMapElemKey() {
  592. const xc uint8 = ','
  593. if d.d.c != containerMapStart {
  594. d.advance()
  595. if d.tok != xc {
  596. d.readDelimError(xc)
  597. }
  598. d.tok = 0
  599. }
  600. }
  601. func (d *jsonDecDriver) ReadMapElemValue() {
  602. const xc uint8 = ':'
  603. d.advance()
  604. if d.tok != xc {
  605. d.readDelimError(xc)
  606. }
  607. d.tok = 0
  608. }
  609. func (d *jsonDecDriver) ReadMapEnd() {
  610. const xc uint8 = '}'
  611. d.advance()
  612. if d.tok != xc {
  613. d.readDelimError(xc)
  614. }
  615. d.tok = 0
  616. }
  617. func (d *jsonDecDriver) readDelimError(xc uint8) {
  618. d.d.errorf("read json delimiter - expect char '%c' but got char '%c'", xc, d.tok)
  619. }
  620. // MARKER: readLit4XXX takes the readn(3|4) as a parameter so they can be inlined.
  621. // We pass the array directly to errorf, as passing slice pushes past inlining threshold,
  622. // and passing slice also might cause allocation of the bs array on the heap.
  623. func (d *jsonDecDriver) readLit4True(bs [4]byte) {
  624. // bs := d.d.decRd.readn3()
  625. d.tok = 0
  626. if jsonValidateSymbols && bs != [...]byte{0, 'r', 'u', 'e'} { // !Equal jsonLiteral4True
  627. // d.d.errorf("expecting %s: got %s", jsonLiteral4True, bs[:])
  628. d.d.errorf("expecting true: got t%s", bs)
  629. }
  630. }
  631. func (d *jsonDecDriver) readLit4False(bs [4]byte) {
  632. // bs := d.d.decRd.readn4()
  633. d.tok = 0
  634. if jsonValidateSymbols && bs != [4]byte{'a', 'l', 's', 'e'} { // !Equal jsonLiteral4False
  635. // d.d.errorf("expecting %s: got %s", jsonLiteral4False, bs)
  636. d.d.errorf("expecting false: got f%s", bs)
  637. }
  638. }
  639. func (d *jsonDecDriver) readLit4Null(bs [4]byte) {
  640. // bs := d.d.decRd.readn3() // readx(3)
  641. d.tok = 0
  642. if jsonValidateSymbols && bs != [...]byte{0, 'u', 'l', 'l'} { // !Equal jsonLiteral4Null
  643. // d.d.errorf("expecting %s: got %s", jsonLiteral4Null, bs[:])
  644. d.d.errorf("expecting null: got n%s", bs)
  645. }
  646. }
  647. func (d *jsonDecDriver) advance() {
  648. if d.tok == 0 {
  649. d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
  650. }
  651. }
  652. func (d *jsonDecDriver) nextValueBytes(v []byte) []byte {
  653. v, cursor := d.nextValueBytesR(v)
  654. decNextValueBytesHelper{d: &d.d}.bytesRdV(&v, cursor)
  655. return v
  656. }
  657. func (d *jsonDecDriver) nextValueBytesR(v0 []byte) (v []byte, cursor uint) {
  658. v = v0
  659. var h = decNextValueBytesHelper{d: &d.d}
  660. dr := &d.d.decRd
  661. consumeString := func() {
  662. TOP:
  663. bs := dr.jsonReadAsisChars()
  664. h.appendN(&v, bs...)
  665. if bs[len(bs)-1] != '"' {
  666. // last char is '\', so consume next one and try again
  667. h.append1(&v, dr.readn1())
  668. goto TOP
  669. }
  670. }
  671. d.advance() // ignore leading whitespace
  672. cursor = d.d.rb.c - 1 // cursor starts just before non-whitespace token
  673. switch d.tok {
  674. default:
  675. h.appendN(&v, dr.jsonReadNum()...)
  676. case 'n':
  677. d.readLit4Null(d.d.decRd.readn3())
  678. h.appendN(&v, jsonLiteralNull...)
  679. case 'f':
  680. d.readLit4False(d.d.decRd.readn4())
  681. h.appendN(&v, jsonLiteralFalse...)
  682. case 't':
  683. d.readLit4True(d.d.decRd.readn3())
  684. h.appendN(&v, jsonLiteralTrue...)
  685. case '"':
  686. h.append1(&v, '"')
  687. consumeString()
  688. case '{', '[':
  689. var elem struct{}
  690. var stack []struct{}
  691. stack = append(stack, elem)
  692. h.append1(&v, d.tok)
  693. for len(stack) != 0 {
  694. c := dr.readn1()
  695. h.append1(&v, c)
  696. switch c {
  697. case '"':
  698. consumeString()
  699. case '{', '[':
  700. stack = append(stack, elem)
  701. case '}', ']':
  702. stack = stack[:len(stack)-1]
  703. }
  704. }
  705. }
  706. d.tok = 0
  707. return
  708. }
  709. func (d *jsonDecDriver) TryNil() bool {
  710. d.advance()
  711. // we shouldn't try to see if quoted "null" was here, right?
  712. // only the plain string: `null` denotes a nil (ie not quotes)
  713. if d.tok == 'n' {
  714. d.readLit4Null(d.d.decRd.readn3())
  715. return true
  716. }
  717. return false
  718. }
  719. func (d *jsonDecDriver) DecodeBool() (v bool) {
  720. d.advance()
  721. if d.tok == 'n' {
  722. d.readLit4Null(d.d.decRd.readn3())
  723. return
  724. }
  725. fquot := d.d.c == containerMapKey && d.tok == '"'
  726. if fquot {
  727. d.tok = d.d.decRd.readn1()
  728. }
  729. switch d.tok {
  730. case 'f':
  731. d.readLit4False(d.d.decRd.readn4())
  732. // v = false
  733. case 't':
  734. d.readLit4True(d.d.decRd.readn3())
  735. v = true
  736. default:
  737. d.d.errorf("decode bool: got first char %c", d.tok)
  738. // v = false // "unreachable"
  739. }
  740. if fquot {
  741. d.d.decRd.readn1()
  742. }
  743. return
  744. }
  745. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  746. // read string, and pass the string into json.unmarshal
  747. d.advance()
  748. if d.tok == 'n' {
  749. d.readLit4Null(d.d.decRd.readn3())
  750. return
  751. }
  752. d.ensureReadingString()
  753. bs := d.readUnescapedString()
  754. t, err := time.Parse(time.RFC3339, stringView(bs))
  755. d.d.onerror(err)
  756. return
  757. }
  758. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  759. // check container type by checking the first char
  760. d.advance()
  761. // optimize this, so we don't do 4 checks but do one computation.
  762. // return jsonContainerSet[d.tok]
  763. // ContainerType is mostly called for Map and Array,
  764. // so this conditional is good enough (max 2 checks typically)
  765. if d.tok == '{' {
  766. return valueTypeMap
  767. } else if d.tok == '[' {
  768. return valueTypeArray
  769. } else if d.tok == 'n' {
  770. d.readLit4Null(d.d.decRd.readn3())
  771. return valueTypeNil
  772. } else if d.tok == '"' {
  773. return valueTypeString
  774. }
  775. return valueTypeUnset
  776. }
  777. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  778. d.advance()
  779. dr := &d.d.decRd
  780. if d.tok == '"' {
  781. bs = dr.readUntil('"')
  782. } else if d.tok == 'n' {
  783. d.readLit4Null(d.d.decRd.readn3())
  784. } else {
  785. if jsonManualInlineDecRdInHotZones {
  786. if dr.bytes {
  787. bs = dr.rb.jsonReadNum()
  788. } else if dr.bufio {
  789. bs = dr.bi.jsonReadNum()
  790. } else {
  791. bs = dr.ri.jsonReadNum()
  792. }
  793. } else {
  794. bs = dr.jsonReadNum()
  795. }
  796. }
  797. d.tok = 0
  798. return
  799. }
  800. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  801. b := d.decNumBytes()
  802. u, neg, ok := parseInteger_bytes(b)
  803. if neg {
  804. d.d.errorf("negative number cannot be decoded as uint64")
  805. }
  806. if !ok {
  807. d.d.onerror(strconvParseErr(b, "ParseUint"))
  808. }
  809. return
  810. }
  811. func (d *jsonDecDriver) DecodeInt64() (v int64) {
  812. b := d.decNumBytes()
  813. u, neg, ok := parseInteger_bytes(b)
  814. if !ok {
  815. d.d.onerror(strconvParseErr(b, "ParseInt"))
  816. }
  817. if chkOvf.Uint2Int(u, neg) {
  818. d.d.errorf("overflow decoding number from %s", b)
  819. }
  820. if neg {
  821. v = -int64(u)
  822. } else {
  823. v = int64(u)
  824. }
  825. return
  826. }
  827. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  828. var err error
  829. bs := d.decNumBytes()
  830. if len(bs) == 0 {
  831. return
  832. }
  833. f, err = parseFloat64(bs)
  834. d.d.onerror(err)
  835. return
  836. }
  837. func (d *jsonDecDriver) DecodeFloat32() (f float32) {
  838. var err error
  839. bs := d.decNumBytes()
  840. if len(bs) == 0 {
  841. return
  842. }
  843. f, err = parseFloat32(bs)
  844. d.d.onerror(err)
  845. return
  846. }
  847. func (d *jsonDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
  848. d.advance()
  849. if d.tok == 'n' {
  850. d.readLit4Null(d.d.decRd.readn3())
  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. d.d.decodeValue(baseRV(rv), d.h.fnNoExt(basetype))
  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.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
  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.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
  879. }
  880. d.tok = 0
  881. return bs
  882. }
  883. func (d *jsonDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
  884. d.d.decByteState = decByteStateNone
  885. d.advance()
  886. if d.tok == 'n' {
  887. d.readLit4Null(d.d.decRd.readn3())
  888. return nil
  889. }
  890. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  891. if d.rawext {
  892. bsOut = bs
  893. d.d.interfaceExtConvertAndDecode(&bsOut, d.h.RawBytesExt)
  894. return
  895. }
  896. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  897. if d.tok == '[' {
  898. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  899. if bs == nil {
  900. d.d.decByteState = decByteStateReuseBuf
  901. bs = d.d.b[:]
  902. }
  903. return d.decBytesFromArray(bs)
  904. }
  905. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  906. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  907. d.ensureReadingString()
  908. bs1 := d.readUnescapedString()
  909. slen := base64.StdEncoding.DecodedLen(len(bs1))
  910. if slen == 0 {
  911. bsOut = []byte{}
  912. } else if slen <= cap(bs) {
  913. bsOut = bs[:slen]
  914. } else if bs == nil {
  915. d.d.decByteState = decByteStateReuseBuf
  916. bsOut = d.d.blist.check(*d.buf, slen)[:slen]
  917. *d.buf = bsOut
  918. } else {
  919. bsOut = make([]byte, slen)
  920. }
  921. slen2, err := base64.StdEncoding.Decode(bsOut, bs1)
  922. if err != nil {
  923. d.d.errorf("error decoding base64 binary '%s': %v", bs1, err)
  924. }
  925. if slen != slen2 {
  926. bsOut = bsOut[:slen2]
  927. }
  928. return
  929. }
  930. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  931. d.d.decByteState = decByteStateNone
  932. d.advance()
  933. // common case
  934. if d.tok == '"' {
  935. return d.dblQuoteStringAsBytes()
  936. }
  937. // handle non-string scalar: null, true, false or a number
  938. switch d.tok {
  939. case 'n':
  940. d.readLit4Null(d.d.decRd.readn3())
  941. return nil // []byte{}
  942. case 'f':
  943. d.readLit4False(d.d.decRd.readn4())
  944. return jsonLiteralFalse
  945. case 't':
  946. d.readLit4True(d.d.decRd.readn3())
  947. return jsonLiteralTrue
  948. }
  949. // try to parse a valid number
  950. d.tok = 0
  951. return d.d.decRd.jsonReadNum()
  952. }
  953. func (d *jsonDecDriver) ensureReadingString() {
  954. if d.tok != '"' {
  955. d.d.errorf("expecting string starting with '\"'; got '%c'", d.tok)
  956. }
  957. }
  958. func (d *jsonDecDriver) readUnescapedString() (bs []byte) {
  959. // d.ensureReadingString()
  960. bs = d.d.decRd.readUntil('"')
  961. d.tok = 0
  962. return
  963. }
  964. func (d *jsonDecDriver) dblQuoteStringAsBytes() (buf []byte) {
  965. d.d.decByteState = decByteStateNone
  966. // use a local buf variable, so we don't do pointer chasing within loop
  967. buf = (*d.buf)[:0]
  968. dr := &d.d.decRd
  969. d.tok = 0
  970. var bs []byte
  971. var c byte
  972. var firstTime bool = true
  973. for {
  974. if firstTime {
  975. firstTime = false
  976. if dr.bytes {
  977. bs = dr.rb.jsonReadAsisChars()
  978. if bs[len(bs)-1] == '"' {
  979. d.d.decByteState = decByteStateZerocopy
  980. return bs[:len(bs)-1]
  981. }
  982. goto APPEND
  983. }
  984. }
  985. if jsonManualInlineDecRdInHotZones {
  986. if dr.bytes {
  987. bs = dr.rb.jsonReadAsisChars()
  988. } else if dr.bufio {
  989. bs = dr.bi.jsonReadAsisChars()
  990. } else {
  991. bs = dr.ri.jsonReadAsisChars()
  992. }
  993. } else {
  994. bs = dr.jsonReadAsisChars()
  995. }
  996. APPEND:
  997. buf = append(buf, bs[:len(bs)-1]...)
  998. c = bs[len(bs)-1]
  999. if c == '"' {
  1000. break
  1001. }
  1002. // c is now '\'
  1003. c = dr.readn1()
  1004. switch c {
  1005. case '"', '\\', '/', '\'':
  1006. buf = append(buf, c)
  1007. case 'b':
  1008. buf = append(buf, '\b')
  1009. case 'f':
  1010. buf = append(buf, '\f')
  1011. case 'n':
  1012. buf = append(buf, '\n')
  1013. case 'r':
  1014. buf = append(buf, '\r')
  1015. case 't':
  1016. buf = append(buf, '\t')
  1017. case 'u':
  1018. buf = append(buf, d.bstr[:utf8.EncodeRune(d.bstr[:], d.appendStringAsBytesSlashU())]...)
  1019. default:
  1020. *d.buf = buf
  1021. d.d.errorf("unsupported escaped value: %c", c)
  1022. }
  1023. }
  1024. *d.buf = buf
  1025. d.d.decByteState = decByteStateReuseBuf
  1026. return
  1027. }
  1028. func (d *jsonDecDriver) appendStringAsBytesSlashU() (r rune) {
  1029. var rr uint32
  1030. var csu [2]byte
  1031. var cs [4]byte = d.d.decRd.readn4()
  1032. if rr = jsonSlashURune(cs); rr == unicode.ReplacementChar {
  1033. return unicode.ReplacementChar
  1034. }
  1035. r = rune(rr)
  1036. if utf16.IsSurrogate(r) {
  1037. csu = d.d.decRd.readn2()
  1038. cs = d.d.decRd.readn4()
  1039. if csu[0] == '\\' && csu[1] == 'u' {
  1040. if rr = jsonSlashURune(cs); rr == unicode.ReplacementChar {
  1041. return unicode.ReplacementChar
  1042. }
  1043. return utf16.DecodeRune(r, rune(rr))
  1044. }
  1045. return unicode.ReplacementChar
  1046. }
  1047. return
  1048. }
  1049. func jsonSlashURune(cs [4]byte) (rr uint32) {
  1050. for _, c := range cs {
  1051. // best to use explicit if-else
  1052. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  1053. if c >= '0' && c <= '9' {
  1054. rr = rr*16 + uint32(c-jsonU4Chk2)
  1055. } else if c >= 'a' && c <= 'f' {
  1056. rr = rr*16 + uint32(c-jsonU4Chk1)
  1057. } else if c >= 'A' && c <= 'F' {
  1058. rr = rr*16 + uint32(c-jsonU4Chk0)
  1059. } else {
  1060. return unicode.ReplacementChar
  1061. }
  1062. }
  1063. return
  1064. }
  1065. func (d *jsonDecDriver) nakedNum(z *fauxUnion, bs []byte) (err error) {
  1066. // Note: nakedNum is NEVER called with a zero-length []byte
  1067. if d.h.PreferFloat {
  1068. z.v = valueTypeFloat
  1069. z.f, err = parseFloat64(bs)
  1070. } else {
  1071. err = parseNumber(bs, z, d.h.SignedInteger)
  1072. }
  1073. return
  1074. }
  1075. func (d *jsonDecDriver) DecodeNaked() {
  1076. z := d.d.naked()
  1077. d.advance()
  1078. var bs []byte
  1079. switch d.tok {
  1080. case 'n':
  1081. d.readLit4Null(d.d.decRd.readn3())
  1082. z.v = valueTypeNil
  1083. case 'f':
  1084. d.readLit4False(d.d.decRd.readn4())
  1085. z.v = valueTypeBool
  1086. z.b = false
  1087. case 't':
  1088. d.readLit4True(d.d.decRd.readn3())
  1089. z.v = valueTypeBool
  1090. z.b = true
  1091. case '{':
  1092. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  1093. case '[':
  1094. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  1095. case '"':
  1096. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  1097. bs = d.dblQuoteStringAsBytes()
  1098. if len(bs) > 0 && d.d.c == containerMapKey && d.h.MapKeyAsString {
  1099. if bytes.Equal(bs, jsonLiteralNull) {
  1100. z.v = valueTypeNil
  1101. } else if bytes.Equal(bs, jsonLiteralTrue) {
  1102. z.v = valueTypeBool
  1103. z.b = true
  1104. } else if bytes.Equal(bs, jsonLiteralFalse) {
  1105. z.v = valueTypeBool
  1106. z.b = false
  1107. } else {
  1108. // check if a number: float, int or uint
  1109. if err := d.nakedNum(z, bs); err != nil {
  1110. z.v = valueTypeString
  1111. z.s = d.d.stringZC(bs)
  1112. }
  1113. }
  1114. } else {
  1115. z.v = valueTypeString
  1116. z.s = d.d.stringZC(bs)
  1117. }
  1118. default: // number
  1119. bs = d.d.decRd.jsonReadNum()
  1120. d.tok = 0
  1121. if len(bs) == 0 {
  1122. d.d.errorf("decode number from empty string")
  1123. }
  1124. if err := d.nakedNum(z, bs); err != nil {
  1125. d.d.errorf("decode number from %s: %v", bs, err)
  1126. }
  1127. }
  1128. }
  1129. //----------------------
  1130. // JsonHandle is a handle for JSON encoding format.
  1131. //
  1132. // Json is comprehensively supported:
  1133. // - decodes numbers into interface{} as int, uint or float64
  1134. // based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
  1135. // - decode integers from float formatted numbers e.g. 1.27e+8
  1136. // - decode any json value (numbers, bool, etc) from quoted strings
  1137. // - configurable way to encode/decode []byte .
  1138. // by default, encodes and decodes []byte using base64 Std Encoding
  1139. // - UTF-8 support for encoding and decoding
  1140. //
  1141. // It has better performance than the json library in the standard library,
  1142. // by leveraging the performance improvements of the codec library.
  1143. //
  1144. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1145. // reading multiple values from a stream containing json and non-json content.
  1146. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1147. // all from the same stream in sequence.
  1148. //
  1149. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are
  1150. // not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
  1151. //
  1152. // Note also that the float values for NaN, +Inf or -Inf are encoded as null,
  1153. // as suggested by NOTE 4 of the ECMA-262 ECMAScript Language Specification 5.1 edition.
  1154. // see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf .
  1155. type JsonHandle struct {
  1156. textEncodingType
  1157. BasicHandle
  1158. // Indent indicates how a value is encoded.
  1159. // - If positive, indent by that number of spaces.
  1160. // - If negative, indent by that number of tabs.
  1161. Indent int8
  1162. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1163. //
  1164. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1165. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1166. // This can be mitigated by configuring how to encode integers.
  1167. //
  1168. // IntegerAsString interpretes the following values:
  1169. // - if 'L', then encode integers > 2^53 as a json string.
  1170. // - if 'A', then encode all integers as a json string
  1171. // containing the exact integer representation as a decimal.
  1172. // - else encode all integers as a json number (default)
  1173. IntegerAsString byte
  1174. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1175. //
  1176. // By default, we encode them as \uXXX
  1177. // to prevent security holes when served from some browsers.
  1178. HTMLCharsAsIs bool
  1179. // PreferFloat says that we will default to decoding a number as a float.
  1180. // If not set, we will examine the characters of the number and decode as an
  1181. // integer type if it doesn't have any of the characters [.eE].
  1182. PreferFloat bool
  1183. // TermWhitespace says that we add a whitespace character
  1184. // at the end of an encoding.
  1185. //
  1186. // The whitespace is important, especially if using numbers in a context
  1187. // where multiple items are written to a stream.
  1188. TermWhitespace bool
  1189. // MapKeyAsString says to encode all map keys as strings.
  1190. //
  1191. // Use this to enforce strict json output.
  1192. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1193. MapKeyAsString bool
  1194. // _ uint64 // padding (cache line)
  1195. // Note: below, we store hardly-used items e.g. RawBytesExt.
  1196. // These values below may straddle a cache line, but they are hardly-used,
  1197. // so shouldn't contribute to false-sharing except in rare cases.
  1198. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1199. // If not configured, raw bytes are encoded to/from base64 text.
  1200. RawBytesExt InterfaceExt
  1201. }
  1202. func (h *JsonHandle) isJson() bool { return true }
  1203. // Name returns the name of the handle: json
  1204. func (h *JsonHandle) Name() string { return "json" }
  1205. func (h *JsonHandle) desc(bd byte) string { return string(bd) }
  1206. func (h *JsonHandle) typical() bool {
  1207. return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L'
  1208. }
  1209. func (h *JsonHandle) newEncDriver() encDriver {
  1210. var e = &jsonEncDriver{h: h}
  1211. // var x []byte
  1212. // e.buf = &x
  1213. e.e.e = e
  1214. e.e.js = true
  1215. e.e.init(h)
  1216. e.reset()
  1217. return e
  1218. }
  1219. func (h *JsonHandle) newDecDriver() decDriver {
  1220. var d = &jsonDecDriver{h: h}
  1221. var x []byte
  1222. d.buf = &x
  1223. d.d.d = d
  1224. d.d.js = true
  1225. d.d.jsms = h.MapKeyAsString
  1226. d.d.init(h)
  1227. d.reset()
  1228. return d
  1229. }
  1230. func (e *jsonEncDriver) resetState() {
  1231. e.dl = 0
  1232. }
  1233. func (e *jsonEncDriver) reset() {
  1234. e.resetState()
  1235. // (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b)
  1236. // cache values from the handle
  1237. e.typical = e.h.typical()
  1238. if e.h.HTMLCharsAsIs {
  1239. e.s = &jsonCharSafeSet
  1240. } else {
  1241. e.s = &jsonCharHtmlSafeSet
  1242. }
  1243. e.rawext = e.h.RawBytesExt != nil
  1244. e.di = int8(e.h.Indent)
  1245. e.d = e.h.Indent != 0
  1246. e.ks = e.h.MapKeyAsString
  1247. e.is = e.h.IntegerAsString
  1248. }
  1249. func (d *jsonDecDriver) resetState() {
  1250. *d.buf = d.d.blist.check(*d.buf, 256)
  1251. d.tok = 0
  1252. }
  1253. func (d *jsonDecDriver) reset() {
  1254. d.resetState()
  1255. d.rawext = d.h.RawBytesExt != nil
  1256. }
  1257. func jsonFloatStrconvFmtPrec64(f float64) (fmt byte, prec int8) {
  1258. fmt = 'f'
  1259. prec = -1
  1260. fbits := math.Float64bits(f)
  1261. abs := math.Float64frombits(fbits &^ (1 << 63))
  1262. if abs == 0 || abs == 1 {
  1263. prec = 1
  1264. } else if abs < 1e-6 || abs >= 1e21 {
  1265. fmt = 'e'
  1266. } else if noFrac64(fbits) {
  1267. prec = 1
  1268. }
  1269. return
  1270. }
  1271. func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) {
  1272. fmt = 'f'
  1273. prec = -1
  1274. // directly handle Modf (to get fractions) and Abs (to get absolute)
  1275. fbits := math.Float32bits(f)
  1276. abs := math.Float32frombits(fbits &^ (1 << 31))
  1277. if abs == 0 || abs == 1 {
  1278. prec = 1
  1279. } else if abs < 1e-6 || abs >= 1e21 {
  1280. fmt = 'e'
  1281. } else if noFrac32(fbits) {
  1282. prec = 1
  1283. }
  1284. return
  1285. }
  1286. var _ decDriverContainerTracker = (*jsonDecDriver)(nil)
  1287. var _ encDriverContainerTracker = (*jsonEncDriver)(nil)
  1288. var _ decDriver = (*jsonDecDriver)(nil)
  1289. var _ encDriver = (*jsonEncDriver)(nil)