json.go 38 KB

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