json.go 25 KB

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