json.go 35 KB

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