json.go 25 KB

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