json.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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. // They all must call sep(), and sep() MUST NOT be called more than once for each read.
  31. // If sep() is called and read is not done, you MUST call retryRead so separator wouldn't be read/written twice.
  32. import (
  33. "bytes"
  34. "encoding/base64"
  35. "fmt"
  36. "reflect"
  37. "strconv"
  38. "unicode/utf16"
  39. "unicode/utf8"
  40. )
  41. //--------------------------------
  42. var jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
  43. var jsonFloat64Pow10 = [...]float64{
  44. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  45. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  46. 1e20, 1e21, 1e22,
  47. }
  48. var jsonUint64Pow10 = [...]uint64{
  49. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  50. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  51. }
  52. const (
  53. // if jsonTrackSkipWhitespace, we track Whitespace and reduce the number of redundant checks.
  54. // Make it a const flag, so that it can be elided during linking if false.
  55. //
  56. // It is not a clear win, because we continually set a flag behind a pointer
  57. // and then check it each time, as opposed to just 4 conditionals on a stack variable.
  58. jsonTrackSkipWhitespace = true
  59. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  60. // - If we see first character of null, false or true,
  61. // do not validate subsequent characters.
  62. // - e.g. if we see a n, assume null and skip next 3 characters,
  63. // and do not validate they are ull.
  64. // P.S. Do not expect a significant decoding boost from this.
  65. jsonValidateSymbols = true
  66. // if jsonTruncateMantissa, truncate mantissa if trailing 0's.
  67. // This is important because it could allow some floats to be decoded without
  68. // deferring to strconv.ParseFloat.
  69. jsonTruncateMantissa = true
  70. // if mantissa >= jsonNumUintCutoff before multiplying by 10, this is an overflow
  71. jsonNumUintCutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  72. // if mantissa >= jsonNumUintMaxVal, this is an overflow
  73. jsonNumUintMaxVal = 1<<uint64(64) - 1
  74. // jsonNumDigitsUint64Largest = 19
  75. )
  76. // A stack is used to keep track of where we are in the tree.
  77. // This is necessary, as the Handle must know whether to consume or emit a separator.
  78. type jsonStackElem struct {
  79. st byte // top of stack (either '}' or ']' or 0 for map, array or neither).
  80. sf bool // NOT first time in that container at top of stack
  81. so bool // stack ctr odd
  82. sr bool // value has NOT been read, so do not re-send separator
  83. }
  84. func (x *jsonStackElem) retryRead() {
  85. if x != nil && !x.sr {
  86. x.sr = true
  87. }
  88. }
  89. func (x *jsonStackElem) sep() (c byte) {
  90. // do not use switch, so it's a candidate for inlining.
  91. // to inline effectively, this must not be called from within another method.
  92. // v := j.st
  93. if x == nil || x.st == 0 {
  94. return
  95. }
  96. if x.sr {
  97. x.sr = false
  98. return
  99. }
  100. // v == '}' OR ']'
  101. if x.st == '}' {
  102. // put , or : depending on if even or odd respectively
  103. if x.so {
  104. c = ':'
  105. if !x.sf {
  106. x.sf = true
  107. }
  108. } else if x.sf {
  109. c = ','
  110. }
  111. } else {
  112. if x.sf {
  113. c = ','
  114. } else {
  115. x.sf = true
  116. }
  117. }
  118. x.so = !x.so
  119. if x.sr {
  120. x.sr = false
  121. }
  122. return
  123. }
  124. // jsonStack contains the stack for tracking the state of the container (branch).
  125. // The same data structure is used during encode and decode, as it is similar functionality.
  126. type jsonStack struct {
  127. s []jsonStackElem // stack for map or array end tag. map=}, array=]
  128. sc *jsonStackElem // pointer to current (top) element on the stack.
  129. }
  130. func (j *jsonStack) start(c byte) {
  131. j.s = append(j.s, jsonStackElem{st: c})
  132. j.sc = &(j.s[len(j.s)-1])
  133. }
  134. func (j *jsonStack) end() {
  135. l := len(j.s) - 1 // length of new stack after pop'ing
  136. j.s = j.s[:l]
  137. if l == 0 {
  138. j.sc = nil
  139. } else {
  140. j.sc = &(j.s[l-1])
  141. }
  142. //j.sc = &(j.s[len(j.s)-1])
  143. }
  144. type jsonEncDriver struct {
  145. e *Encoder
  146. w encWriter
  147. h *JsonHandle
  148. b [64]byte // scratch
  149. bs []byte // scratch
  150. se setExtWrapper
  151. s jsonStack
  152. noBuiltInTypes
  153. }
  154. func (e *jsonEncDriver) EncodeNil() {
  155. if c := e.s.sc.sep(); c != 0 {
  156. e.w.writen1(c)
  157. }
  158. e.w.writeb(jsonLiterals[9:13]) // null
  159. }
  160. func (e *jsonEncDriver) EncodeBool(b bool) {
  161. if c := e.s.sc.sep(); c != 0 {
  162. e.w.writen1(c)
  163. }
  164. if b {
  165. e.w.writeb(jsonLiterals[0:4]) // true
  166. } else {
  167. e.w.writeb(jsonLiterals[4:9]) // false
  168. }
  169. }
  170. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  171. if c := e.s.sc.sep(); c != 0 {
  172. e.w.writen1(c)
  173. }
  174. e.w.writeb(strconv.AppendFloat(e.b[:0], float64(f), 'E', -1, 32))
  175. }
  176. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  177. if c := e.s.sc.sep(); c != 0 {
  178. e.w.writen1(c)
  179. }
  180. // e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64))
  181. e.w.writeb(strconv.AppendFloat(e.b[:0], f, 'E', -1, 64))
  182. }
  183. func (e *jsonEncDriver) EncodeInt(v int64) {
  184. if c := e.s.sc.sep(); c != 0 {
  185. e.w.writen1(c)
  186. }
  187. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  188. }
  189. func (e *jsonEncDriver) EncodeUint(v uint64) {
  190. if c := e.s.sc.sep(); c != 0 {
  191. e.w.writen1(c)
  192. }
  193. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  194. }
  195. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  196. if c := e.s.sc.sep(); c != 0 {
  197. e.w.writen1(c)
  198. }
  199. if v := ext.ConvertExt(rv); v == nil {
  200. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  201. } else {
  202. e.s.sc.retryRead()
  203. en.encode(v)
  204. }
  205. }
  206. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  207. if c := e.s.sc.sep(); c != 0 {
  208. e.w.writen1(c)
  209. }
  210. // only encodes re.Value (never re.Data)
  211. if re.Value == nil {
  212. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  213. } else {
  214. e.s.sc.retryRead()
  215. en.encode(re.Value)
  216. }
  217. }
  218. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  219. if c := e.s.sc.sep(); c != 0 {
  220. e.w.writen1(c)
  221. }
  222. e.s.start(']')
  223. e.w.writen1('[')
  224. }
  225. func (e *jsonEncDriver) EncodeMapStart(length int) {
  226. if c := e.s.sc.sep(); c != 0 {
  227. e.w.writen1(c)
  228. }
  229. e.s.start('}')
  230. e.w.writen1('{')
  231. }
  232. func (e *jsonEncDriver) EncodeEnd() {
  233. b := e.s.sc.st
  234. e.s.end()
  235. e.w.writen1(b)
  236. }
  237. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  238. // e.w.writestr(strconv.Quote(v))
  239. if c := e.s.sc.sep(); c != 0 {
  240. e.w.writen1(c)
  241. }
  242. e.quoteStr(v)
  243. }
  244. func (e *jsonEncDriver) EncodeSymbol(v string) {
  245. // e.EncodeString(c_UTF8, v)
  246. if c := e.s.sc.sep(); c != 0 {
  247. e.w.writen1(c)
  248. }
  249. e.quoteStr(v)
  250. }
  251. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  252. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  253. if c == c_RAW && e.se.i != nil {
  254. e.EncodeExt(v, 0, &e.se, e.e)
  255. return
  256. }
  257. if c := e.s.sc.sep(); c != 0 {
  258. e.w.writen1(c)
  259. }
  260. if c == c_RAW {
  261. slen := base64.StdEncoding.EncodedLen(len(v))
  262. if e.bs == nil {
  263. e.bs = e.b[:]
  264. }
  265. if cap(e.bs) >= slen {
  266. e.bs = e.bs[:slen]
  267. } else {
  268. e.bs = make([]byte, slen)
  269. }
  270. base64.StdEncoding.Encode(e.bs, v)
  271. e.w.writen1('"')
  272. e.w.writeb(e.bs)
  273. e.w.writen1('"')
  274. } else {
  275. // e.EncodeString(c, string(v))
  276. e.quoteStr(stringView(v))
  277. }
  278. }
  279. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  280. if c := e.s.sc.sep(); c != 0 {
  281. e.w.writen1(c)
  282. }
  283. e.w.writeb(v)
  284. }
  285. func (e *jsonEncDriver) quoteStr(s string) {
  286. // adapted from std pkg encoding/json
  287. const hex = "0123456789abcdef"
  288. w := e.w
  289. w.writen1('"')
  290. start := 0
  291. for i := 0; i < len(s); {
  292. if b := s[i]; b < utf8.RuneSelf {
  293. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  294. i++
  295. continue
  296. }
  297. if start < i {
  298. w.writestr(s[start:i])
  299. }
  300. switch b {
  301. case '\\', '"':
  302. w.writen2('\\', b)
  303. case '\n':
  304. w.writen2('\\', 'n')
  305. case '\r':
  306. w.writen2('\\', 'r')
  307. case '\b':
  308. w.writen2('\\', 'b')
  309. case '\f':
  310. w.writen2('\\', 'f')
  311. case '\t':
  312. w.writen2('\\', 't')
  313. default:
  314. // encode all bytes < 0x20 (except \r, \n).
  315. // also encode < > & to prevent security holes when served to some browsers.
  316. w.writestr(`\u00`)
  317. w.writen2(hex[b>>4], hex[b&0xF])
  318. }
  319. i++
  320. start = i
  321. continue
  322. }
  323. c, size := utf8.DecodeRuneInString(s[i:])
  324. if c == utf8.RuneError && size == 1 {
  325. if start < i {
  326. w.writestr(s[start:i])
  327. }
  328. w.writestr(`\ufffd`)
  329. i += size
  330. start = i
  331. continue
  332. }
  333. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  334. // Both technically valid JSON, but bomb on JSONP, so fix here.
  335. if c == '\u2028' || c == '\u2029' {
  336. if start < i {
  337. w.writestr(s[start:i])
  338. }
  339. w.writestr(`\u202`)
  340. w.writen1(hex[c&0xF])
  341. i += size
  342. start = i
  343. continue
  344. }
  345. i += size
  346. }
  347. if start < len(s) {
  348. w.writestr(s[start:])
  349. }
  350. w.writen1('"')
  351. }
  352. //--------------------------------
  353. type jsonNum struct {
  354. bytes []byte // may have [+-.eE0-9]
  355. mantissa uint64 // where mantissa ends, and maybe dot begins.
  356. exponent int16 // exponent value.
  357. manOverflow bool
  358. neg bool // started with -. No initial sign in the bytes above.
  359. dot bool // has dot
  360. explicitExponent bool // explicit exponent
  361. }
  362. func (x *jsonNum) reset() {
  363. x.bytes = x.bytes[:0]
  364. x.manOverflow = false
  365. x.neg = false
  366. x.dot = false
  367. x.explicitExponent = false
  368. x.mantissa = 0
  369. x.exponent = 0
  370. }
  371. // uintExp is called only if exponent > 0.
  372. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  373. n = x.mantissa
  374. e := x.exponent
  375. if e >= int16(len(jsonUint64Pow10)) {
  376. overflow = true
  377. return
  378. }
  379. n *= jsonUint64Pow10[e]
  380. if n < x.mantissa || n > jsonNumUintMaxVal {
  381. overflow = true
  382. return
  383. }
  384. return
  385. // for i := int16(0); i < e; i++ {
  386. // if n >= jsonNumUintCutoff {
  387. // overflow = true
  388. // return
  389. // }
  390. // n *= 10
  391. // }
  392. // return
  393. }
  394. func (x *jsonNum) floatVal() (f float64) {
  395. // We do not want to lose precision.
  396. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  397. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  398. // We expect up to 99.... (19 digits)
  399. // - The mantissa cannot fit into a 52 bits of uint64
  400. // - The exponent is beyond our scope ie beyong 22.
  401. const uint64MantissaBits = 52
  402. const maxExponent = int16(len(jsonFloat64Pow10)) - 1
  403. parseUsingStrConv := x.manOverflow ||
  404. x.exponent > maxExponent ||
  405. (x.exponent < 0 && -(x.exponent) > maxExponent) ||
  406. x.mantissa>>uint64MantissaBits != 0
  407. if parseUsingStrConv {
  408. var err error
  409. if f, err = strconv.ParseFloat(stringView(x.bytes), 64); err != nil {
  410. panic(fmt.Errorf("parse float: %s, %v", x.bytes, err))
  411. return
  412. }
  413. if x.neg {
  414. f = -f
  415. }
  416. return
  417. }
  418. // all good. so handle parse here.
  419. f = float64(x.mantissa)
  420. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  421. if x.neg {
  422. f = -f
  423. }
  424. if x.exponent > 0 {
  425. f *= jsonFloat64Pow10[x.exponent]
  426. } else if x.exponent < 0 {
  427. f /= jsonFloat64Pow10[-x.exponent]
  428. }
  429. return
  430. }
  431. type jsonDecDriver struct {
  432. d *Decoder
  433. h *JsonHandle
  434. r decReader // *bytesDecReader decReader
  435. ct valueType // container type. one of unset, array or map.
  436. bstr [8]byte // scratch used for string \UXXX parsing
  437. b [64]byte // scratch
  438. wsSkipped bool // whitespace skipped
  439. se setExtWrapper
  440. s jsonStack
  441. n jsonNum
  442. noBuiltInTypes
  443. }
  444. // This will skip whitespace characters and return the next byte to read.
  445. // The next byte determines what the value will be one of.
  446. func (d *jsonDecDriver) skipWhitespace(unread bool) (b byte) {
  447. // as initReadNext is not called all the time, we set ct to unSet whenever
  448. // we skipwhitespace, as this is the signal that something new is about to be read.
  449. d.ct = valueTypeUnset
  450. b = d.r.readn1()
  451. if !jsonTrackSkipWhitespace || !d.wsSkipped {
  452. for ; b == ' ' || b == '\t' || b == '\r' || b == '\n'; b = d.r.readn1() {
  453. }
  454. if jsonTrackSkipWhitespace {
  455. d.wsSkipped = true
  456. }
  457. }
  458. if unread {
  459. d.r.unreadn1()
  460. }
  461. return b
  462. }
  463. func (d *jsonDecDriver) CheckBreak() bool {
  464. b := d.skipWhitespace(true)
  465. return b == '}' || b == ']'
  466. }
  467. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  468. bs := d.r.readx(int(toIdx - fromIdx))
  469. if jsonValidateSymbols {
  470. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  471. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  472. return
  473. }
  474. }
  475. if jsonTrackSkipWhitespace {
  476. d.wsSkipped = false
  477. }
  478. }
  479. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  480. // we mustn't consume the state here, and end up trying to read separator twice.
  481. // Instead, we keep track of the state and restore it if we couldn't decode as nil.
  482. if c := d.s.sc.sep(); c != 0 {
  483. d.expectChar(c)
  484. }
  485. b := d.skipWhitespace(false)
  486. if b == 'n' {
  487. d.readStrIdx(10, 13) // ull
  488. d.ct = valueTypeNil
  489. return true
  490. }
  491. d.r.unreadn1()
  492. d.s.sc.retryRead()
  493. return false
  494. }
  495. func (d *jsonDecDriver) DecodeBool() bool {
  496. if c := d.s.sc.sep(); c != 0 {
  497. d.expectChar(c)
  498. }
  499. b := d.skipWhitespace(false)
  500. if b == 'f' {
  501. d.readStrIdx(5, 9) // alse
  502. return false
  503. }
  504. if b == 't' {
  505. d.readStrIdx(1, 4) // rue
  506. return true
  507. }
  508. d.d.errorf("json: decode bool: got first char %c", b)
  509. return false // "unreachable"
  510. }
  511. func (d *jsonDecDriver) ReadMapStart() int {
  512. if c := d.s.sc.sep(); c != 0 {
  513. d.expectChar(c)
  514. }
  515. d.s.start('}')
  516. d.expectChar('{')
  517. d.ct = valueTypeMap
  518. return -1
  519. }
  520. func (d *jsonDecDriver) ReadArrayStart() int {
  521. if c := d.s.sc.sep(); c != 0 {
  522. d.expectChar(c)
  523. }
  524. d.s.start(']')
  525. d.expectChar('[')
  526. d.ct = valueTypeArray
  527. return -1
  528. }
  529. func (d *jsonDecDriver) ReadEnd() {
  530. b := d.s.sc.st
  531. d.s.end()
  532. d.expectChar(b)
  533. }
  534. func (d *jsonDecDriver) expectChar(c uint8) {
  535. b := d.skipWhitespace(false)
  536. if b != c {
  537. d.d.errorf("json: expect char '%c' but got char '%c'", c, b)
  538. return
  539. }
  540. if jsonTrackSkipWhitespace {
  541. d.wsSkipped = false
  542. }
  543. }
  544. // func (d *jsonDecDriver) maybeChar(c uint8) {
  545. // b := d.skipWhitespace(false)
  546. // if b != c {
  547. // d.r.unreadn1()
  548. // return
  549. // }
  550. // if jsonTrackSkipWhitespace {
  551. // d.wsSkipped = false
  552. // }
  553. // }
  554. func (d *jsonDecDriver) IsContainerType(vt valueType) bool {
  555. // check container type by checking the first char
  556. if d.ct == valueTypeUnset {
  557. b := d.skipWhitespace(true)
  558. if b == '{' {
  559. d.ct = valueTypeMap
  560. } else if b == '[' {
  561. d.ct = valueTypeArray
  562. } else if b == 'n' {
  563. d.ct = valueTypeNil
  564. } else if b == '"' {
  565. d.ct = valueTypeString
  566. }
  567. }
  568. if vt == valueTypeNil || vt == valueTypeBytes || vt == valueTypeString ||
  569. vt == valueTypeArray || vt == valueTypeMap {
  570. return d.ct == vt
  571. }
  572. // ugorji: made switch into conditionals, so that IsContainerType can be inlined.
  573. // switch vt {
  574. // case valueTypeNil, valueTypeBytes, valueTypeString, valueTypeArray, valueTypeMap:
  575. // return d.ct == vt
  576. // }
  577. d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  578. return false // "unreachable"
  579. }
  580. func (d *jsonDecDriver) decNum(storeBytes bool) {
  581. // storeBytes = true // TODO: remove.
  582. // If it is has a . or an e|E, decode as a float; else decode as an int.
  583. b := d.skipWhitespace(false)
  584. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  585. d.d.errorf("json: decNum: got first char '%c'", b)
  586. return
  587. }
  588. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  589. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  590. // var n jsonNum // create stack-copy jsonNum, and set to pointer at end.
  591. // n.bytes = d.n.bytes[:0]
  592. n := &d.n
  593. n.reset()
  594. // The format of a number is as below:
  595. // parsing: sign? digit* dot? digit* e? sign? digit*
  596. // states: 0 1* 2 3* 4 5* 6 7
  597. // We honor this state so we can break correctly.
  598. var state uint8 = 0
  599. var eNeg bool
  600. var e int16
  601. var eof bool
  602. LOOP:
  603. for !eof {
  604. // fmt.Printf("LOOP: b: %q\n", b)
  605. switch b {
  606. case '+':
  607. switch state {
  608. case 0:
  609. state = 2
  610. // do not add sign to the slice ...
  611. b, eof = d.r.readn1eof()
  612. continue
  613. case 6: // typ = jsonNumFloat
  614. state = 7
  615. default:
  616. break LOOP
  617. }
  618. case '-':
  619. switch state {
  620. case 0:
  621. state = 2
  622. n.neg = true
  623. // do not add sign to the slice ...
  624. b, eof = d.r.readn1eof()
  625. continue
  626. case 6: // typ = jsonNumFloat
  627. eNeg = true
  628. state = 7
  629. default:
  630. break LOOP
  631. }
  632. case '.':
  633. switch state {
  634. case 0, 2: // typ = jsonNumFloat
  635. state = 4
  636. n.dot = true
  637. default:
  638. break LOOP
  639. }
  640. case 'e', 'E':
  641. switch state {
  642. case 0, 2, 4: // typ = jsonNumFloat
  643. state = 6
  644. // n.mantissaEndIndex = int16(len(n.bytes))
  645. n.explicitExponent = true
  646. default:
  647. break LOOP
  648. }
  649. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  650. switch state {
  651. case 0:
  652. state = 2
  653. fallthrough
  654. case 2:
  655. fallthrough
  656. case 4:
  657. if n.dot {
  658. n.exponent--
  659. }
  660. if n.mantissa >= jsonNumUintCutoff {
  661. n.manOverflow = true
  662. break
  663. }
  664. v := uint64(b - '0')
  665. n.mantissa *= 10
  666. if v != 0 {
  667. n1 := n.mantissa + v
  668. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  669. n.manOverflow = true // n+v overflows
  670. break
  671. }
  672. n.mantissa = n1
  673. }
  674. case 6:
  675. state = 7
  676. fallthrough
  677. case 7:
  678. if !(b == '0' && e == 0) {
  679. e = e*10 + int16(b-'0')
  680. }
  681. default:
  682. break LOOP
  683. }
  684. default:
  685. break LOOP
  686. }
  687. if storeBytes {
  688. n.bytes = append(n.bytes, b)
  689. }
  690. b, eof = d.r.readn1eof()
  691. }
  692. if jsonTruncateMantissa && n.mantissa != 0 {
  693. for n.mantissa%10 == 0 {
  694. n.mantissa /= 10
  695. n.exponent++
  696. }
  697. }
  698. if e != 0 {
  699. if eNeg {
  700. n.exponent -= e
  701. } else {
  702. n.exponent += e
  703. }
  704. }
  705. // d.n = n
  706. if !eof {
  707. d.r.unreadn1()
  708. }
  709. if jsonTrackSkipWhitespace {
  710. d.wsSkipped = false
  711. }
  712. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  713. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  714. return
  715. }
  716. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  717. if c := d.s.sc.sep(); c != 0 {
  718. d.expectChar(c)
  719. }
  720. d.decNum(false)
  721. n := &d.n
  722. if n.manOverflow {
  723. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  724. return
  725. }
  726. var u uint64
  727. if n.exponent == 0 {
  728. u = n.mantissa
  729. } else if n.exponent < 0 {
  730. d.d.errorf("json: fractional integer")
  731. return
  732. } else if n.exponent > 0 {
  733. var overflow bool
  734. if u, overflow = n.uintExp(); overflow {
  735. d.d.errorf("json: overflow integer")
  736. return
  737. }
  738. }
  739. i = int64(u)
  740. if n.neg {
  741. i = -i
  742. }
  743. if chkOvf.Int(i, bitsize) {
  744. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  745. return
  746. }
  747. // fmt.Printf("DecodeInt: %v\n", i)
  748. return
  749. }
  750. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  751. if c := d.s.sc.sep(); c != 0 {
  752. d.expectChar(c)
  753. }
  754. d.decNum(false)
  755. n := &d.n
  756. if n.neg {
  757. d.d.errorf("json: unsigned integer cannot be negative")
  758. return
  759. }
  760. if n.manOverflow {
  761. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  762. return
  763. }
  764. if n.exponent == 0 {
  765. u = n.mantissa
  766. } else if n.exponent < 0 {
  767. d.d.errorf("json: fractional integer")
  768. return
  769. } else if n.exponent > 0 {
  770. var overflow bool
  771. if u, overflow = n.uintExp(); overflow {
  772. d.d.errorf("json: overflow integer")
  773. return
  774. }
  775. }
  776. if chkOvf.Uint(u, bitsize) {
  777. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  778. return
  779. }
  780. // fmt.Printf("DecodeUint: %v\n", u)
  781. return
  782. }
  783. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  784. if c := d.s.sc.sep(); c != 0 {
  785. d.expectChar(c)
  786. }
  787. d.decNum(true)
  788. n := &d.n
  789. f = n.floatVal()
  790. if chkOverflow32 && chkOvf.Float32(f) {
  791. d.d.errorf("json: overflow float32: %v, %s", f, n.bytes)
  792. return
  793. }
  794. return
  795. }
  796. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  797. // No need to call sep here, as d.d.decode() handles it
  798. // if c := d.s.sc.sep(); c != 0 {
  799. // d.expectChar(c)
  800. // }
  801. if ext == nil {
  802. re := rv.(*RawExt)
  803. re.Tag = xtag
  804. d.d.decode(&re.Value)
  805. } else {
  806. var v interface{}
  807. d.d.decode(&v)
  808. ext.UpdateExt(rv, v)
  809. }
  810. return
  811. }
  812. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  813. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  814. if !isstring && d.se.i != nil {
  815. bsOut = bs
  816. d.DecodeExt(&bsOut, 0, &d.se)
  817. return
  818. }
  819. if c := d.s.sc.sep(); c != 0 {
  820. d.expectChar(c)
  821. }
  822. // zerocopy doesn't matter for json, as the bytes must be parsed.
  823. bs0 := d.appendStringAsBytes(d.b[:0])
  824. if isstring {
  825. return bs0
  826. }
  827. slen := base64.StdEncoding.DecodedLen(len(bs0))
  828. if cap(bs) >= slen {
  829. bsOut = bs[:slen]
  830. } else {
  831. bsOut = make([]byte, slen)
  832. }
  833. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  834. if err != nil {
  835. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  836. return nil
  837. }
  838. if slen != slen2 {
  839. bsOut = bsOut[:slen2]
  840. }
  841. return
  842. }
  843. func (d *jsonDecDriver) DecodeString() (s string) {
  844. if c := d.s.sc.sep(); c != 0 {
  845. d.expectChar(c)
  846. }
  847. return string(d.appendStringAsBytes(d.b[:0]))
  848. }
  849. func (d *jsonDecDriver) appendStringAsBytes(v []byte) []byte {
  850. d.expectChar('"')
  851. for {
  852. c := d.r.readn1()
  853. if c == '"' {
  854. break
  855. } else if c == '\\' {
  856. c = d.r.readn1()
  857. switch c {
  858. case '"', '\\', '/', '\'':
  859. v = append(v, c)
  860. case 'b':
  861. v = append(v, '\b')
  862. case 'f':
  863. v = append(v, '\f')
  864. case 'n':
  865. v = append(v, '\n')
  866. case 'r':
  867. v = append(v, '\r')
  868. case 't':
  869. v = append(v, '\t')
  870. case 'u':
  871. rr := d.jsonU4(false)
  872. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  873. if utf16.IsSurrogate(rr) {
  874. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  875. }
  876. w2 := utf8.EncodeRune(d.bstr[:], rr)
  877. v = append(v, d.bstr[:w2]...)
  878. default:
  879. d.d.errorf("json: unsupported escaped value: %c", c)
  880. return nil
  881. }
  882. } else {
  883. v = append(v, c)
  884. }
  885. }
  886. if jsonTrackSkipWhitespace {
  887. d.wsSkipped = false
  888. }
  889. return v
  890. }
  891. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  892. if checkSlashU && !(d.r.readn1() == '\\' && d.r.readn1() == 'u') {
  893. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  894. return 0
  895. }
  896. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  897. var u uint32
  898. for i := 0; i < 4; i++ {
  899. v := d.r.readn1()
  900. if '0' <= v && v <= '9' {
  901. v = v - '0'
  902. } else if 'a' <= v && v <= 'z' {
  903. v = v - 'a' + 10
  904. } else if 'A' <= v && v <= 'Z' {
  905. v = v - 'A' + 10
  906. } else {
  907. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  908. return 0
  909. }
  910. u = u*16 + uint32(v)
  911. }
  912. return rune(u)
  913. }
  914. func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
  915. if c := d.s.sc.sep(); c != 0 {
  916. d.expectChar(c)
  917. }
  918. n := d.skipWhitespace(true)
  919. switch n {
  920. case 'n':
  921. d.readStrIdx(9, 13) // null
  922. vt = valueTypeNil
  923. case 'f':
  924. d.readStrIdx(4, 9) // false
  925. vt = valueTypeBool
  926. v = false
  927. case 't':
  928. d.readStrIdx(0, 4) // true
  929. vt = valueTypeBool
  930. v = true
  931. case '{':
  932. vt = valueTypeMap
  933. decodeFurther = true
  934. case '[':
  935. vt = valueTypeArray
  936. decodeFurther = true
  937. case '"':
  938. vt = valueTypeString
  939. v = string(d.appendStringAsBytes(d.b[:0])) // same as d.DecodeString(), but skipping sep() call.
  940. default: // number
  941. d.decNum(true)
  942. n := &d.n
  943. // if the string had a any of [.eE], then decode as float.
  944. switch {
  945. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  946. vt = valueTypeFloat
  947. v = n.floatVal()
  948. case n.exponent == 0:
  949. u := n.mantissa
  950. switch {
  951. case n.neg:
  952. vt = valueTypeInt
  953. v = -int64(u)
  954. case d.h.SignedInteger:
  955. vt = valueTypeInt
  956. v = int64(u)
  957. default:
  958. vt = valueTypeUint
  959. v = u
  960. }
  961. default:
  962. u, overflow := n.uintExp()
  963. switch {
  964. case overflow:
  965. vt = valueTypeFloat
  966. v = n.floatVal()
  967. case n.neg:
  968. vt = valueTypeInt
  969. v = -int64(u)
  970. case d.h.SignedInteger:
  971. vt = valueTypeInt
  972. v = int64(u)
  973. default:
  974. vt = valueTypeUint
  975. v = u
  976. }
  977. }
  978. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  979. }
  980. if decodeFurther {
  981. d.s.sc.retryRead()
  982. }
  983. return
  984. }
  985. //----------------------
  986. // JsonHandle is a handle for JSON encoding format.
  987. //
  988. // Json is comprehensively supported:
  989. // - decodes numbers into interface{} as int, uint or float64
  990. // - configurable way to encode/decode []byte .
  991. // by default, encodes and decodes []byte using base64 Std Encoding
  992. // - UTF-8 support for encoding and decoding
  993. //
  994. // It has better performance than the json library in the standard library,
  995. // by leveraging the performance improvements of the codec library and
  996. // minimizing allocations.
  997. //
  998. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  999. // reading multiple values from a stream containing json and non-json content.
  1000. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1001. // all from the same stream in sequence.
  1002. type JsonHandle struct {
  1003. BasicHandle
  1004. textEncodingType
  1005. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1006. // If not configured, raw bytes are encoded to/from base64 text.
  1007. RawBytesExt InterfaceExt
  1008. }
  1009. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1010. hd := jsonEncDriver{e: e, w: e.w, h: h}
  1011. hd.se.i = h.RawBytesExt
  1012. return &hd
  1013. }
  1014. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1015. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1016. hd := jsonDecDriver{d: d, r: d.r, h: h}
  1017. hd.se.i = h.RawBytesExt
  1018. hd.n.bytes = d.b[:]
  1019. return &hd
  1020. }
  1021. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1022. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1023. }
  1024. var jsonEncodeTerminate = []byte{' '}
  1025. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1026. return jsonEncodeTerminate
  1027. }
  1028. var _ decDriver = (*jsonDecDriver)(nil)
  1029. var _ encDriver = (*jsonEncDriver)(nil)