json.go 27 KB

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