另客网go项目公用的代码库

json.go 36KB

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