json.go 36 KB

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