json.go 36 KB

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