json.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. // By default, this json support uses base64 encoding for bytes, because you cannot
  5. // store and read any arbitrary string in json (only unicode).
  6. // However, the user can configre how to encode/decode bytes.
  7. //
  8. // This library specifically supports UTF-8 for encoding and decoding only.
  9. //
  10. // Note that the library will happily encode/decode things which are not valid
  11. // json e.g. a map[int64]string. We do it for consistency. With valid json,
  12. // we will encode and decode appropriately.
  13. // Users can specify their map type if necessary to force it.
  14. //
  15. // Note:
  16. // - we cannot use strconv.Quote and strconv.Unquote because json quotes/unquotes differently.
  17. // We implement it here.
  18. // - Also, strconv.ParseXXX for floats and integers
  19. // - only works on strings resulting in unnecessary allocation and []byte-string conversion.
  20. // - it does a lot of redundant checks, because json numbers are simpler that what it supports.
  21. // - We parse numbers (floats and integers) directly here.
  22. // We only delegate parsing floats if it is a hairy float which could cause a loss of precision.
  23. // In that case, we delegate to strconv.ParseFloat.
  24. //
  25. // Note:
  26. // - encode does not beautify. There is no whitespace when encoding.
  27. // - rpc calls which take single integer arguments or write single numeric arguments will need care.
  28. // Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver
  29. // MUST not call one-another.
  30. import (
  31. "bytes"
  32. "encoding/base64"
  33. "fmt"
  34. "reflect"
  35. "strconv"
  36. "unicode/utf16"
  37. "unicode/utf8"
  38. )
  39. //--------------------------------
  40. var (
  41. jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
  42. jsonFloat64Pow10 = [...]float64{
  43. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  44. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  45. 1e20, 1e21, 1e22,
  46. }
  47. jsonUint64Pow10 = [...]uint64{
  48. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  49. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  50. }
  51. // jsonTabs and jsonSpaces are used as caches for indents
  52. jsonTabs, jsonSpaces string
  53. )
  54. const (
  55. // jsonUnreadAfterDecNum controls whether we unread after decoding a number.
  56. //
  57. // instead of unreading, just update d.tok (iff it's not a whitespace char)
  58. // However, doing this means that we may HOLD onto some data which belongs to another stream.
  59. // Thus, it is safest to unread the data when done.
  60. // keep behind a constant flag for now.
  61. jsonUnreadAfterDecNum = true
  62. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  63. // - If we see first character of null, false or true,
  64. // do not validate subsequent characters.
  65. // - e.g. if we see a n, assume null and skip next 3 characters,
  66. // and do not validate they are ull.
  67. // P.S. Do not expect a significant decoding boost from this.
  68. jsonValidateSymbols = true
  69. // if jsonTruncateMantissa, truncate mantissa if trailing 0's.
  70. // This is important because it could allow some floats to be decoded without
  71. // deferring to strconv.ParseFloat.
  72. jsonTruncateMantissa = true
  73. // if mantissa >= jsonNumUintCutoff before multiplying by 10, this is an overflow
  74. jsonNumUintCutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  75. // if mantissa >= jsonNumUintMaxVal, this is an overflow
  76. jsonNumUintMaxVal = 1<<uint64(64) - 1
  77. // jsonNumDigitsUint64Largest = 19
  78. jsonSpacesOrTabsLen = 128
  79. )
  80. func init() {
  81. var bs [jsonSpacesOrTabsLen]byte
  82. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  83. bs[i] = ' '
  84. }
  85. jsonSpaces = string(bs[:])
  86. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  87. bs[i] = '\t'
  88. }
  89. jsonTabs = string(bs[:])
  90. }
  91. type jsonEncDriver struct {
  92. e *Encoder
  93. w encWriter
  94. h *JsonHandle
  95. b [64]byte // scratch
  96. bs []byte // scratch
  97. se setExtWrapper
  98. ds string // indent string
  99. dl uint16 // indent level
  100. dt bool // indent using tabs
  101. d bool // indent
  102. c containerState
  103. noBuiltInTypes
  104. }
  105. // indent is done as below:
  106. // - newline and indent are added before each mapKey or arrayElem
  107. // - newline and indent are added before each ending,
  108. // except there was no entry (so we can have {} or [])
  109. func (e *jsonEncDriver) sendContainerState(c containerState) {
  110. // determine whether to output separators
  111. if c == containerMapKey {
  112. if e.c != containerMapStart {
  113. e.w.writen1(',')
  114. }
  115. if e.d {
  116. e.writeIndent()
  117. }
  118. } else if c == containerMapValue {
  119. if e.d {
  120. e.w.writen2(':', ' ')
  121. } else {
  122. e.w.writen1(':')
  123. }
  124. } else if c == containerMapEnd {
  125. if e.d {
  126. e.dl--
  127. if e.c != containerMapStart {
  128. e.writeIndent()
  129. }
  130. }
  131. e.w.writen1('}')
  132. } else if c == containerArrayElem {
  133. if e.c != containerArrayStart {
  134. e.w.writen1(',')
  135. }
  136. if e.d {
  137. e.writeIndent()
  138. }
  139. } else if c == containerArrayEnd {
  140. if e.d {
  141. e.dl--
  142. if e.c != containerArrayStart {
  143. e.writeIndent()
  144. }
  145. }
  146. e.w.writen1(']')
  147. }
  148. e.c = c
  149. }
  150. func (e *jsonEncDriver) writeIndent() {
  151. e.w.writen1('\n')
  152. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  153. if e.dt {
  154. e.w.writestr(jsonTabs[:x])
  155. } else {
  156. e.w.writestr(jsonSpaces[:x])
  157. }
  158. } else {
  159. for i := uint16(0); i < e.dl; i++ {
  160. e.w.writestr(e.ds)
  161. }
  162. }
  163. }
  164. func (e *jsonEncDriver) EncodeNil() {
  165. e.w.writeb(jsonLiterals[9:13]) // null
  166. }
  167. func (e *jsonEncDriver) EncodeBool(b bool) {
  168. if b {
  169. e.w.writeb(jsonLiterals[0:4]) // true
  170. } else {
  171. e.w.writeb(jsonLiterals[4:9]) // false
  172. }
  173. }
  174. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  175. e.encodeFloat(float64(f), 32)
  176. }
  177. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  178. // e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64))
  179. e.encodeFloat(f, 64)
  180. }
  181. func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
  182. x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
  183. e.w.writeb(x)
  184. if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
  185. e.w.writen2('.', '0')
  186. }
  187. }
  188. func (e *jsonEncDriver) EncodeInt(v int64) {
  189. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  190. e.w.writen1('"')
  191. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  192. e.w.writen1('"')
  193. return
  194. }
  195. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  196. }
  197. func (e *jsonEncDriver) EncodeUint(v uint64) {
  198. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  199. e.w.writen1('"')
  200. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  201. e.w.writen1('"')
  202. return
  203. }
  204. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  205. }
  206. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  207. if v := ext.ConvertExt(rv); v == nil {
  208. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  209. } else {
  210. en.encode(v)
  211. }
  212. }
  213. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  214. // only encodes re.Value (never re.Data)
  215. if re.Value == nil {
  216. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  217. } else {
  218. en.encode(re.Value)
  219. }
  220. }
  221. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  222. if e.d {
  223. e.dl++
  224. }
  225. e.w.writen1('[')
  226. e.c = containerArrayStart
  227. }
  228. func (e *jsonEncDriver) EncodeMapStart(length int) {
  229. if e.d {
  230. e.dl++
  231. }
  232. e.w.writen1('{')
  233. e.c = containerMapStart
  234. }
  235. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  236. // e.w.writestr(strconv.Quote(v))
  237. e.quoteStr(v)
  238. }
  239. func (e *jsonEncDriver) EncodeSymbol(v string) {
  240. // e.EncodeString(c_UTF8, v)
  241. e.quoteStr(v)
  242. }
  243. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  244. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  245. if c == c_RAW && e.se.i != nil {
  246. e.EncodeExt(v, 0, &e.se, e.e)
  247. return
  248. }
  249. if c == c_RAW {
  250. slen := base64.StdEncoding.EncodedLen(len(v))
  251. if cap(e.bs) >= slen {
  252. e.bs = e.bs[:slen]
  253. } else {
  254. e.bs = make([]byte, slen)
  255. }
  256. base64.StdEncoding.Encode(e.bs, v)
  257. e.w.writen1('"')
  258. e.w.writeb(e.bs)
  259. e.w.writen1('"')
  260. } else {
  261. // e.EncodeString(c, string(v))
  262. e.quoteStr(stringView(v))
  263. }
  264. }
  265. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  266. e.w.writeb(v)
  267. }
  268. func (e *jsonEncDriver) quoteStr(s string) {
  269. // adapted from std pkg encoding/json
  270. const hex = "0123456789abcdef"
  271. w := e.w
  272. w.writen1('"')
  273. start := 0
  274. for i := 0; i < len(s); {
  275. // encode all bytes < 0x20 (except \r, \n).
  276. // also encode < > & to prevent security holes when served to some browsers.
  277. if b := s[i]; b < utf8.RuneSelf {
  278. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  279. i++
  280. continue
  281. }
  282. if start < i {
  283. w.writestr(s[start:i])
  284. }
  285. switch b {
  286. case '\\', '"':
  287. w.writen2('\\', b)
  288. case '\n':
  289. w.writen2('\\', 'n')
  290. case '\r':
  291. w.writen2('\\', 'r')
  292. case '\b':
  293. w.writen2('\\', 'b')
  294. case '\f':
  295. w.writen2('\\', 'f')
  296. case '\t':
  297. w.writen2('\\', 't')
  298. case '<', '>', '&':
  299. if e.h.HTMLCharsAsIs {
  300. w.writen1(b)
  301. } else {
  302. w.writestr(`\u00`)
  303. w.writen2(hex[b>>4], hex[b&0xF])
  304. }
  305. default:
  306. w.writestr(`\u00`)
  307. w.writen2(hex[b>>4], hex[b&0xF])
  308. }
  309. i++
  310. start = i
  311. continue
  312. }
  313. c, size := utf8.DecodeRuneInString(s[i:])
  314. if c == utf8.RuneError && size == 1 {
  315. if start < i {
  316. w.writestr(s[start:i])
  317. }
  318. w.writestr(`\ufffd`)
  319. i += size
  320. start = i
  321. continue
  322. }
  323. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  324. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  325. if c == '\u2028' || c == '\u2029' {
  326. if start < i {
  327. w.writestr(s[start:i])
  328. }
  329. w.writestr(`\u202`)
  330. w.writen1(hex[c&0xF])
  331. i += size
  332. start = i
  333. continue
  334. }
  335. i += size
  336. }
  337. if start < len(s) {
  338. w.writestr(s[start:])
  339. }
  340. w.writen1('"')
  341. }
  342. //--------------------------------
  343. type jsonNum struct {
  344. // bytes []byte // may have [+-.eE0-9]
  345. mantissa uint64 // where mantissa ends, and maybe dot begins.
  346. exponent int16 // exponent value.
  347. manOverflow bool
  348. neg bool // started with -. No initial sign in the bytes above.
  349. dot bool // has dot
  350. explicitExponent bool // explicit exponent
  351. }
  352. func (x *jsonNum) reset() {
  353. x.manOverflow = false
  354. x.neg = false
  355. x.dot = false
  356. x.explicitExponent = false
  357. x.mantissa = 0
  358. x.exponent = 0
  359. }
  360. // uintExp is called only if exponent > 0.
  361. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  362. n = x.mantissa
  363. e := x.exponent
  364. if e >= int16(len(jsonUint64Pow10)) {
  365. overflow = true
  366. return
  367. }
  368. n *= jsonUint64Pow10[e]
  369. if n < x.mantissa || n > jsonNumUintMaxVal {
  370. overflow = true
  371. return
  372. }
  373. return
  374. // for i := int16(0); i < e; i++ {
  375. // if n >= jsonNumUintCutoff {
  376. // overflow = true
  377. // return
  378. // }
  379. // n *= 10
  380. // }
  381. // return
  382. }
  383. // these constants are only used withn floatVal.
  384. // They are brought out, so that floatVal can be inlined.
  385. const (
  386. jsonUint64MantissaBits = 52
  387. jsonMaxExponent = int16(len(jsonFloat64Pow10)) - 1
  388. )
  389. func (x *jsonNum) floatVal() (f float64, parseUsingStrConv bool) {
  390. // We do not want to lose precision.
  391. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  392. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  393. // We expect up to 99.... (19 digits)
  394. // - The mantissa cannot fit into a 52 bits of uint64
  395. // - The exponent is beyond our scope ie beyong 22.
  396. parseUsingStrConv = x.manOverflow ||
  397. x.exponent > jsonMaxExponent ||
  398. (x.exponent < 0 && -(x.exponent) > jsonMaxExponent) ||
  399. x.mantissa>>jsonUint64MantissaBits != 0
  400. if parseUsingStrConv {
  401. return
  402. }
  403. // all good. so handle parse here.
  404. f = float64(x.mantissa)
  405. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  406. if x.neg {
  407. f = -f
  408. }
  409. if x.exponent > 0 {
  410. f *= jsonFloat64Pow10[x.exponent]
  411. } else if x.exponent < 0 {
  412. f /= jsonFloat64Pow10[-x.exponent]
  413. }
  414. return
  415. }
  416. type jsonDecDriver struct {
  417. noBuiltInTypes
  418. d *Decoder
  419. h *JsonHandle
  420. r decReader
  421. c containerState
  422. // tok is used to store the token read right after skipWhiteSpace.
  423. tok uint8
  424. bstr [8]byte // scratch used for string \UXXX parsing
  425. b [64]byte // scratch, used for parsing strings or numbers
  426. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  427. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  428. se setExtWrapper
  429. n jsonNum
  430. }
  431. func jsonIsWS(b byte) bool {
  432. return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  433. }
  434. // // This will skip whitespace characters and return the next byte to read.
  435. // // The next byte determines what the value will be one of.
  436. // func (d *jsonDecDriver) skipWhitespace() {
  437. // // fast-path: do not enter loop. Just check first (in case no whitespace).
  438. // b := d.r.readn1()
  439. // if jsonIsWS(b) {
  440. // r := d.r
  441. // for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  442. // }
  443. // }
  444. // d.tok = b
  445. // }
  446. func (d *jsonDecDriver) uncacheRead() {
  447. if d.tok != 0 {
  448. d.r.unreadn1()
  449. d.tok = 0
  450. }
  451. }
  452. func (d *jsonDecDriver) sendContainerState(c containerState) {
  453. if d.tok == 0 {
  454. var b byte
  455. r := d.r
  456. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  457. }
  458. d.tok = b
  459. }
  460. var xc uint8 // char expected
  461. if c == containerMapKey {
  462. if d.c != containerMapStart {
  463. xc = ','
  464. }
  465. } else if c == containerMapValue {
  466. xc = ':'
  467. } else if c == containerMapEnd {
  468. xc = '}'
  469. } else if c == containerArrayElem {
  470. if d.c != containerArrayStart {
  471. xc = ','
  472. }
  473. } else if c == containerArrayEnd {
  474. xc = ']'
  475. }
  476. if xc != 0 {
  477. if d.tok != xc {
  478. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  479. }
  480. d.tok = 0
  481. }
  482. d.c = c
  483. }
  484. func (d *jsonDecDriver) CheckBreak() bool {
  485. if d.tok == 0 {
  486. var b byte
  487. r := d.r
  488. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  489. }
  490. d.tok = b
  491. }
  492. if d.tok == '}' || d.tok == ']' {
  493. // d.tok = 0 // only checking, not consuming
  494. return true
  495. }
  496. return false
  497. }
  498. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  499. bs := d.r.readx(int(toIdx - fromIdx))
  500. d.tok = 0
  501. if jsonValidateSymbols {
  502. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  503. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  504. return
  505. }
  506. }
  507. }
  508. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  509. if d.tok == 0 {
  510. var b byte
  511. r := d.r
  512. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  513. }
  514. d.tok = b
  515. }
  516. if d.tok == 'n' {
  517. d.readStrIdx(10, 13) // ull
  518. return true
  519. }
  520. return false
  521. }
  522. func (d *jsonDecDriver) DecodeBool() bool {
  523. if d.tok == 0 {
  524. var b byte
  525. r := d.r
  526. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  527. }
  528. d.tok = b
  529. }
  530. if d.tok == 'f' {
  531. d.readStrIdx(5, 9) // alse
  532. return false
  533. }
  534. if d.tok == 't' {
  535. d.readStrIdx(1, 4) // rue
  536. return true
  537. }
  538. d.d.errorf("json: decode bool: got first char %c", d.tok)
  539. return false // "unreachable"
  540. }
  541. func (d *jsonDecDriver) ReadMapStart() int {
  542. if d.tok == 0 {
  543. var b byte
  544. r := d.r
  545. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  546. }
  547. d.tok = b
  548. }
  549. if d.tok != '{' {
  550. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  551. }
  552. d.tok = 0
  553. d.c = containerMapStart
  554. return -1
  555. }
  556. func (d *jsonDecDriver) ReadArrayStart() int {
  557. if d.tok == 0 {
  558. var b byte
  559. r := d.r
  560. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  561. }
  562. d.tok = b
  563. }
  564. if d.tok != '[' {
  565. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  566. }
  567. d.tok = 0
  568. d.c = containerArrayStart
  569. return -1
  570. }
  571. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  572. // check container type by checking the first char
  573. if d.tok == 0 {
  574. var b byte
  575. r := d.r
  576. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  577. }
  578. d.tok = b
  579. }
  580. if b := d.tok; b == '{' {
  581. return valueTypeMap
  582. } else if b == '[' {
  583. return valueTypeArray
  584. } else if b == 'n' {
  585. return valueTypeNil
  586. } else if b == '"' {
  587. return valueTypeString
  588. }
  589. return valueTypeUnset
  590. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  591. // return false // "unreachable"
  592. }
  593. func (d *jsonDecDriver) decNum(storeBytes bool) {
  594. // If it is has a . or an e|E, decode as a float; else decode as an int.
  595. if d.tok == 0 {
  596. var b byte
  597. r := d.r
  598. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  599. }
  600. d.tok = b
  601. }
  602. b := d.tok
  603. var str bool
  604. if b == '"' {
  605. str = true
  606. b = d.r.readn1()
  607. }
  608. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  609. d.d.errorf("json: decNum: got first char '%c'", b)
  610. return
  611. }
  612. d.tok = 0
  613. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  614. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  615. n := &d.n
  616. r := d.r
  617. n.reset()
  618. d.bs = d.bs[:0]
  619. if str && storeBytes {
  620. d.bs = append(d.bs, '"')
  621. }
  622. // The format of a number is as below:
  623. // parsing: sign? digit* dot? digit* e? sign? digit*
  624. // states: 0 1* 2 3* 4 5* 6 7
  625. // We honor this state so we can break correctly.
  626. var state uint8 = 0
  627. var eNeg bool
  628. var e int16
  629. var eof bool
  630. LOOP:
  631. for !eof {
  632. // fmt.Printf("LOOP: b: %q\n", b)
  633. switch b {
  634. case '+':
  635. switch state {
  636. case 0:
  637. state = 2
  638. if storeBytes {
  639. d.bs = append(d.bs, b)
  640. }
  641. b, eof = r.readn1eof()
  642. continue
  643. case 6: // typ = jsonNumFloat
  644. state = 7
  645. default:
  646. break LOOP
  647. }
  648. case '-':
  649. switch state {
  650. case 0:
  651. state = 2
  652. n.neg = true
  653. if storeBytes {
  654. d.bs = append(d.bs, b)
  655. }
  656. b, eof = r.readn1eof()
  657. continue
  658. case 6: // typ = jsonNumFloat
  659. eNeg = true
  660. state = 7
  661. default:
  662. break LOOP
  663. }
  664. case '.':
  665. switch state {
  666. case 0, 2: // typ = jsonNumFloat
  667. state = 4
  668. n.dot = true
  669. default:
  670. break LOOP
  671. }
  672. case 'e', 'E':
  673. switch state {
  674. case 0, 2, 4: // typ = jsonNumFloat
  675. state = 6
  676. // n.mantissaEndIndex = int16(len(n.bytes))
  677. n.explicitExponent = true
  678. default:
  679. break LOOP
  680. }
  681. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  682. switch state {
  683. case 0:
  684. state = 2
  685. fallthrough
  686. case 2:
  687. fallthrough
  688. case 4:
  689. if n.dot {
  690. n.exponent--
  691. }
  692. if n.mantissa >= jsonNumUintCutoff {
  693. n.manOverflow = true
  694. break
  695. }
  696. v := uint64(b - '0')
  697. n.mantissa *= 10
  698. if v != 0 {
  699. n1 := n.mantissa + v
  700. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  701. n.manOverflow = true // n+v overflows
  702. break
  703. }
  704. n.mantissa = n1
  705. }
  706. case 6:
  707. state = 7
  708. fallthrough
  709. case 7:
  710. if !(b == '0' && e == 0) {
  711. e = e*10 + int16(b-'0')
  712. }
  713. default:
  714. break LOOP
  715. }
  716. case '"':
  717. if str {
  718. if storeBytes {
  719. d.bs = append(d.bs, '"')
  720. }
  721. b, eof = r.readn1eof()
  722. }
  723. break LOOP
  724. default:
  725. break LOOP
  726. }
  727. if storeBytes {
  728. d.bs = append(d.bs, b)
  729. }
  730. b, eof = r.readn1eof()
  731. }
  732. if jsonTruncateMantissa && n.mantissa != 0 {
  733. for n.mantissa%10 == 0 {
  734. n.mantissa /= 10
  735. n.exponent++
  736. }
  737. }
  738. if e != 0 {
  739. if eNeg {
  740. n.exponent -= e
  741. } else {
  742. n.exponent += e
  743. }
  744. }
  745. // d.n = n
  746. if !eof {
  747. if jsonUnreadAfterDecNum {
  748. r.unreadn1()
  749. } else {
  750. if !jsonIsWS(b) {
  751. d.tok = b
  752. }
  753. }
  754. }
  755. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  756. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  757. return
  758. }
  759. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  760. d.decNum(false)
  761. n := &d.n
  762. if n.manOverflow {
  763. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  764. return
  765. }
  766. var u uint64
  767. if n.exponent == 0 {
  768. u = n.mantissa
  769. } else if n.exponent < 0 {
  770. d.d.errorf("json: fractional integer")
  771. return
  772. } else if n.exponent > 0 {
  773. var overflow bool
  774. if u, overflow = n.uintExp(); overflow {
  775. d.d.errorf("json: overflow integer")
  776. return
  777. }
  778. }
  779. i = int64(u)
  780. if n.neg {
  781. i = -i
  782. }
  783. if chkOvf.Int(i, bitsize) {
  784. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  785. return
  786. }
  787. // fmt.Printf("DecodeInt: %v\n", i)
  788. return
  789. }
  790. // floatVal MUST only be called after a decNum, as d.bs now contains the bytes of the number
  791. func (d *jsonDecDriver) floatVal() (f float64) {
  792. f, useStrConv := d.n.floatVal()
  793. if useStrConv {
  794. var err error
  795. if f, err = strconv.ParseFloat(stringView(d.bs), 64); err != nil {
  796. panic(fmt.Errorf("parse float: %s, %v", d.bs, err))
  797. }
  798. if d.n.neg {
  799. f = -f
  800. }
  801. }
  802. return
  803. }
  804. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  805. d.decNum(false)
  806. n := &d.n
  807. if n.neg {
  808. d.d.errorf("json: unsigned integer cannot be negative")
  809. return
  810. }
  811. if n.manOverflow {
  812. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  813. return
  814. }
  815. if n.exponent == 0 {
  816. u = n.mantissa
  817. } else if n.exponent < 0 {
  818. d.d.errorf("json: fractional integer")
  819. return
  820. } else if n.exponent > 0 {
  821. var overflow bool
  822. if u, overflow = n.uintExp(); overflow {
  823. d.d.errorf("json: overflow integer")
  824. return
  825. }
  826. }
  827. if chkOvf.Uint(u, bitsize) {
  828. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  829. return
  830. }
  831. // fmt.Printf("DecodeUint: %v\n", u)
  832. return
  833. }
  834. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  835. d.decNum(true)
  836. f = d.floatVal()
  837. if chkOverflow32 && chkOvf.Float32(f) {
  838. d.d.errorf("json: overflow float32: %v, %s", f, d.bs)
  839. return
  840. }
  841. return
  842. }
  843. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  844. if ext == nil {
  845. re := rv.(*RawExt)
  846. re.Tag = xtag
  847. d.d.decode(&re.Value)
  848. } else {
  849. var v interface{}
  850. d.d.decode(&v)
  851. ext.UpdateExt(rv, v)
  852. }
  853. return
  854. }
  855. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  856. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  857. if !isstring && d.se.i != nil {
  858. bsOut = bs
  859. d.DecodeExt(&bsOut, 0, &d.se)
  860. return
  861. }
  862. d.appendStringAsBytes()
  863. // if isstring, then just return the bytes, even if it is using the scratch buffer.
  864. // the bytes will be converted to a string as needed.
  865. if isstring {
  866. return d.bs
  867. }
  868. // if appendStringAsBytes returned a zero-len slice, then treat as nil.
  869. // This should only happen for null, and "".
  870. if len(d.bs) == 0 {
  871. return nil
  872. }
  873. bs0 := d.bs
  874. slen := base64.StdEncoding.DecodedLen(len(bs0))
  875. if slen <= cap(bs) {
  876. bsOut = bs[:slen]
  877. } else if zerocopy && slen <= cap(d.b2) {
  878. bsOut = d.b2[:slen]
  879. } else {
  880. bsOut = make([]byte, slen)
  881. }
  882. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  883. if err != nil {
  884. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  885. return nil
  886. }
  887. if slen != slen2 {
  888. bsOut = bsOut[:slen2]
  889. }
  890. return
  891. }
  892. func (d *jsonDecDriver) DecodeString() (s string) {
  893. d.appendStringAsBytes()
  894. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  895. if d.c == containerMapKey {
  896. return d.d.string(d.bs)
  897. }
  898. return string(d.bs)
  899. }
  900. func (d *jsonDecDriver) appendStringAsBytes() {
  901. if d.tok == 0 {
  902. var b byte
  903. r := d.r
  904. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  905. }
  906. d.tok = b
  907. }
  908. if d.tok != '"' {
  909. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  910. // handle non-string scalar: null, true, false or a number
  911. switch d.tok {
  912. case 'n':
  913. d.readStrIdx(10, 13) // ull
  914. d.bs = d.bs[:0]
  915. case 'f':
  916. d.readStrIdx(5, 9) // alse
  917. d.bs = d.bs[:5]
  918. copy(d.bs, "false")
  919. case 't':
  920. d.readStrIdx(1, 4) // rue
  921. d.bs = d.bs[:4]
  922. copy(d.bs, "true")
  923. default:
  924. // try to parse a valid number
  925. d.decNum(true)
  926. }
  927. return
  928. }
  929. d.tok = 0
  930. v := d.bs[:0]
  931. var c uint8
  932. r := d.r
  933. for {
  934. c = r.readn1()
  935. if c == '"' {
  936. break
  937. } else if c == '\\' {
  938. c = r.readn1()
  939. switch c {
  940. case '"', '\\', '/', '\'':
  941. v = append(v, c)
  942. case 'b':
  943. v = append(v, '\b')
  944. case 'f':
  945. v = append(v, '\f')
  946. case 'n':
  947. v = append(v, '\n')
  948. case 'r':
  949. v = append(v, '\r')
  950. case 't':
  951. v = append(v, '\t')
  952. case 'u':
  953. rr := d.jsonU4(false)
  954. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  955. if utf16.IsSurrogate(rr) {
  956. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  957. }
  958. w2 := utf8.EncodeRune(d.bstr[:], rr)
  959. v = append(v, d.bstr[:w2]...)
  960. default:
  961. d.d.errorf("json: unsupported escaped value: %c", c)
  962. }
  963. } else {
  964. v = append(v, c)
  965. }
  966. }
  967. d.bs = v
  968. }
  969. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  970. r := d.r
  971. if checkSlashU && !(r.readn1() == '\\' && r.readn1() == 'u') {
  972. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  973. return 0
  974. }
  975. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  976. var u uint32
  977. for i := 0; i < 4; i++ {
  978. v := r.readn1()
  979. if '0' <= v && v <= '9' {
  980. v = v - '0'
  981. } else if 'a' <= v && v <= 'z' {
  982. v = v - 'a' + 10
  983. } else if 'A' <= v && v <= 'Z' {
  984. v = v - 'A' + 10
  985. } else {
  986. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  987. return 0
  988. }
  989. u = u*16 + uint32(v)
  990. }
  991. return rune(u)
  992. }
  993. func (d *jsonDecDriver) DecodeNaked() {
  994. z := &d.d.n
  995. // var decodeFurther bool
  996. if d.tok == 0 {
  997. var b byte
  998. r := d.r
  999. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  1000. }
  1001. d.tok = b
  1002. }
  1003. switch d.tok {
  1004. case 'n':
  1005. d.readStrIdx(10, 13) // ull
  1006. z.v = valueTypeNil
  1007. case 'f':
  1008. d.readStrIdx(5, 9) // alse
  1009. z.v = valueTypeBool
  1010. z.b = false
  1011. case 't':
  1012. d.readStrIdx(1, 4) // rue
  1013. z.v = valueTypeBool
  1014. z.b = true
  1015. case '{':
  1016. z.v = valueTypeMap
  1017. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadMapStart
  1018. // decodeFurther = true
  1019. case '[':
  1020. z.v = valueTypeArray
  1021. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadArrayStart
  1022. // decodeFurther = true
  1023. case '"':
  1024. z.v = valueTypeString
  1025. z.s = d.DecodeString()
  1026. default: // number
  1027. d.decNum(true)
  1028. n := &d.n
  1029. // if the string had a any of [.eE], then decode as float.
  1030. switch {
  1031. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  1032. z.v = valueTypeFloat
  1033. z.f = d.floatVal()
  1034. case n.exponent == 0:
  1035. u := n.mantissa
  1036. switch {
  1037. case n.neg:
  1038. z.v = valueTypeInt
  1039. z.i = -int64(u)
  1040. case d.h.SignedInteger:
  1041. z.v = valueTypeInt
  1042. z.i = int64(u)
  1043. default:
  1044. z.v = valueTypeUint
  1045. z.u = u
  1046. }
  1047. default:
  1048. u, overflow := n.uintExp()
  1049. switch {
  1050. case overflow:
  1051. z.v = valueTypeFloat
  1052. z.f = d.floatVal()
  1053. case n.neg:
  1054. z.v = valueTypeInt
  1055. z.i = -int64(u)
  1056. case d.h.SignedInteger:
  1057. z.v = valueTypeInt
  1058. z.i = int64(u)
  1059. default:
  1060. z.v = valueTypeUint
  1061. z.u = u
  1062. }
  1063. }
  1064. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  1065. }
  1066. // if decodeFurther {
  1067. // d.s.sc.retryRead()
  1068. // }
  1069. return
  1070. }
  1071. //----------------------
  1072. // JsonHandle is a handle for JSON encoding format.
  1073. //
  1074. // Json is comprehensively supported:
  1075. // - decodes numbers into interface{} as int, uint or float64
  1076. // - configurable way to encode/decode []byte .
  1077. // by default, encodes and decodes []byte using base64 Std Encoding
  1078. // - UTF-8 support for encoding and decoding
  1079. //
  1080. // It has better performance than the json library in the standard library,
  1081. // by leveraging the performance improvements of the codec library and
  1082. // minimizing allocations.
  1083. //
  1084. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1085. // reading multiple values from a stream containing json and non-json content.
  1086. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1087. // all from the same stream in sequence.
  1088. type JsonHandle struct {
  1089. textEncodingType
  1090. BasicHandle
  1091. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1092. // If not configured, raw bytes are encoded to/from base64 text.
  1093. RawBytesExt InterfaceExt
  1094. // Indent indicates how a value is encoded.
  1095. // - If positive, indent by that number of spaces.
  1096. // - If negative, indent by that number of tabs.
  1097. Indent int8
  1098. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1099. //
  1100. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1101. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1102. // This can be mitigated by configuring how to encode integers.
  1103. //
  1104. // IntegerAsString interpretes the following values:
  1105. // - if 'L', then encode integers > 2^53 as a json string.
  1106. // - if 'A', then encode all integers as a json string
  1107. // containing the exact integer representation as a decimal.
  1108. // - else encode all integers as a json number (default)
  1109. IntegerAsString uint8
  1110. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1111. //
  1112. // By default, we encode them as \uXXX
  1113. // to prevent security holes when served from some browsers.
  1114. HTMLCharsAsIs bool
  1115. }
  1116. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1117. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1118. }
  1119. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1120. hd := jsonEncDriver{e: e, h: h}
  1121. hd.bs = hd.b[:0]
  1122. hd.reset()
  1123. return &hd
  1124. }
  1125. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1126. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1127. hd := jsonDecDriver{d: d, h: h}
  1128. hd.bs = hd.b[:0]
  1129. hd.reset()
  1130. return &hd
  1131. }
  1132. func (e *jsonEncDriver) reset() {
  1133. e.w = e.e.w
  1134. e.se.i = e.h.RawBytesExt
  1135. if e.bs != nil {
  1136. e.bs = e.bs[:0]
  1137. }
  1138. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1139. e.c = 0
  1140. if e.h.Indent > 0 {
  1141. e.d = true
  1142. e.ds = jsonSpaces[:e.h.Indent]
  1143. } else if e.h.Indent < 0 {
  1144. e.d = true
  1145. e.dt = true
  1146. e.ds = jsonTabs[:-(e.h.Indent)]
  1147. }
  1148. }
  1149. func (d *jsonDecDriver) reset() {
  1150. d.r = d.d.r
  1151. d.se.i = d.h.RawBytesExt
  1152. if d.bs != nil {
  1153. d.bs = d.bs[:0]
  1154. }
  1155. d.c, d.tok = 0, 0
  1156. d.n.reset()
  1157. }
  1158. var jsonEncodeTerminate = []byte{' '}
  1159. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1160. return jsonEncodeTerminate
  1161. }
  1162. var _ decDriver = (*jsonDecDriver)(nil)
  1163. var _ encDriver = (*jsonEncDriver)(nil)