json.go 33 KB

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