json.go 34 KB

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