json.go 34 KB

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