json.go 36 KB

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