json.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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. fnull bool // found null from appendStringAsBytes
  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. if d.tok == 0 {
  547. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  548. }
  549. const xc uint8 = '{'
  550. if d.tok != xc {
  551. d.d.errorf("read map - expect char '%c' but got char '%c'", xc, d.tok)
  552. }
  553. d.tok = 0
  554. return -1
  555. }
  556. func (d *jsonDecDriver) ReadArrayStart() int {
  557. if d.tok == 0 {
  558. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  559. }
  560. const xc uint8 = '['
  561. if d.tok != xc {
  562. d.d.errorf("read array - expect char '%c' but got char '%c'", xc, d.tok)
  563. }
  564. d.tok = 0
  565. return -1
  566. }
  567. func (d *jsonDecDriver) CheckBreak() bool {
  568. if d.tok == 0 {
  569. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  570. }
  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. if d.tok == 0 {
  585. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  586. }
  587. if d.d.c != containerArrayStart {
  588. if d.tok != xc {
  589. d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok)
  590. }
  591. d.tok = 0
  592. }
  593. }
  594. func (d *jsonDecDriver) ReadArrayEnd() {
  595. const xc uint8 = ']'
  596. if d.tok == 0 {
  597. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  598. }
  599. if d.tok != xc {
  600. d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok)
  601. }
  602. d.tok = 0
  603. }
  604. func (d *jsonDecDriver) ReadMapElemKey() {
  605. const xc uint8 = ','
  606. if d.tok == 0 {
  607. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  608. }
  609. if d.d.c != containerMapStart {
  610. if d.tok != xc {
  611. d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok)
  612. }
  613. d.tok = 0
  614. }
  615. }
  616. func (d *jsonDecDriver) ReadMapElemValue() {
  617. const xc uint8 = ':'
  618. if d.tok == 0 {
  619. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  620. }
  621. if d.tok != xc {
  622. d.d.errorf("read map value - expect char '%c' but got char '%c'", xc, d.tok)
  623. }
  624. d.tok = 0
  625. }
  626. func (d *jsonDecDriver) ReadMapEnd() {
  627. const xc uint8 = '}'
  628. if d.tok == 0 {
  629. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  630. }
  631. if d.tok != xc {
  632. d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok)
  633. }
  634. d.tok = 0
  635. }
  636. // func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
  637. // // length here is always less than 8 (literals are: null, true, false)
  638. // bs := d.r.readx(int(length))
  639. // d.tok = 0
  640. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  641. // d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  642. // }
  643. // }
  644. func (d *jsonDecDriver) readLit4True() {
  645. bs := d.r.readx(3)
  646. d.tok = 0
  647. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4True) {
  648. d.d.errorf("expecting %s: got %s", jsonLiteral4True, bs)
  649. }
  650. }
  651. func (d *jsonDecDriver) readLit4False() {
  652. bs := d.r.readx(4)
  653. d.tok = 0
  654. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4False) {
  655. d.d.errorf("expecting %s: got %s", jsonLiteral4False, bs)
  656. }
  657. }
  658. func (d *jsonDecDriver) readLit4Null() {
  659. bs := d.r.readx(3)
  660. d.tok = 0
  661. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiteral4Null) {
  662. d.d.errorf("expecting %s: got %s", jsonLiteral4Null, bs)
  663. }
  664. }
  665. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  666. if d.tok == 0 {
  667. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  668. }
  669. // we shouldn't try to see if "null" was here, right?
  670. // only the plain string: `null` denotes a nil (ie not quotes)
  671. if d.tok == 'n' {
  672. d.readLit4Null()
  673. return true
  674. }
  675. return false
  676. }
  677. func (d *jsonDecDriver) DecodeBool() (v bool) {
  678. if d.tok == 0 {
  679. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  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.fnull {
  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. if d.tok == 0 {
  716. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  717. }
  718. // optimize this, so we don't do 4 checks but do one computation.
  719. // return jsonContainerSet[d.tok]
  720. // ContainerType is mostly called for Map and Array,
  721. // so this conditional is good enough (max 2 checks typically)
  722. if b := d.tok; b == '{' {
  723. return valueTypeMap
  724. } else if b == '[' {
  725. return valueTypeArray
  726. } else if b == 'n' {
  727. return valueTypeNil
  728. } else if b == '"' {
  729. return valueTypeString
  730. }
  731. return valueTypeUnset
  732. }
  733. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  734. // stores num bytes in d.bs
  735. if d.tok == 0 {
  736. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  737. }
  738. if d.tok == '"' {
  739. bs = d.r.readUntil(d.b2[:0], '"')
  740. bs = bs[:len(bs)-1]
  741. } else {
  742. d.r.unreadn1()
  743. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  744. }
  745. d.tok = 0
  746. return bs
  747. }
  748. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  749. bs := d.decNumBytes()
  750. if len(bs) == 0 {
  751. return
  752. }
  753. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  754. if overflow {
  755. d.d.errorf("overflow parsing unsigned integer: %s", bs)
  756. } else if neg {
  757. d.d.errorf("minus found parsing unsigned integer: %s", bs)
  758. } else if badsyntax {
  759. // fallback: try to decode as float, and cast
  760. n = d.decUint64ViaFloat(bs)
  761. }
  762. return n
  763. }
  764. func (d *jsonDecDriver) DecodeInt64() (i int64) {
  765. const cutoff = uint64(1 << uint(64-1))
  766. bs := d.decNumBytes()
  767. if len(bs) == 0 {
  768. return
  769. }
  770. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  771. if overflow {
  772. d.d.errorf("overflow parsing integer: %s", bs)
  773. } else if badsyntax {
  774. // d.d.errorf("invalid syntax for integer: %s", bs)
  775. // fallback: try to decode as float, and cast
  776. if neg {
  777. n = d.decUint64ViaFloat(bs[1:])
  778. } else {
  779. n = d.decUint64ViaFloat(bs)
  780. }
  781. }
  782. if neg {
  783. if n > cutoff {
  784. d.d.errorf("overflow parsing integer: %s", bs)
  785. }
  786. i = -(int64(n))
  787. } else {
  788. if n >= cutoff {
  789. d.d.errorf("overflow parsing integer: %s", bs)
  790. }
  791. i = int64(n)
  792. }
  793. return
  794. }
  795. func (d *jsonDecDriver) decUint64ViaFloat(s []byte) (u uint64) {
  796. if len(s) == 0 {
  797. return
  798. }
  799. f, err := parseFloat64(s)
  800. if err != nil {
  801. d.d.errorf("invalid syntax for integer: %s", s)
  802. // d.d.errorv(err)
  803. }
  804. fi, ff := math.Modf(f)
  805. if ff > 0 {
  806. d.d.errorf("fractional part found parsing integer: %s", s)
  807. } else if fi > float64(math.MaxUint64) {
  808. d.d.errorf("overflow parsing integer: %s", s)
  809. }
  810. return uint64(fi)
  811. }
  812. // func (d *jsonDecDriver) decodeFloat(bitsize int) (f float64) {
  813. // bs := d.decNumBytes()
  814. // if len(bs) == 0 {
  815. // return
  816. // }
  817. // f, err := parseFloat(bs, bitsize)
  818. // if err != nil {
  819. // d.d.errorv(err)
  820. // }
  821. // return
  822. // }
  823. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  824. // return d.decodeFloat(64)
  825. var err error
  826. if bs := d.decNumBytes(); len(bs) > 0 {
  827. if f, err = parseFloat64(bs); err != nil {
  828. d.d.errorv(err)
  829. }
  830. }
  831. return
  832. }
  833. func (d *jsonDecDriver) DecodeFloat32() (f float32) {
  834. var err error
  835. if bs := d.decNumBytes(); len(bs) > 0 {
  836. if f, err = parseFloat32(bs); err != nil {
  837. d.d.errorv(err)
  838. }
  839. }
  840. return
  841. }
  842. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  843. if ext == nil {
  844. re := rv.(*RawExt)
  845. re.Tag = xtag
  846. d.d.decode(&re.Value)
  847. } else if ext == SelfExt {
  848. rv2 := baseRV(rv)
  849. d.d.decodeValue(rv2, d.h.fnNoExt(rv2.Type()))
  850. } else {
  851. d.d.interfaceExtConvertAndDecode(rv, ext)
  852. }
  853. return
  854. }
  855. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  856. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  857. if d.se.InterfaceExt != nil {
  858. bsOut = bs
  859. d.DecodeExt(&bsOut, 0, &d.se)
  860. return
  861. }
  862. if d.tok == 0 {
  863. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  864. }
  865. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  866. if d.tok == '[' {
  867. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  868. if zerocopy && len(bs) == 0 {
  869. bs = d.d.b[:]
  870. }
  871. if bs == nil {
  872. bs = []byte{}
  873. } else {
  874. bs = bs[:0]
  875. }
  876. d.tok = 0
  877. bs = append(bs, uint8(d.DecodeUint64()))
  878. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  879. for d.tok != ']' {
  880. if d.tok != ',' {
  881. d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
  882. }
  883. d.tok = 0
  884. bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
  885. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  886. }
  887. d.tok = 0
  888. return bs
  889. }
  890. d.appendStringAsBytes()
  891. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  892. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  893. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  894. // However, it sets a fnull field to true, so we can check if a null was found.
  895. if len(d.bs) == 0 {
  896. if d.fnull {
  897. return nil
  898. }
  899. return []byte{}
  900. }
  901. bs0 := d.bs
  902. slen := base64.StdEncoding.DecodedLen(len(bs0))
  903. if slen <= cap(bs) {
  904. bsOut = bs[:slen]
  905. } else if zerocopy && slen <= cap(d.b2) {
  906. bsOut = d.b2[:slen]
  907. } else {
  908. bsOut = make([]byte, slen)
  909. }
  910. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  911. if err != nil {
  912. d.d.errorf("error decoding base64 binary '%s': %v", bs0, err)
  913. return nil
  914. }
  915. if slen != slen2 {
  916. bsOut = bsOut[:slen2]
  917. }
  918. return
  919. }
  920. // func (d *jsonDecDriver) DecodeString() (s string) {
  921. // d.appendStringAsBytes()
  922. // return d.bsToString()
  923. // }
  924. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  925. d.appendStringAsBytes()
  926. return d.bs
  927. }
  928. func (d *jsonDecDriver) appendStringAsBytes() {
  929. if d.tok == 0 {
  930. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  931. }
  932. d.fnull = false
  933. if d.tok != '"' {
  934. // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
  935. // handle non-string scalar: null, true, false or a number
  936. switch d.tok {
  937. case 'n':
  938. d.readLit4Null()
  939. d.bs = d.bs[:0]
  940. d.fnull = true
  941. case 'f':
  942. d.readLit4False()
  943. d.bs = d.bs[:5]
  944. copy(d.bs, "false")
  945. case 't':
  946. d.readLit4True()
  947. d.bs = d.bs[:4]
  948. copy(d.bs, "true")
  949. default:
  950. // try to parse a valid number
  951. bs := d.decNumBytes()
  952. if len(bs) <= cap(d.bs) {
  953. d.bs = d.bs[:len(bs)]
  954. } else {
  955. d.bs = make([]byte, len(bs))
  956. }
  957. copy(d.bs, bs)
  958. }
  959. return
  960. }
  961. d.tok = 0
  962. r := d.r
  963. var cs = r.readUntil(d.b2[:0], '"')
  964. var cslen = uint(len(cs))
  965. var c uint8
  966. v := d.bs[:0]
  967. // append on each byte seen can be expensive, so we just
  968. // keep track of where we last read a contiguous set of
  969. // non-special bytes (using cursor variable),
  970. // and when we see a special byte
  971. // e.g. end-of-slice, " or \,
  972. // we will append the full range into the v slice before proceeding
  973. var i, cursor uint
  974. for {
  975. if i == cslen {
  976. v = append(v, cs[cursor:]...)
  977. cs = r.readUntil(d.b2[:0], '"')
  978. cslen = uint(len(cs))
  979. i, cursor = 0, 0
  980. }
  981. c = cs[i]
  982. if c == '"' {
  983. v = append(v, cs[cursor:i]...)
  984. break
  985. }
  986. if c != '\\' {
  987. i++
  988. continue
  989. }
  990. v = append(v, cs[cursor:i]...)
  991. i++
  992. c = cs[i]
  993. switch c {
  994. case '"', '\\', '/', '\'':
  995. v = append(v, c)
  996. case 'b':
  997. v = append(v, '\b')
  998. case 'f':
  999. v = append(v, '\f')
  1000. case 'n':
  1001. v = append(v, '\n')
  1002. case 'r':
  1003. v = append(v, '\r')
  1004. case 't':
  1005. v = append(v, '\t')
  1006. case 'u':
  1007. var r rune
  1008. var rr uint32
  1009. if cslen < i+4 {
  1010. d.d.errorf("need at least 4 more bytes for unicode sequence")
  1011. }
  1012. var j uint
  1013. for _, c = range cs[i+1 : i+5] { // bounds-check-elimination
  1014. // best to use explicit if-else
  1015. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  1016. if c >= '0' && c <= '9' {
  1017. rr = rr*16 + uint32(c-jsonU4Chk2)
  1018. } else if c >= 'a' && c <= 'f' {
  1019. rr = rr*16 + uint32(c-jsonU4Chk1)
  1020. } else if c >= 'A' && c <= 'F' {
  1021. rr = rr*16 + uint32(c-jsonU4Chk0)
  1022. } else {
  1023. r = unicode.ReplacementChar
  1024. i += 4
  1025. goto encode_rune
  1026. }
  1027. }
  1028. r = rune(rr)
  1029. i += 4
  1030. if utf16.IsSurrogate(r) {
  1031. if len(cs) >= int(i+6) {
  1032. var cx = cs[i+1:][:6:6] // [:6] affords bounds-check-elimination
  1033. if cx[0] == '\\' && cx[1] == 'u' {
  1034. i += 2
  1035. var rr1 uint32
  1036. for j = 2; j < 6; j++ {
  1037. c = cx[j]
  1038. if c >= '0' && c <= '9' {
  1039. rr = rr*16 + uint32(c-jsonU4Chk2)
  1040. } else if c >= 'a' && c <= 'f' {
  1041. rr = rr*16 + uint32(c-jsonU4Chk1)
  1042. } else if c >= 'A' && c <= 'F' {
  1043. rr = rr*16 + uint32(c-jsonU4Chk0)
  1044. } else {
  1045. r = unicode.ReplacementChar
  1046. i += 4
  1047. goto encode_rune
  1048. }
  1049. }
  1050. r = utf16.DecodeRune(r, rune(rr1))
  1051. i += 4
  1052. goto encode_rune
  1053. }
  1054. }
  1055. r = unicode.ReplacementChar
  1056. }
  1057. encode_rune:
  1058. w2 := utf8.EncodeRune(d.bstr[:], r)
  1059. v = append(v, d.bstr[:w2]...)
  1060. default:
  1061. d.d.errorf("unsupported escaped value: %c", c)
  1062. }
  1063. i++
  1064. cursor = i
  1065. }
  1066. d.bs = v
  1067. }
  1068. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  1069. const cutoff = uint64(1 << uint(64-1))
  1070. var n uint64
  1071. var neg, badsyntax, overflow bool
  1072. if len(bs) == 0 {
  1073. if d.h.PreferFloat {
  1074. z.v = valueTypeFloat
  1075. z.f = 0
  1076. } else if d.h.SignedInteger {
  1077. z.v = valueTypeInt
  1078. z.i = 0
  1079. } else {
  1080. z.v = valueTypeUint
  1081. z.u = 0
  1082. }
  1083. return
  1084. }
  1085. if d.h.PreferFloat {
  1086. goto F
  1087. }
  1088. n, neg, badsyntax, overflow = jsonParseInteger(bs)
  1089. if badsyntax || overflow {
  1090. goto F
  1091. }
  1092. if neg {
  1093. if n > cutoff {
  1094. goto F
  1095. }
  1096. z.v = valueTypeInt
  1097. z.i = -(int64(n))
  1098. } else if d.h.SignedInteger {
  1099. if n >= cutoff {
  1100. goto F
  1101. }
  1102. z.v = valueTypeInt
  1103. z.i = int64(n)
  1104. } else {
  1105. z.v = valueTypeUint
  1106. z.u = n
  1107. }
  1108. return
  1109. F:
  1110. z.v = valueTypeFloat
  1111. z.f, err = parseFloat64(bs)
  1112. return
  1113. }
  1114. func (d *jsonDecDriver) bsToString() string {
  1115. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  1116. if jsonAlwaysReturnInternString || d.d.c == containerMapKey {
  1117. return d.d.string(d.bs)
  1118. }
  1119. return string(d.bs)
  1120. }
  1121. func (d *jsonDecDriver) DecodeNaked() {
  1122. z := d.d.naked()
  1123. // var decodeFurther bool
  1124. if d.tok == 0 {
  1125. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  1126. }
  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.n.reset()
  1309. }
  1310. func (d *jsonDecDriver) atEndOfDecode() {}
  1311. // jsonFloatStrconvFmtPrec ...
  1312. //
  1313. // ensure that every float has an 'e' or '.' in it,/ for easy differentiation from integers.
  1314. // this is better/faster than checking if encoded value has [e.] and appending if needed.
  1315. // func jsonFloatStrconvFmtPrec(f float64, bits32 bool) (fmt byte, prec int) {
  1316. // fmt = 'f'
  1317. // prec = -1
  1318. // var abs = math.Abs(f)
  1319. // if abs == 0 || abs == 1 {
  1320. // prec = 1
  1321. // } else if !bits32 && (abs < 1e-6 || abs >= 1e21) ||
  1322. // bits32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
  1323. // fmt = 'e'
  1324. // } else if _, frac := math.Modf(abs); frac == 0 {
  1325. // // ensure that floats have a .0 at the end, for easy identification as floats
  1326. // prec = 1
  1327. // }
  1328. // return
  1329. // }
  1330. func jsonFloatStrconvFmtPrec64(f float64) (fmt byte, prec int8) {
  1331. fmt = 'f'
  1332. prec = -1
  1333. var abs = math.Abs(f)
  1334. if abs == 0 || abs == 1 {
  1335. prec = 1
  1336. } else if abs < 1e-6 || abs >= 1e21 {
  1337. fmt = 'e'
  1338. } else if noFrac64(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1339. prec = 1
  1340. }
  1341. return
  1342. }
  1343. func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) {
  1344. fmt = 'f'
  1345. prec = -1
  1346. var abs = abs32(f)
  1347. if abs == 0 || abs == 1 {
  1348. prec = 1
  1349. } else if abs < 1e-6 || abs >= 1e21 {
  1350. fmt = 'e'
  1351. } else if noFrac32(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1352. prec = 1
  1353. }
  1354. return
  1355. }
  1356. // custom-fitted version of strconv.Parse(Ui|I)nt.
  1357. // Also ensures we don't have to search for .eE to determine if a float or not.
  1358. // Note: s CANNOT be a zero-length slice.
  1359. func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) {
  1360. const maxUint64 = (1<<64 - 1)
  1361. const cutoff = maxUint64/10 + 1
  1362. if len(s) == 0 { // bounds-check-elimination
  1363. // treat empty string as zero value
  1364. // badSyntax = true
  1365. return
  1366. }
  1367. switch s[0] {
  1368. case '+':
  1369. s = s[1:]
  1370. case '-':
  1371. s = s[1:]
  1372. neg = true
  1373. }
  1374. for _, c := range s {
  1375. if c < '0' || c > '9' {
  1376. badSyntax = true
  1377. return
  1378. }
  1379. // unsigned integers don't overflow well on multiplication, so check cutoff here
  1380. // e.g. (maxUint64-5)*10 doesn't overflow well ...
  1381. if n >= cutoff {
  1382. overflow = true
  1383. return
  1384. }
  1385. n *= 10
  1386. n1 := n + uint64(c-'0')
  1387. if n1 < n || n1 > maxUint64 {
  1388. overflow = true
  1389. return
  1390. }
  1391. n = n1
  1392. }
  1393. return
  1394. }
  1395. var _ decDriverContainerTracker = (*jsonDecDriver)(nil)
  1396. var _ encDriverContainerTracker = (*jsonEncDriver)(nil)
  1397. var _ decDriver = (*jsonDecDriver)(nil)
  1398. var _ encDriver = (*jsonEncDriverGeneric)(nil)
  1399. var _ encDriver = (*jsonEncDriverTypical)(nil)
  1400. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverTypical)(nil)
  1401. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverGeneric)(nil)
  1402. var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriver)(nil)
  1403. // var _ encDriver = (*jsonEncDriver)(nil)