json.go 34 KB

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