json.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  183. e.w.writen1('"')
  184. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  185. e.w.writen1('"')
  186. return
  187. }
  188. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  189. }
  190. func (e *jsonEncDriver) EncodeUint(v uint64) {
  191. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  192. e.w.writen1('"')
  193. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  194. e.w.writen1('"')
  195. return
  196. }
  197. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  198. }
  199. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  200. if v := ext.ConvertExt(rv); v == nil {
  201. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  202. } else {
  203. en.encode(v)
  204. }
  205. }
  206. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  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. en.encode(re.Value)
  212. }
  213. }
  214. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  215. if e.d {
  216. e.dl++
  217. }
  218. e.w.writen1('[')
  219. e.c = containerArrayStart
  220. }
  221. func (e *jsonEncDriver) EncodeMapStart(length int) {
  222. if e.d {
  223. e.dl++
  224. }
  225. e.w.writen1('{')
  226. e.c = containerMapStart
  227. }
  228. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  229. // e.w.writestr(strconv.Quote(v))
  230. e.quoteStr(v)
  231. }
  232. func (e *jsonEncDriver) EncodeSymbol(v string) {
  233. // e.EncodeString(c_UTF8, v)
  234. e.quoteStr(v)
  235. }
  236. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  237. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  238. if c == c_RAW && e.se.i != nil {
  239. e.EncodeExt(v, 0, &e.se, e.e)
  240. return
  241. }
  242. if c == c_RAW {
  243. slen := base64.StdEncoding.EncodedLen(len(v))
  244. if cap(e.bs) >= slen {
  245. e.bs = e.bs[:slen]
  246. } else {
  247. e.bs = make([]byte, slen)
  248. }
  249. base64.StdEncoding.Encode(e.bs, v)
  250. e.w.writen1('"')
  251. e.w.writeb(e.bs)
  252. e.w.writen1('"')
  253. } else {
  254. // e.EncodeString(c, string(v))
  255. e.quoteStr(stringView(v))
  256. }
  257. }
  258. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  259. e.w.writeb(v)
  260. }
  261. func (e *jsonEncDriver) quoteStr(s string) {
  262. // adapted from std pkg encoding/json
  263. const hex = "0123456789abcdef"
  264. w := e.w
  265. w.writen1('"')
  266. start := 0
  267. for i := 0; i < len(s); {
  268. if b := s[i]; b < utf8.RuneSelf {
  269. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  270. i++
  271. continue
  272. }
  273. if start < i {
  274. w.writestr(s[start:i])
  275. }
  276. switch b {
  277. case '\\', '"':
  278. w.writen2('\\', b)
  279. case '\n':
  280. w.writen2('\\', 'n')
  281. case '\r':
  282. w.writen2('\\', 'r')
  283. case '\b':
  284. w.writen2('\\', 'b')
  285. case '\f':
  286. w.writen2('\\', 'f')
  287. case '\t':
  288. w.writen2('\\', 't')
  289. default:
  290. // encode all bytes < 0x20 (except \r, \n).
  291. // also encode < > & to prevent security holes when served to some browsers.
  292. w.writestr(`\u00`)
  293. w.writen2(hex[b>>4], hex[b&0xF])
  294. }
  295. i++
  296. start = i
  297. continue
  298. }
  299. c, size := utf8.DecodeRuneInString(s[i:])
  300. if c == utf8.RuneError && size == 1 {
  301. if start < i {
  302. w.writestr(s[start:i])
  303. }
  304. w.writestr(`\ufffd`)
  305. i += size
  306. start = i
  307. continue
  308. }
  309. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  310. // Both technically valid JSON, but bomb on JSONP, so fix here.
  311. if c == '\u2028' || c == '\u2029' {
  312. if start < i {
  313. w.writestr(s[start:i])
  314. }
  315. w.writestr(`\u202`)
  316. w.writen1(hex[c&0xF])
  317. i += size
  318. start = i
  319. continue
  320. }
  321. i += size
  322. }
  323. if start < len(s) {
  324. w.writestr(s[start:])
  325. }
  326. w.writen1('"')
  327. }
  328. //--------------------------------
  329. type jsonNum struct {
  330. // bytes []byte // may have [+-.eE0-9]
  331. mantissa uint64 // where mantissa ends, and maybe dot begins.
  332. exponent int16 // exponent value.
  333. manOverflow bool
  334. neg bool // started with -. No initial sign in the bytes above.
  335. dot bool // has dot
  336. explicitExponent bool // explicit exponent
  337. }
  338. func (x *jsonNum) reset() {
  339. x.manOverflow = false
  340. x.neg = false
  341. x.dot = false
  342. x.explicitExponent = false
  343. x.mantissa = 0
  344. x.exponent = 0
  345. }
  346. // uintExp is called only if exponent > 0.
  347. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  348. n = x.mantissa
  349. e := x.exponent
  350. if e >= int16(len(jsonUint64Pow10)) {
  351. overflow = true
  352. return
  353. }
  354. n *= jsonUint64Pow10[e]
  355. if n < x.mantissa || n > jsonNumUintMaxVal {
  356. overflow = true
  357. return
  358. }
  359. return
  360. // for i := int16(0); i < e; i++ {
  361. // if n >= jsonNumUintCutoff {
  362. // overflow = true
  363. // return
  364. // }
  365. // n *= 10
  366. // }
  367. // return
  368. }
  369. // these constants are only used withn floatVal.
  370. // They are brought out, so that floatVal can be inlined.
  371. const (
  372. jsonUint64MantissaBits = 52
  373. jsonMaxExponent = int16(len(jsonFloat64Pow10)) - 1
  374. )
  375. func (x *jsonNum) floatVal() (f float64, parseUsingStrConv bool) {
  376. // We do not want to lose precision.
  377. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  378. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  379. // We expect up to 99.... (19 digits)
  380. // - The mantissa cannot fit into a 52 bits of uint64
  381. // - The exponent is beyond our scope ie beyong 22.
  382. parseUsingStrConv = x.manOverflow ||
  383. x.exponent > jsonMaxExponent ||
  384. (x.exponent < 0 && -(x.exponent) > jsonMaxExponent) ||
  385. x.mantissa>>jsonUint64MantissaBits != 0
  386. if parseUsingStrConv {
  387. return
  388. }
  389. // all good. so handle parse here.
  390. f = float64(x.mantissa)
  391. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  392. if x.neg {
  393. f = -f
  394. }
  395. if x.exponent > 0 {
  396. f *= jsonFloat64Pow10[x.exponent]
  397. } else if x.exponent < 0 {
  398. f /= jsonFloat64Pow10[-x.exponent]
  399. }
  400. return
  401. }
  402. type jsonDecDriver struct {
  403. noBuiltInTypes
  404. d *Decoder
  405. h *JsonHandle
  406. r decReader
  407. c containerState
  408. // tok is used to store the token read right after skipWhiteSpace.
  409. tok uint8
  410. bstr [8]byte // scratch used for string \UXXX parsing
  411. b [64]byte // scratch, used for parsing strings or numbers
  412. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  413. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  414. se setExtWrapper
  415. n jsonNum
  416. }
  417. func jsonIsWS(b byte) bool {
  418. return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  419. }
  420. // // This will skip whitespace characters and return the next byte to read.
  421. // // The next byte determines what the value will be one of.
  422. // func (d *jsonDecDriver) skipWhitespace() {
  423. // // fast-path: do not enter loop. Just check first (in case no whitespace).
  424. // b := d.r.readn1()
  425. // if jsonIsWS(b) {
  426. // r := d.r
  427. // for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  428. // }
  429. // }
  430. // d.tok = b
  431. // }
  432. func (d *jsonDecDriver) uncacheRead() {
  433. if d.tok != 0 {
  434. d.r.unreadn1()
  435. d.tok = 0
  436. }
  437. }
  438. func (d *jsonDecDriver) sendContainerState(c containerState) {
  439. if d.tok == 0 {
  440. var b byte
  441. r := d.r
  442. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  443. }
  444. d.tok = b
  445. }
  446. var xc uint8 // char expected
  447. if c == containerMapKey {
  448. if d.c != containerMapStart {
  449. xc = ','
  450. }
  451. } else if c == containerMapValue {
  452. xc = ':'
  453. } else if c == containerMapEnd {
  454. xc = '}'
  455. } else if c == containerArrayElem {
  456. if d.c != containerArrayStart {
  457. xc = ','
  458. }
  459. } else if c == containerArrayEnd {
  460. xc = ']'
  461. }
  462. if xc != 0 {
  463. if d.tok != xc {
  464. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  465. }
  466. d.tok = 0
  467. }
  468. d.c = c
  469. }
  470. func (d *jsonDecDriver) CheckBreak() bool {
  471. if d.tok == 0 {
  472. var b byte
  473. r := d.r
  474. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  475. }
  476. d.tok = b
  477. }
  478. if d.tok == '}' || d.tok == ']' {
  479. // d.tok = 0 // only checking, not consuming
  480. return true
  481. }
  482. return false
  483. }
  484. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  485. bs := d.r.readx(int(toIdx - fromIdx))
  486. d.tok = 0
  487. if jsonValidateSymbols {
  488. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  489. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  490. return
  491. }
  492. }
  493. }
  494. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  495. if d.tok == 0 {
  496. var b byte
  497. r := d.r
  498. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  499. }
  500. d.tok = b
  501. }
  502. if d.tok == 'n' {
  503. d.readStrIdx(10, 13) // ull
  504. return true
  505. }
  506. return false
  507. }
  508. func (d *jsonDecDriver) DecodeBool() bool {
  509. if d.tok == 0 {
  510. var b byte
  511. r := d.r
  512. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  513. }
  514. d.tok = b
  515. }
  516. if d.tok == 'f' {
  517. d.readStrIdx(5, 9) // alse
  518. return false
  519. }
  520. if d.tok == 't' {
  521. d.readStrIdx(1, 4) // rue
  522. return true
  523. }
  524. d.d.errorf("json: decode bool: got first char %c", d.tok)
  525. return false // "unreachable"
  526. }
  527. func (d *jsonDecDriver) ReadMapStart() int {
  528. if d.tok == 0 {
  529. var b byte
  530. r := d.r
  531. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  532. }
  533. d.tok = b
  534. }
  535. if d.tok != '{' {
  536. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  537. }
  538. d.tok = 0
  539. d.c = containerMapStart
  540. return -1
  541. }
  542. func (d *jsonDecDriver) ReadArrayStart() int {
  543. if d.tok == 0 {
  544. var b byte
  545. r := d.r
  546. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  547. }
  548. d.tok = b
  549. }
  550. if d.tok != '[' {
  551. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  552. }
  553. d.tok = 0
  554. d.c = containerArrayStart
  555. return -1
  556. }
  557. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  558. // check container type by checking the first char
  559. if d.tok == 0 {
  560. var b byte
  561. r := d.r
  562. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  563. }
  564. d.tok = b
  565. }
  566. if b := d.tok; b == '{' {
  567. return valueTypeMap
  568. } else if b == '[' {
  569. return valueTypeArray
  570. } else if b == 'n' {
  571. return valueTypeNil
  572. } else if b == '"' {
  573. return valueTypeString
  574. }
  575. return valueTypeUnset
  576. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  577. // return false // "unreachable"
  578. }
  579. func (d *jsonDecDriver) decNum(storeBytes bool) {
  580. // If it is has a . or an e|E, decode as a float; else decode as an int.
  581. if d.tok == 0 {
  582. var b byte
  583. r := d.r
  584. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  585. }
  586. d.tok = b
  587. }
  588. b := d.tok
  589. var str bool
  590. if b == '"' {
  591. str = true
  592. b = d.r.readn1()
  593. }
  594. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  595. d.d.errorf("json: decNum: got first char '%c'", b)
  596. return
  597. }
  598. d.tok = 0
  599. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  600. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  601. n := &d.n
  602. r := d.r
  603. n.reset()
  604. d.bs = d.bs[:0]
  605. if str && storeBytes {
  606. d.bs = append(d.bs, '"')
  607. }
  608. // The format of a number is as below:
  609. // parsing: sign? digit* dot? digit* e? sign? digit*
  610. // states: 0 1* 2 3* 4 5* 6 7
  611. // We honor this state so we can break correctly.
  612. var state uint8 = 0
  613. var eNeg bool
  614. var e int16
  615. var eof bool
  616. LOOP:
  617. for !eof {
  618. // fmt.Printf("LOOP: b: %q\n", b)
  619. switch b {
  620. case '+':
  621. switch state {
  622. case 0:
  623. state = 2
  624. // do not add sign to the slice ...
  625. b, eof = r.readn1eof()
  626. continue
  627. case 6: // typ = jsonNumFloat
  628. state = 7
  629. default:
  630. break LOOP
  631. }
  632. case '-':
  633. switch state {
  634. case 0:
  635. state = 2
  636. n.neg = true
  637. // do not add sign to the slice ...
  638. b, eof = r.readn1eof()
  639. continue
  640. case 6: // typ = jsonNumFloat
  641. eNeg = true
  642. state = 7
  643. default:
  644. break LOOP
  645. }
  646. case '.':
  647. switch state {
  648. case 0, 2: // typ = jsonNumFloat
  649. state = 4
  650. n.dot = true
  651. default:
  652. break LOOP
  653. }
  654. case 'e', 'E':
  655. switch state {
  656. case 0, 2, 4: // typ = jsonNumFloat
  657. state = 6
  658. // n.mantissaEndIndex = int16(len(n.bytes))
  659. n.explicitExponent = true
  660. default:
  661. break LOOP
  662. }
  663. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  664. switch state {
  665. case 0:
  666. state = 2
  667. fallthrough
  668. case 2:
  669. fallthrough
  670. case 4:
  671. if n.dot {
  672. n.exponent--
  673. }
  674. if n.mantissa >= jsonNumUintCutoff {
  675. n.manOverflow = true
  676. break
  677. }
  678. v := uint64(b - '0')
  679. n.mantissa *= 10
  680. if v != 0 {
  681. n1 := n.mantissa + v
  682. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  683. n.manOverflow = true // n+v overflows
  684. break
  685. }
  686. n.mantissa = n1
  687. }
  688. case 6:
  689. state = 7
  690. fallthrough
  691. case 7:
  692. if !(b == '0' && e == 0) {
  693. e = e*10 + int16(b-'0')
  694. }
  695. default:
  696. break LOOP
  697. }
  698. case '"':
  699. if str {
  700. if storeBytes {
  701. d.bs = append(d.bs, '"')
  702. }
  703. b, eof = r.readn1eof()
  704. }
  705. break LOOP
  706. default:
  707. break LOOP
  708. }
  709. if storeBytes {
  710. d.bs = append(d.bs, b)
  711. }
  712. b, eof = r.readn1eof()
  713. }
  714. if jsonTruncateMantissa && n.mantissa != 0 {
  715. for n.mantissa%10 == 0 {
  716. n.mantissa /= 10
  717. n.exponent++
  718. }
  719. }
  720. if e != 0 {
  721. if eNeg {
  722. n.exponent -= e
  723. } else {
  724. n.exponent += e
  725. }
  726. }
  727. // d.n = n
  728. if !eof {
  729. if jsonUnreadAfterDecNum {
  730. r.unreadn1()
  731. } else {
  732. if !jsonIsWS(b) {
  733. d.tok = b
  734. }
  735. }
  736. }
  737. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  738. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  739. return
  740. }
  741. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  742. d.decNum(false)
  743. n := &d.n
  744. if n.manOverflow {
  745. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  746. return
  747. }
  748. var u uint64
  749. if n.exponent == 0 {
  750. u = n.mantissa
  751. } else if n.exponent < 0 {
  752. d.d.errorf("json: fractional integer")
  753. return
  754. } else if n.exponent > 0 {
  755. var overflow bool
  756. if u, overflow = n.uintExp(); overflow {
  757. d.d.errorf("json: overflow integer")
  758. return
  759. }
  760. }
  761. i = int64(u)
  762. if n.neg {
  763. i = -i
  764. }
  765. if chkOvf.Int(i, bitsize) {
  766. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  767. return
  768. }
  769. // fmt.Printf("DecodeInt: %v\n", i)
  770. return
  771. }
  772. // floatVal MUST only be called after a decNum, as d.bs now contains the bytes of the number
  773. func (d *jsonDecDriver) floatVal() (f float64) {
  774. f, useStrConv := d.n.floatVal()
  775. if useStrConv {
  776. var err error
  777. if f, err = strconv.ParseFloat(stringView(d.bs), 64); err != nil {
  778. panic(fmt.Errorf("parse float: %s, %v", d.bs, err))
  779. }
  780. if d.n.neg {
  781. f = -f
  782. }
  783. }
  784. return
  785. }
  786. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  787. d.decNum(false)
  788. n := &d.n
  789. if n.neg {
  790. d.d.errorf("json: unsigned integer cannot be negative")
  791. return
  792. }
  793. if n.manOverflow {
  794. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  795. return
  796. }
  797. if n.exponent == 0 {
  798. u = n.mantissa
  799. } else if n.exponent < 0 {
  800. d.d.errorf("json: fractional integer")
  801. return
  802. } else if n.exponent > 0 {
  803. var overflow bool
  804. if u, overflow = n.uintExp(); overflow {
  805. d.d.errorf("json: overflow integer")
  806. return
  807. }
  808. }
  809. if chkOvf.Uint(u, bitsize) {
  810. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  811. return
  812. }
  813. // fmt.Printf("DecodeUint: %v\n", u)
  814. return
  815. }
  816. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  817. d.decNum(true)
  818. f = d.floatVal()
  819. if chkOverflow32 && chkOvf.Float32(f) {
  820. d.d.errorf("json: overflow float32: %v, %s", f, d.bs)
  821. return
  822. }
  823. return
  824. }
  825. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  826. if ext == nil {
  827. re := rv.(*RawExt)
  828. re.Tag = xtag
  829. d.d.decode(&re.Value)
  830. } else {
  831. var v interface{}
  832. d.d.decode(&v)
  833. ext.UpdateExt(rv, v)
  834. }
  835. return
  836. }
  837. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  838. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  839. if !isstring && d.se.i != nil {
  840. bsOut = bs
  841. d.DecodeExt(&bsOut, 0, &d.se)
  842. return
  843. }
  844. d.appendStringAsBytes()
  845. // if isstring, then just return the bytes, even if it is using the scratch buffer.
  846. // the bytes will be converted to a string as needed.
  847. if isstring {
  848. return d.bs
  849. }
  850. bs0 := d.bs
  851. slen := base64.StdEncoding.DecodedLen(len(bs0))
  852. if slen <= cap(bs) {
  853. bsOut = bs[:slen]
  854. } else if zerocopy && slen <= cap(d.b2) {
  855. bsOut = d.b2[:slen]
  856. } else {
  857. bsOut = make([]byte, slen)
  858. }
  859. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  860. if err != nil {
  861. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  862. return nil
  863. }
  864. if slen != slen2 {
  865. bsOut = bsOut[:slen2]
  866. }
  867. return
  868. }
  869. func (d *jsonDecDriver) DecodeString() (s string) {
  870. d.appendStringAsBytes()
  871. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  872. if d.c == containerMapKey {
  873. return d.d.string(d.bs)
  874. }
  875. return string(d.bs)
  876. }
  877. func (d *jsonDecDriver) appendStringAsBytes() {
  878. if d.tok == 0 {
  879. var b byte
  880. r := d.r
  881. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  882. }
  883. d.tok = b
  884. }
  885. if d.tok != '"' {
  886. d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  887. }
  888. d.tok = 0
  889. v := d.bs[:0]
  890. var c uint8
  891. r := d.r
  892. for {
  893. c = r.readn1()
  894. if c == '"' {
  895. break
  896. } else if c == '\\' {
  897. c = r.readn1()
  898. switch c {
  899. case '"', '\\', '/', '\'':
  900. v = append(v, c)
  901. case 'b':
  902. v = append(v, '\b')
  903. case 'f':
  904. v = append(v, '\f')
  905. case 'n':
  906. v = append(v, '\n')
  907. case 'r':
  908. v = append(v, '\r')
  909. case 't':
  910. v = append(v, '\t')
  911. case 'u':
  912. rr := d.jsonU4(false)
  913. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  914. if utf16.IsSurrogate(rr) {
  915. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  916. }
  917. w2 := utf8.EncodeRune(d.bstr[:], rr)
  918. v = append(v, d.bstr[:w2]...)
  919. default:
  920. d.d.errorf("json: unsupported escaped value: %c", c)
  921. }
  922. } else {
  923. v = append(v, c)
  924. }
  925. }
  926. d.bs = v
  927. }
  928. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  929. r := d.r
  930. if checkSlashU && !(r.readn1() == '\\' && r.readn1() == 'u') {
  931. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  932. return 0
  933. }
  934. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  935. var u uint32
  936. for i := 0; i < 4; i++ {
  937. v := r.readn1()
  938. if '0' <= v && v <= '9' {
  939. v = v - '0'
  940. } else if 'a' <= v && v <= 'z' {
  941. v = v - 'a' + 10
  942. } else if 'A' <= v && v <= 'Z' {
  943. v = v - 'A' + 10
  944. } else {
  945. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  946. return 0
  947. }
  948. u = u*16 + uint32(v)
  949. }
  950. return rune(u)
  951. }
  952. func (d *jsonDecDriver) DecodeNaked() {
  953. z := &d.d.n
  954. // var decodeFurther bool
  955. if d.tok == 0 {
  956. var b byte
  957. r := d.r
  958. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  959. }
  960. d.tok = b
  961. }
  962. switch d.tok {
  963. case 'n':
  964. d.readStrIdx(10, 13) // ull
  965. z.v = valueTypeNil
  966. case 'f':
  967. d.readStrIdx(5, 9) // alse
  968. z.v = valueTypeBool
  969. z.b = false
  970. case 't':
  971. d.readStrIdx(1, 4) // rue
  972. z.v = valueTypeBool
  973. z.b = true
  974. case '{':
  975. z.v = valueTypeMap
  976. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadMapStart
  977. // decodeFurther = true
  978. case '[':
  979. z.v = valueTypeArray
  980. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadArrayStart
  981. // decodeFurther = true
  982. case '"':
  983. z.v = valueTypeString
  984. z.s = d.DecodeString()
  985. default: // number
  986. d.decNum(true)
  987. n := &d.n
  988. // if the string had a any of [.eE], then decode as float.
  989. switch {
  990. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  991. z.v = valueTypeFloat
  992. z.f = d.floatVal()
  993. case n.exponent == 0:
  994. u := n.mantissa
  995. switch {
  996. case n.neg:
  997. z.v = valueTypeInt
  998. z.i = -int64(u)
  999. case d.h.SignedInteger:
  1000. z.v = valueTypeInt
  1001. z.i = int64(u)
  1002. default:
  1003. z.v = valueTypeUint
  1004. z.u = u
  1005. }
  1006. default:
  1007. u, overflow := n.uintExp()
  1008. switch {
  1009. case overflow:
  1010. z.v = valueTypeFloat
  1011. z.f = d.floatVal()
  1012. case n.neg:
  1013. z.v = valueTypeInt
  1014. z.i = -int64(u)
  1015. case d.h.SignedInteger:
  1016. z.v = valueTypeInt
  1017. z.i = int64(u)
  1018. default:
  1019. z.v = valueTypeUint
  1020. z.u = u
  1021. }
  1022. }
  1023. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  1024. }
  1025. // if decodeFurther {
  1026. // d.s.sc.retryRead()
  1027. // }
  1028. return
  1029. }
  1030. //----------------------
  1031. // JsonHandle is a handle for JSON encoding format.
  1032. //
  1033. // Json is comprehensively supported:
  1034. // - decodes numbers into interface{} as int, uint or float64
  1035. // - configurable way to encode/decode []byte .
  1036. // by default, encodes and decodes []byte using base64 Std Encoding
  1037. // - UTF-8 support for encoding and decoding
  1038. //
  1039. // It has better performance than the json library in the standard library,
  1040. // by leveraging the performance improvements of the codec library and
  1041. // minimizing allocations.
  1042. //
  1043. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1044. // reading multiple values from a stream containing json and non-json content.
  1045. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1046. // all from the same stream in sequence.
  1047. type JsonHandle struct {
  1048. textEncodingType
  1049. BasicHandle
  1050. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1051. // If not configured, raw bytes are encoded to/from base64 text.
  1052. RawBytesExt InterfaceExt
  1053. // Indent indicates how a value is encoded.
  1054. // - If positive, indent by that number of spaces.
  1055. // - If negative, indent by that number of tabs.
  1056. Indent int8
  1057. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1058. //
  1059. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1060. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1061. // This can be mitigated by configuring how to encode integers.
  1062. //
  1063. // IntegerAsString interpretes the following values:
  1064. // - if 'L', then encode integers > 2^53 as a json string.
  1065. // - if 'A', then encode all integers as a json string
  1066. // containing the exact integer representation as a decimal.
  1067. // - else encode all integers as a json number (default)
  1068. IntegerAsString uint8
  1069. }
  1070. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1071. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1072. }
  1073. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1074. hd := jsonEncDriver{e: e, h: h}
  1075. hd.bs = hd.b[:0]
  1076. hd.reset()
  1077. return &hd
  1078. }
  1079. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1080. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1081. hd := jsonDecDriver{d: d, h: h}
  1082. hd.bs = hd.b[:0]
  1083. hd.reset()
  1084. return &hd
  1085. }
  1086. func (e *jsonEncDriver) reset() {
  1087. e.w = e.e.w
  1088. e.se.i = e.h.RawBytesExt
  1089. if e.bs != nil {
  1090. e.bs = e.bs[:0]
  1091. }
  1092. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1093. e.c = 0
  1094. if e.h.Indent > 0 {
  1095. e.d = true
  1096. e.ds = jsonSpaces[:e.h.Indent]
  1097. } else if e.h.Indent < 0 {
  1098. e.d = true
  1099. e.dt = true
  1100. e.ds = jsonTabs[:-(e.h.Indent)]
  1101. }
  1102. }
  1103. func (d *jsonDecDriver) reset() {
  1104. d.r = d.d.r
  1105. d.se.i = d.h.RawBytesExt
  1106. if d.bs != nil {
  1107. d.bs = d.bs[:0]
  1108. }
  1109. d.c, d.tok = 0, 0
  1110. d.n.reset()
  1111. }
  1112. var jsonEncodeTerminate = []byte{' '}
  1113. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1114. return jsonEncodeTerminate
  1115. }
  1116. var _ decDriver = (*jsonDecDriver)(nil)
  1117. var _ encDriver = (*jsonEncDriver)(nil)