json.go 37 KB

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