json.go 35 KB

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