json.go 26 KB

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