json.go 28 KB

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