http urls monitor.

json.go 34KB

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. bs := d.r.readx(int(length))
  631. d.tok = 0
  632. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  633. d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  634. return
  635. }
  636. }
  637. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  638. if d.tok == 0 {
  639. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  640. }
  641. // we shouldn't try to see if "null" was here, right?
  642. // only the plain string: `null` denotes a nil (ie not quotes)
  643. if d.tok == 'n' {
  644. d.readLit(3, jsonLitNull+1) // (n)ull
  645. return true
  646. }
  647. return false
  648. }
  649. func (d *jsonDecDriver) DecodeBool() (v bool) {
  650. if d.tok == 0 {
  651. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  652. }
  653. fquot := d.c == containerMapKey && d.tok == '"'
  654. if fquot {
  655. d.tok = d.r.readn1()
  656. }
  657. switch d.tok {
  658. case 'f':
  659. d.readLit(4, jsonLitFalse+1) // (f)alse
  660. // v = false
  661. case 't':
  662. d.readLit(3, jsonLitTrue+1) // (t)rue
  663. v = true
  664. default:
  665. d.d.errorf("decode bool: got first char %c", d.tok)
  666. // v = false // "unreachable"
  667. }
  668. if fquot {
  669. d.r.readn1()
  670. }
  671. return
  672. }
  673. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  674. // read string, and pass the string into json.unmarshal
  675. d.appendStringAsBytes()
  676. if d.fnull {
  677. return
  678. }
  679. t, err := time.Parse(time.RFC3339, stringView(d.bs))
  680. if err != nil {
  681. d.d.errorv(err)
  682. }
  683. return
  684. }
  685. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  686. // check container type by checking the first char
  687. if d.tok == 0 {
  688. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  689. }
  690. // optimize this, so we don't do 4 checks but do one computation.
  691. // return jsonContainerSet[d.tok]
  692. // ContainerType is mostly called for Map and Array,
  693. // so this conditional is good enough (max 2 checks typically)
  694. if b := d.tok; b == '{' {
  695. return valueTypeMap
  696. } else if b == '[' {
  697. return valueTypeArray
  698. } else if b == 'n' {
  699. return valueTypeNil
  700. } else if b == '"' {
  701. return valueTypeString
  702. }
  703. return valueTypeUnset
  704. }
  705. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  706. // stores num bytes in d.bs
  707. if d.tok == 0 {
  708. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  709. }
  710. if d.tok == '"' {
  711. bs = d.r.readUntil(d.b2[:0], '"')
  712. bs = bs[:len(bs)-1]
  713. } else {
  714. d.r.unreadn1()
  715. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  716. }
  717. d.tok = 0
  718. return bs
  719. }
  720. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  721. bs := d.decNumBytes()
  722. if len(bs) == 0 {
  723. return
  724. }
  725. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  726. if overflow {
  727. d.d.errorf("overflow parsing unsigned integer: %s", bs)
  728. } else if neg {
  729. d.d.errorf("minus found parsing unsigned integer: %s", bs)
  730. } else if badsyntax {
  731. // fallback: try to decode as float, and cast
  732. n = d.decUint64ViaFloat(stringView(bs))
  733. }
  734. return n
  735. }
  736. func (d *jsonDecDriver) DecodeInt64() (i int64) {
  737. const cutoff = uint64(1 << uint(64-1))
  738. bs := d.decNumBytes()
  739. if len(bs) == 0 {
  740. return
  741. }
  742. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  743. if overflow {
  744. d.d.errorf("overflow parsing integer: %s", bs)
  745. } else if badsyntax {
  746. // d.d.errorf("invalid syntax for integer: %s", bs)
  747. // fallback: try to decode as float, and cast
  748. if neg {
  749. n = d.decUint64ViaFloat(stringView(bs[1:]))
  750. } else {
  751. n = d.decUint64ViaFloat(stringView(bs))
  752. }
  753. }
  754. if neg {
  755. if n > cutoff {
  756. d.d.errorf("overflow parsing integer: %s", bs)
  757. }
  758. i = -(int64(n))
  759. } else {
  760. if n >= cutoff {
  761. d.d.errorf("overflow parsing integer: %s", bs)
  762. }
  763. i = int64(n)
  764. }
  765. return
  766. }
  767. func (d *jsonDecDriver) decUint64ViaFloat(s string) (u uint64) {
  768. if len(s) == 0 {
  769. return
  770. }
  771. f, err := strconv.ParseFloat(s, 64)
  772. if err != nil {
  773. d.d.errorf("invalid syntax for integer: %s", s)
  774. // d.d.errorv(err)
  775. }
  776. fi, ff := math.Modf(f)
  777. if ff > 0 {
  778. d.d.errorf("fractional part found parsing integer: %s", s)
  779. } else if fi > float64(math.MaxUint64) {
  780. d.d.errorf("overflow parsing integer: %s", s)
  781. }
  782. return uint64(fi)
  783. }
  784. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  785. bs := d.decNumBytes()
  786. if len(bs) == 0 {
  787. return
  788. }
  789. f, err := strconv.ParseFloat(stringView(bs), 64)
  790. if err != nil {
  791. d.d.errorv(err)
  792. }
  793. return
  794. }
  795. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  796. if ext == nil {
  797. re := rv.(*RawExt)
  798. re.Tag = xtag
  799. d.d.decode(&re.Value)
  800. } else {
  801. var v interface{}
  802. d.d.decode(&v)
  803. ext.UpdateExt(rv, v)
  804. }
  805. return
  806. }
  807. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  808. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  809. if d.se.InterfaceExt != nil {
  810. bsOut = bs
  811. d.DecodeExt(&bsOut, 0, &d.se)
  812. return
  813. }
  814. if d.tok == 0 {
  815. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  816. }
  817. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  818. if d.tok == '[' {
  819. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  820. return
  821. }
  822. d.appendStringAsBytes()
  823. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  824. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  825. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  826. // However, it sets a fnull field to true, so we can check if a null was found.
  827. if len(d.bs) == 0 {
  828. if d.fnull {
  829. return nil
  830. }
  831. return []byte{}
  832. }
  833. bs0 := d.bs
  834. slen := base64.StdEncoding.DecodedLen(len(bs0))
  835. if slen <= cap(bs) {
  836. bsOut = bs[:slen]
  837. } else if zerocopy && slen <= cap(d.b2) {
  838. bsOut = d.b2[:slen]
  839. } else {
  840. bsOut = make([]byte, slen)
  841. }
  842. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  843. if err != nil {
  844. d.d.errorf("error decoding base64 binary '%s': %v", bs0, err)
  845. return nil
  846. }
  847. if slen != slen2 {
  848. bsOut = bsOut[:slen2]
  849. }
  850. return
  851. }
  852. func (d *jsonDecDriver) DecodeString() (s string) {
  853. d.appendStringAsBytes()
  854. return d.bsToString()
  855. }
  856. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  857. d.appendStringAsBytes()
  858. return d.bs
  859. }
  860. func (d *jsonDecDriver) appendStringAsBytes() {
  861. if d.tok == 0 {
  862. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  863. }
  864. d.fnull = false
  865. if d.tok != '"' {
  866. // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
  867. // handle non-string scalar: null, true, false or a number
  868. switch d.tok {
  869. case 'n':
  870. d.readLit(3, jsonLitNull+1) // (n)ull
  871. d.bs = d.bs[:0]
  872. d.fnull = true
  873. case 'f':
  874. d.readLit(4, jsonLitFalse+1) // (f)alse
  875. d.bs = d.bs[:5]
  876. copy(d.bs, "false")
  877. case 't':
  878. d.readLit(3, jsonLitTrue+1) // (t)rue
  879. d.bs = d.bs[:4]
  880. copy(d.bs, "true")
  881. default:
  882. // try to parse a valid number
  883. bs := d.decNumBytes()
  884. if len(bs) <= cap(d.bs) {
  885. d.bs = d.bs[:len(bs)]
  886. } else {
  887. d.bs = make([]byte, len(bs))
  888. }
  889. copy(d.bs, bs)
  890. }
  891. return
  892. }
  893. d.tok = 0
  894. r := d.r
  895. var cs = r.readUntil(d.b2[:0], '"')
  896. var cslen = len(cs)
  897. var c uint8
  898. v := d.bs[:0]
  899. // append on each byte seen can be expensive, so we just
  900. // keep track of where we last read a contiguous set of
  901. // non-special bytes (using cursor variable),
  902. // and when we see a special byte
  903. // e.g. end-of-slice, " or \,
  904. // we will append the full range into the v slice before proceeding
  905. for i, cursor := 0, 0; ; {
  906. if i == cslen {
  907. v = append(v, cs[cursor:]...)
  908. cs = r.readUntil(d.b2[:0], '"')
  909. cslen = len(cs)
  910. i, cursor = 0, 0
  911. }
  912. c = cs[i]
  913. if c == '"' {
  914. v = append(v, cs[cursor:i]...)
  915. break
  916. }
  917. if c != '\\' {
  918. i++
  919. continue
  920. }
  921. v = append(v, cs[cursor:i]...)
  922. i++
  923. c = cs[i]
  924. switch c {
  925. case '"', '\\', '/', '\'':
  926. v = append(v, c)
  927. case 'b':
  928. v = append(v, '\b')
  929. case 'f':
  930. v = append(v, '\f')
  931. case 'n':
  932. v = append(v, '\n')
  933. case 'r':
  934. v = append(v, '\r')
  935. case 't':
  936. v = append(v, '\t')
  937. case 'u':
  938. var r rune
  939. var rr uint32
  940. if len(cs) < i+4 { // may help reduce bounds-checking
  941. d.d.errorf("need at least 4 more bytes for unicode sequence")
  942. }
  943. // c = cs[i+4] // may help reduce bounds-checking
  944. for j := 1; j < 5; j++ {
  945. // best to use explicit if-else
  946. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  947. c = cs[i+j]
  948. if c >= '0' && c <= '9' {
  949. rr = rr*16 + uint32(c-jsonU4Chk2)
  950. } else if c >= 'a' && c <= 'f' {
  951. rr = rr*16 + uint32(c-jsonU4Chk1)
  952. } else if c >= 'A' && c <= 'F' {
  953. rr = rr*16 + uint32(c-jsonU4Chk0)
  954. } else {
  955. r = unicode.ReplacementChar
  956. i += 4
  957. goto encode_rune
  958. }
  959. }
  960. r = rune(rr)
  961. i += 4
  962. if utf16.IsSurrogate(r) {
  963. if len(cs) >= i+6 && cs[i+2] == 'u' && cs[i+1] == '\\' {
  964. i += 2
  965. // c = cs[i+4] // may help reduce bounds-checking
  966. var rr1 uint32
  967. for j := 1; j < 5; j++ {
  968. c = cs[i+j]
  969. if c >= '0' && c <= '9' {
  970. rr = rr*16 + uint32(c-jsonU4Chk2)
  971. } else if c >= 'a' && c <= 'f' {
  972. rr = rr*16 + uint32(c-jsonU4Chk1)
  973. } else if c >= 'A' && c <= 'F' {
  974. rr = rr*16 + uint32(c-jsonU4Chk0)
  975. } else {
  976. r = unicode.ReplacementChar
  977. i += 4
  978. goto encode_rune
  979. }
  980. }
  981. r = utf16.DecodeRune(r, rune(rr1))
  982. i += 4
  983. } else {
  984. r = unicode.ReplacementChar
  985. goto encode_rune
  986. }
  987. }
  988. encode_rune:
  989. w2 := utf8.EncodeRune(d.bstr[:], r)
  990. v = append(v, d.bstr[:w2]...)
  991. default:
  992. d.d.errorf("unsupported escaped value: %c", c)
  993. }
  994. i++
  995. cursor = i
  996. }
  997. d.bs = v
  998. }
  999. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  1000. const cutoff = uint64(1 << uint(64-1))
  1001. var n uint64
  1002. var neg, badsyntax, overflow bool
  1003. if len(bs) == 0 {
  1004. if d.h.PreferFloat {
  1005. z.v = valueTypeFloat
  1006. z.f = 0
  1007. } else if d.h.SignedInteger {
  1008. z.v = valueTypeInt
  1009. z.i = 0
  1010. } else {
  1011. z.v = valueTypeUint
  1012. z.u = 0
  1013. }
  1014. return
  1015. }
  1016. if d.h.PreferFloat {
  1017. goto F
  1018. }
  1019. n, neg, badsyntax, overflow = jsonParseInteger(bs)
  1020. if badsyntax || overflow {
  1021. goto F
  1022. }
  1023. if neg {
  1024. if n > cutoff {
  1025. goto F
  1026. }
  1027. z.v = valueTypeInt
  1028. z.i = -(int64(n))
  1029. } else if d.h.SignedInteger {
  1030. if n >= cutoff {
  1031. goto F
  1032. }
  1033. z.v = valueTypeInt
  1034. z.i = int64(n)
  1035. } else {
  1036. z.v = valueTypeUint
  1037. z.u = n
  1038. }
  1039. return
  1040. F:
  1041. z.v = valueTypeFloat
  1042. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  1043. return
  1044. }
  1045. func (d *jsonDecDriver) bsToString() string {
  1046. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  1047. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  1048. return d.d.string(d.bs)
  1049. }
  1050. return string(d.bs)
  1051. }
  1052. func (d *jsonDecDriver) DecodeNaked() {
  1053. z := d.d.n
  1054. // var decodeFurther bool
  1055. if d.tok == 0 {
  1056. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  1057. }
  1058. switch d.tok {
  1059. case 'n':
  1060. d.readLit(3, jsonLitNull+1) // (n)ull
  1061. z.v = valueTypeNil
  1062. case 'f':
  1063. d.readLit(4, jsonLitFalse+1) // (f)alse
  1064. z.v = valueTypeBool
  1065. z.b = false
  1066. case 't':
  1067. d.readLit(3, jsonLitTrue+1) // (t)rue
  1068. z.v = valueTypeBool
  1069. z.b = true
  1070. case '{':
  1071. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  1072. case '[':
  1073. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  1074. case '"':
  1075. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  1076. d.appendStringAsBytes()
  1077. if len(d.bs) > 0 && d.c == containerMapKey && d.h.MapKeyAsString {
  1078. switch stringView(d.bs) {
  1079. case "null":
  1080. z.v = valueTypeNil
  1081. case "true":
  1082. z.v = valueTypeBool
  1083. z.b = true
  1084. case "false":
  1085. z.v = valueTypeBool
  1086. z.b = false
  1087. default:
  1088. // check if a number: float, int or uint
  1089. if err := d.nakedNum(z, d.bs); err != nil {
  1090. z.v = valueTypeString
  1091. z.s = d.bsToString()
  1092. }
  1093. }
  1094. } else {
  1095. z.v = valueTypeString
  1096. z.s = d.bsToString()
  1097. }
  1098. default: // number
  1099. bs := d.decNumBytes()
  1100. if len(bs) == 0 {
  1101. d.d.errorf("decode number from empty string")
  1102. return
  1103. }
  1104. if err := d.nakedNum(z, bs); err != nil {
  1105. d.d.errorf("decode number from %s: %v", bs, err)
  1106. return
  1107. }
  1108. }
  1109. // if decodeFurther {
  1110. // d.s.sc.retryRead()
  1111. // }
  1112. return
  1113. }
  1114. //----------------------
  1115. // JsonHandle is a handle for JSON encoding format.
  1116. //
  1117. // Json is comprehensively supported:
  1118. // - decodes numbers into interface{} as int, uint or float64
  1119. // based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
  1120. // - decode integers from float formatted numbers e.g. 1.27e+8
  1121. // - decode any json value (numbers, bool, etc) from quoted strings
  1122. // - configurable way to encode/decode []byte .
  1123. // by default, encodes and decodes []byte using base64 Std Encoding
  1124. // - UTF-8 support for encoding and decoding
  1125. //
  1126. // It has better performance than the json library in the standard library,
  1127. // by leveraging the performance improvements of the codec library.
  1128. //
  1129. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1130. // reading multiple values from a stream containing json and non-json content.
  1131. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1132. // all from the same stream in sequence.
  1133. //
  1134. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are
  1135. // not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
  1136. type JsonHandle struct {
  1137. textEncodingType
  1138. BasicHandle
  1139. // Indent indicates how a value is encoded.
  1140. // - If positive, indent by that number of spaces.
  1141. // - If negative, indent by that number of tabs.
  1142. Indent int8
  1143. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1144. //
  1145. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1146. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1147. // This can be mitigated by configuring how to encode integers.
  1148. //
  1149. // IntegerAsString interpretes the following values:
  1150. // - if 'L', then encode integers > 2^53 as a json string.
  1151. // - if 'A', then encode all integers as a json string
  1152. // containing the exact integer representation as a decimal.
  1153. // - else encode all integers as a json number (default)
  1154. IntegerAsString byte
  1155. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1156. //
  1157. // By default, we encode them as \uXXX
  1158. // to prevent security holes when served from some browsers.
  1159. HTMLCharsAsIs bool
  1160. // PreferFloat says that we will default to decoding a number as a float.
  1161. // If not set, we will examine the characters of the number and decode as an
  1162. // integer type if it doesn't have any of the characters [.eE].
  1163. PreferFloat bool
  1164. // TermWhitespace says that we add a whitespace character
  1165. // at the end of an encoding.
  1166. //
  1167. // The whitespace is important, especially if using numbers in a context
  1168. // where multiple items are written to a stream.
  1169. TermWhitespace bool
  1170. // MapKeyAsString says to encode all map keys as strings.
  1171. //
  1172. // Use this to enforce strict json output.
  1173. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1174. MapKeyAsString bool
  1175. // _ [2]byte // padding
  1176. // Note: below, we store hardly-used items e.g. RawBytesExt is cached in the (en|de)cDriver.
  1177. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1178. // If not configured, raw bytes are encoded to/from base64 text.
  1179. RawBytesExt InterfaceExt
  1180. _ [2]uint64 // padding
  1181. }
  1182. // Name returns the name of the handle: json
  1183. func (h *JsonHandle) Name() string { return "json" }
  1184. func (h *JsonHandle) hasElemSeparators() bool { return true }
  1185. func (h *JsonHandle) typical() bool {
  1186. return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L'
  1187. }
  1188. type jsonTypical interface {
  1189. typical()
  1190. }
  1191. func (h *JsonHandle) recreateEncDriver(ed encDriver) (v bool) {
  1192. _, v = ed.(jsonTypical)
  1193. return v != h.typical()
  1194. }
  1195. // SetInterfaceExt sets an extension
  1196. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1197. return h.SetExt(rt, tag, &extWrapper{bytesExtFailer{}, ext})
  1198. }
  1199. type jsonEncDriverTypicalImpl struct {
  1200. jsonEncDriver
  1201. jsonEncDriverTypical
  1202. _ [3]uint64 // padding
  1203. }
  1204. func (x *jsonEncDriverTypicalImpl) reset() {
  1205. x.jsonEncDriver.reset()
  1206. x.jsonEncDriverTypical.reset(&x.jsonEncDriver)
  1207. }
  1208. type jsonEncDriverGenericImpl struct {
  1209. jsonEncDriver
  1210. jsonEncDriverGeneric
  1211. _ [2]uint64 // padding
  1212. }
  1213. func (x *jsonEncDriverGenericImpl) reset() {
  1214. x.jsonEncDriver.reset()
  1215. x.jsonEncDriverGeneric.reset(&x.jsonEncDriver)
  1216. }
  1217. func (h *JsonHandle) newEncDriver(e *Encoder) (ee encDriver) {
  1218. var hd *jsonEncDriver
  1219. if h.typical() {
  1220. var v jsonEncDriverTypicalImpl
  1221. ee = &v
  1222. hd = &v.jsonEncDriver
  1223. } else {
  1224. var v jsonEncDriverGenericImpl
  1225. ee = &v
  1226. hd = &v.jsonEncDriver
  1227. }
  1228. hd.e, hd.h, hd.bs = e, h, hd.b[:0]
  1229. hd.se.BytesExt = bytesExtFailer{}
  1230. ee.reset()
  1231. return
  1232. }
  1233. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1234. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1235. hd := jsonDecDriver{d: d, h: h}
  1236. hd.se.BytesExt = bytesExtFailer{}
  1237. hd.bs = hd.b[:0]
  1238. hd.reset()
  1239. return &hd
  1240. }
  1241. func (e *jsonEncDriver) reset() {
  1242. e.ew = e.e.w
  1243. e.se.InterfaceExt = e.h.RawBytesExt
  1244. if e.bs != nil {
  1245. e.bs = e.bs[:0]
  1246. }
  1247. }
  1248. func (d *jsonDecDriver) reset() {
  1249. d.r = d.d.r
  1250. d.se.InterfaceExt = d.h.RawBytesExt
  1251. if d.bs != nil {
  1252. d.bs = d.bs[:0]
  1253. }
  1254. d.c, d.tok = 0, 0
  1255. // d.n.reset()
  1256. }
  1257. func jsonFloatStrconvFmtPrec(f float64) (fmt byte, prec int) {
  1258. prec = -1
  1259. var abs = math.Abs(f)
  1260. if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
  1261. fmt = 'e'
  1262. } else {
  1263. fmt = 'f'
  1264. // set prec to 1 iff mod is 0.
  1265. // better than using jsonIsFloatBytesB2 to check if a . or E in the float bytes.
  1266. // this ensures that every float has an e or .0 in it.
  1267. if abs <= 1 {
  1268. if abs == 0 || abs == 1 {
  1269. prec = 1
  1270. }
  1271. } else if _, mod := math.Modf(abs); mod == 0 {
  1272. prec = 1
  1273. }
  1274. }
  1275. return
  1276. }
  1277. // custom-fitted version of strconv.Parse(Ui|I)nt.
  1278. // Also ensures we don't have to search for .eE to determine if a float or not.
  1279. // Note: s CANNOT be a zero-length slice.
  1280. func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) {
  1281. const maxUint64 = (1<<64 - 1)
  1282. const cutoff = maxUint64/10 + 1
  1283. // if len(s) == 0 {
  1284. // // treat empty string as zero value
  1285. // // badSyntax = true
  1286. // return
  1287. // }
  1288. switch s[0] {
  1289. case '+':
  1290. s = s[1:]
  1291. case '-':
  1292. s = s[1:]
  1293. neg = true
  1294. }
  1295. for _, c := range s {
  1296. if c < '0' || c > '9' {
  1297. badSyntax = true
  1298. return
  1299. }
  1300. // unsigned integers don't overflow well on multiplication, so check cutoff here
  1301. // e.g. (maxUint64-5)*10 doesn't overflow well ...
  1302. if n >= cutoff {
  1303. overflow = true
  1304. return
  1305. }
  1306. n *= 10
  1307. n1 := n + uint64(c-'0')
  1308. if n1 < n || n1 > maxUint64 {
  1309. overflow = true
  1310. return
  1311. }
  1312. n = n1
  1313. }
  1314. return
  1315. }
  1316. var _ decDriver = (*jsonDecDriver)(nil)
  1317. var _ encDriver = (*jsonEncDriverGenericImpl)(nil)
  1318. var _ encDriver = (*jsonEncDriverTypicalImpl)(nil)
  1319. var _ jsonTypical = (*jsonEncDriverTypical)(nil)