json.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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.bytes = x.bytes[:0]
  382. x.manOverflow = false
  383. x.neg = false
  384. x.dot = false
  385. x.explicitExponent = false
  386. x.mantissa = 0
  387. x.exponent = 0
  388. }
  389. // uintExp is called only if exponent > 0.
  390. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  391. n = x.mantissa
  392. e := x.exponent
  393. if e >= int16(len(jsonUint64Pow10)) {
  394. overflow = true
  395. return
  396. }
  397. n *= jsonUint64Pow10[e]
  398. if n < x.mantissa || n > jsonNumUintMaxVal {
  399. overflow = true
  400. return
  401. }
  402. return
  403. // for i := int16(0); i < e; i++ {
  404. // if n >= jsonNumUintCutoff {
  405. // overflow = true
  406. // return
  407. // }
  408. // n *= 10
  409. // }
  410. // return
  411. }
  412. func (x *jsonNum) floatVal() (f float64) {
  413. // We do not want to lose precision.
  414. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  415. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  416. // We expect up to 99.... (19 digits)
  417. // - The mantissa cannot fit into a 52 bits of uint64
  418. // - The exponent is beyond our scope ie beyong 22.
  419. const uint64MantissaBits = 52
  420. const maxExponent = int16(len(jsonFloat64Pow10)) - 1
  421. parseUsingStrConv := x.manOverflow ||
  422. x.exponent > maxExponent ||
  423. (x.exponent < 0 && -(x.exponent) > maxExponent) ||
  424. x.mantissa>>uint64MantissaBits != 0
  425. if parseUsingStrConv {
  426. var err error
  427. if f, err = strconv.ParseFloat(stringView(x.bytes), 64); err != nil {
  428. panic(fmt.Errorf("parse float: %s, %v", x.bytes, err))
  429. return
  430. }
  431. if x.neg {
  432. f = -f
  433. }
  434. return
  435. }
  436. // all good. so handle parse here.
  437. f = float64(x.mantissa)
  438. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  439. if x.neg {
  440. f = -f
  441. }
  442. if x.exponent > 0 {
  443. f *= jsonFloat64Pow10[x.exponent]
  444. } else if x.exponent < 0 {
  445. f /= jsonFloat64Pow10[-x.exponent]
  446. }
  447. return
  448. }
  449. type jsonDecDriver struct {
  450. d *Decoder
  451. h *JsonHandle
  452. r decReader // *bytesDecReader decReader
  453. ct valueType // container type. one of unset, array or map.
  454. bstr [8]byte // scratch used for string \UXXX parsing
  455. b [64]byte // scratch
  456. b2 [64]byte
  457. wsSkipped bool // whitespace skipped
  458. se setExtWrapper
  459. s jsonStack
  460. n jsonNum
  461. noBuiltInTypes
  462. }
  463. // This will skip whitespace characters and return the next byte to read.
  464. // The next byte determines what the value will be one of.
  465. func (d *jsonDecDriver) skipWhitespace(unread bool) (b byte) {
  466. // as initReadNext is not called all the time, we set ct to unSet whenever
  467. // we skipwhitespace, as this is the signal that something new is about to be read.
  468. d.ct = valueTypeUnset
  469. b = d.r.readn1()
  470. if !jsonTrackSkipWhitespace || !d.wsSkipped {
  471. for ; b == ' ' || b == '\t' || b == '\r' || b == '\n'; b = d.r.readn1() {
  472. }
  473. if jsonTrackSkipWhitespace {
  474. d.wsSkipped = true
  475. }
  476. }
  477. if unread {
  478. d.r.unreadn1()
  479. }
  480. return b
  481. }
  482. func (d *jsonDecDriver) CheckBreak() bool {
  483. b := d.skipWhitespace(true)
  484. return b == '}' || b == ']'
  485. }
  486. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  487. bs := d.r.readx(int(toIdx - fromIdx))
  488. if jsonValidateSymbols {
  489. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  490. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  491. return
  492. }
  493. }
  494. if jsonTrackSkipWhitespace {
  495. d.wsSkipped = false
  496. }
  497. }
  498. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  499. // we mustn't consume the state here, and end up trying to read separator twice.
  500. // Instead, we keep track of the state and restore it if we couldn't decode as nil.
  501. if c := d.s.sc.sep(); c != 0 {
  502. d.expectChar(c)
  503. }
  504. b := d.skipWhitespace(false)
  505. if b == 'n' {
  506. d.readStrIdx(10, 13) // ull
  507. d.ct = valueTypeNil
  508. return true
  509. }
  510. d.r.unreadn1()
  511. d.s.sc.retryRead()
  512. return false
  513. }
  514. func (d *jsonDecDriver) DecodeBool() bool {
  515. if c := d.s.sc.sep(); c != 0 {
  516. d.expectChar(c)
  517. }
  518. b := d.skipWhitespace(false)
  519. if b == 'f' {
  520. d.readStrIdx(5, 9) // alse
  521. return false
  522. }
  523. if b == 't' {
  524. d.readStrIdx(1, 4) // rue
  525. return true
  526. }
  527. d.d.errorf("json: decode bool: got first char %c", b)
  528. return false // "unreachable"
  529. }
  530. func (d *jsonDecDriver) ReadMapStart() int {
  531. if c := d.s.sc.sep(); c != 0 {
  532. d.expectChar(c)
  533. }
  534. d.s.start('}')
  535. d.expectChar('{')
  536. d.ct = valueTypeMap
  537. return -1
  538. }
  539. func (d *jsonDecDriver) ReadArrayStart() int {
  540. if c := d.s.sc.sep(); c != 0 {
  541. d.expectChar(c)
  542. }
  543. d.s.start(']')
  544. d.expectChar('[')
  545. d.ct = valueTypeArray
  546. return -1
  547. }
  548. func (d *jsonDecDriver) ReadEnd() {
  549. b := d.s.sc.st
  550. d.s.end()
  551. d.expectChar(b)
  552. }
  553. func (d *jsonDecDriver) expectChar(c uint8) {
  554. b := d.skipWhitespace(false)
  555. if b != c {
  556. d.d.errorf("json: expect char '%c' but got char '%c'", c, b)
  557. return
  558. }
  559. if jsonTrackSkipWhitespace {
  560. d.wsSkipped = false
  561. }
  562. }
  563. // func (d *jsonDecDriver) maybeChar(c uint8) {
  564. // b := d.skipWhitespace(false)
  565. // if b != c {
  566. // d.r.unreadn1()
  567. // return
  568. // }
  569. // if jsonTrackSkipWhitespace {
  570. // d.wsSkipped = false
  571. // }
  572. // }
  573. func (d *jsonDecDriver) IsContainerType(vt valueType) bool {
  574. // check container type by checking the first char
  575. if d.ct == valueTypeUnset {
  576. b := d.skipWhitespace(true)
  577. if b == '{' {
  578. d.ct = valueTypeMap
  579. } else if b == '[' {
  580. d.ct = valueTypeArray
  581. } else if b == 'n' {
  582. d.ct = valueTypeNil
  583. } else if b == '"' {
  584. d.ct = valueTypeString
  585. }
  586. }
  587. if vt == valueTypeNil || vt == valueTypeBytes || vt == valueTypeString ||
  588. vt == valueTypeArray || vt == valueTypeMap {
  589. return d.ct == vt
  590. }
  591. // ugorji: made switch into conditionals, so that IsContainerType can be inlined.
  592. // switch vt {
  593. // case valueTypeNil, valueTypeBytes, valueTypeString, valueTypeArray, valueTypeMap:
  594. // return d.ct == vt
  595. // }
  596. d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  597. return false // "unreachable"
  598. }
  599. func (d *jsonDecDriver) decNum(storeBytes bool) {
  600. // storeBytes = true // TODO: remove.
  601. // If it is has a . or an e|E, decode as a float; else decode as an int.
  602. b := d.skipWhitespace(false)
  603. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  604. d.d.errorf("json: decNum: got first char '%c'", b)
  605. return
  606. }
  607. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  608. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  609. // var n jsonNum // create stack-copy jsonNum, and set to pointer at end.
  610. // n.bytes = d.n.bytes[:0]
  611. n := &d.n
  612. n.reset()
  613. // The format of a number is as below:
  614. // parsing: sign? digit* dot? digit* e? sign? digit*
  615. // states: 0 1* 2 3* 4 5* 6 7
  616. // We honor this state so we can break correctly.
  617. var state uint8 = 0
  618. var eNeg bool
  619. var e int16
  620. var eof bool
  621. LOOP:
  622. for !eof {
  623. // fmt.Printf("LOOP: b: %q\n", b)
  624. switch b {
  625. case '+':
  626. switch state {
  627. case 0:
  628. state = 2
  629. // do not add sign to the slice ...
  630. b, eof = d.r.readn1eof()
  631. continue
  632. case 6: // typ = jsonNumFloat
  633. state = 7
  634. default:
  635. break LOOP
  636. }
  637. case '-':
  638. switch state {
  639. case 0:
  640. state = 2
  641. n.neg = true
  642. // do not add sign to the slice ...
  643. b, eof = d.r.readn1eof()
  644. continue
  645. case 6: // typ = jsonNumFloat
  646. eNeg = true
  647. state = 7
  648. default:
  649. break LOOP
  650. }
  651. case '.':
  652. switch state {
  653. case 0, 2: // typ = jsonNumFloat
  654. state = 4
  655. n.dot = true
  656. default:
  657. break LOOP
  658. }
  659. case 'e', 'E':
  660. switch state {
  661. case 0, 2, 4: // typ = jsonNumFloat
  662. state = 6
  663. // n.mantissaEndIndex = int16(len(n.bytes))
  664. n.explicitExponent = true
  665. default:
  666. break LOOP
  667. }
  668. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  669. switch state {
  670. case 0:
  671. state = 2
  672. fallthrough
  673. case 2:
  674. fallthrough
  675. case 4:
  676. if n.dot {
  677. n.exponent--
  678. }
  679. if n.mantissa >= jsonNumUintCutoff {
  680. n.manOverflow = true
  681. break
  682. }
  683. v := uint64(b - '0')
  684. n.mantissa *= 10
  685. if v != 0 {
  686. n1 := n.mantissa + v
  687. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  688. n.manOverflow = true // n+v overflows
  689. break
  690. }
  691. n.mantissa = n1
  692. }
  693. case 6:
  694. state = 7
  695. fallthrough
  696. case 7:
  697. if !(b == '0' && e == 0) {
  698. e = e*10 + int16(b-'0')
  699. }
  700. default:
  701. break LOOP
  702. }
  703. default:
  704. break LOOP
  705. }
  706. if storeBytes {
  707. n.bytes = append(n.bytes, b)
  708. }
  709. b, eof = d.r.readn1eof()
  710. }
  711. if jsonTruncateMantissa && n.mantissa != 0 {
  712. for n.mantissa%10 == 0 {
  713. n.mantissa /= 10
  714. n.exponent++
  715. }
  716. }
  717. if e != 0 {
  718. if eNeg {
  719. n.exponent -= e
  720. } else {
  721. n.exponent += e
  722. }
  723. }
  724. // d.n = n
  725. if !eof {
  726. d.r.unreadn1()
  727. }
  728. if jsonTrackSkipWhitespace {
  729. d.wsSkipped = false
  730. }
  731. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  732. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  733. return
  734. }
  735. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  736. if c := d.s.sc.sep(); c != 0 {
  737. d.expectChar(c)
  738. }
  739. d.decNum(false)
  740. n := &d.n
  741. if n.manOverflow {
  742. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  743. return
  744. }
  745. var u uint64
  746. if n.exponent == 0 {
  747. u = n.mantissa
  748. } else if n.exponent < 0 {
  749. d.d.errorf("json: fractional integer")
  750. return
  751. } else if n.exponent > 0 {
  752. var overflow bool
  753. if u, overflow = n.uintExp(); overflow {
  754. d.d.errorf("json: overflow integer")
  755. return
  756. }
  757. }
  758. i = int64(u)
  759. if n.neg {
  760. i = -i
  761. }
  762. if chkOvf.Int(i, bitsize) {
  763. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  764. return
  765. }
  766. // fmt.Printf("DecodeInt: %v\n", i)
  767. return
  768. }
  769. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  770. if c := d.s.sc.sep(); c != 0 {
  771. d.expectChar(c)
  772. }
  773. d.decNum(false)
  774. n := &d.n
  775. if n.neg {
  776. d.d.errorf("json: unsigned integer cannot be negative")
  777. return
  778. }
  779. if n.manOverflow {
  780. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  781. return
  782. }
  783. if n.exponent == 0 {
  784. u = n.mantissa
  785. } else if n.exponent < 0 {
  786. d.d.errorf("json: fractional integer")
  787. return
  788. } else if n.exponent > 0 {
  789. var overflow bool
  790. if u, overflow = n.uintExp(); overflow {
  791. d.d.errorf("json: overflow integer")
  792. return
  793. }
  794. }
  795. if chkOvf.Uint(u, bitsize) {
  796. d.d.errorf("json: overflow %v bits: %s", bitsize, n.bytes)
  797. return
  798. }
  799. // fmt.Printf("DecodeUint: %v\n", u)
  800. return
  801. }
  802. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  803. if c := d.s.sc.sep(); c != 0 {
  804. d.expectChar(c)
  805. }
  806. d.decNum(true)
  807. n := &d.n
  808. f = n.floatVal()
  809. if chkOverflow32 && chkOvf.Float32(f) {
  810. d.d.errorf("json: overflow float32: %v, %s", f, n.bytes)
  811. return
  812. }
  813. return
  814. }
  815. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  816. // No need to call sep here, as d.d.decode() handles it
  817. // if c := d.s.sc.sep(); c != 0 {
  818. // d.expectChar(c)
  819. // }
  820. if ext == nil {
  821. re := rv.(*RawExt)
  822. re.Tag = xtag
  823. d.d.decode(&re.Value)
  824. } else {
  825. var v interface{}
  826. d.d.decode(&v)
  827. ext.UpdateExt(rv, v)
  828. }
  829. return
  830. }
  831. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  832. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  833. if !isstring && d.se.i != nil {
  834. bsOut = bs
  835. d.DecodeExt(&bsOut, 0, &d.se)
  836. return
  837. }
  838. if c := d.s.sc.sep(); c != 0 {
  839. d.expectChar(c)
  840. }
  841. bs0 := d.appendStringAsBytes(d.b[:0])
  842. // if isstring, then just return the bytes, even if it is using the scratch buffer.
  843. // the bytes will be converted to a string as needed.
  844. if isstring {
  845. return bs0
  846. }
  847. slen := base64.StdEncoding.DecodedLen(len(bs0))
  848. if slen <= cap(bs) {
  849. bsOut = bs[:slen]
  850. } else if zerocopy && slen <= cap(d.b2) {
  851. bsOut = d.b2[:slen]
  852. } else {
  853. bsOut = make([]byte, slen)
  854. }
  855. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  856. if err != nil {
  857. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  858. return nil
  859. }
  860. if slen != slen2 {
  861. bsOut = bsOut[:slen2]
  862. }
  863. return
  864. }
  865. func (d *jsonDecDriver) DecodeString() (s string) {
  866. if c := d.s.sc.sep(); c != 0 {
  867. d.expectChar(c)
  868. }
  869. return string(d.appendStringAsBytes(d.b[:0]))
  870. }
  871. func (d *jsonDecDriver) appendStringAsBytes(v []byte) []byte {
  872. d.expectChar('"')
  873. for {
  874. c := d.r.readn1()
  875. if c == '"' {
  876. break
  877. } else if c == '\\' {
  878. c = d.r.readn1()
  879. switch c {
  880. case '"', '\\', '/', '\'':
  881. v = append(v, c)
  882. case 'b':
  883. v = append(v, '\b')
  884. case 'f':
  885. v = append(v, '\f')
  886. case 'n':
  887. v = append(v, '\n')
  888. case 'r':
  889. v = append(v, '\r')
  890. case 't':
  891. v = append(v, '\t')
  892. case 'u':
  893. rr := d.jsonU4(false)
  894. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  895. if utf16.IsSurrogate(rr) {
  896. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  897. }
  898. w2 := utf8.EncodeRune(d.bstr[:], rr)
  899. v = append(v, d.bstr[:w2]...)
  900. default:
  901. d.d.errorf("json: unsupported escaped value: %c", c)
  902. return nil
  903. }
  904. } else {
  905. v = append(v, c)
  906. }
  907. }
  908. if jsonTrackSkipWhitespace {
  909. d.wsSkipped = false
  910. }
  911. return v
  912. }
  913. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  914. if checkSlashU && !(d.r.readn1() == '\\' && d.r.readn1() == 'u') {
  915. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  916. return 0
  917. }
  918. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  919. var u uint32
  920. for i := 0; i < 4; i++ {
  921. v := d.r.readn1()
  922. if '0' <= v && v <= '9' {
  923. v = v - '0'
  924. } else if 'a' <= v && v <= 'z' {
  925. v = v - 'a' + 10
  926. } else if 'A' <= v && v <= 'Z' {
  927. v = v - 'A' + 10
  928. } else {
  929. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  930. return 0
  931. }
  932. u = u*16 + uint32(v)
  933. }
  934. return rune(u)
  935. }
  936. func (d *jsonDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
  937. if c := d.s.sc.sep(); c != 0 {
  938. d.expectChar(c)
  939. }
  940. n := d.skipWhitespace(true)
  941. switch n {
  942. case 'n':
  943. d.readStrIdx(9, 13) // null
  944. vt = valueTypeNil
  945. case 'f':
  946. d.readStrIdx(4, 9) // false
  947. vt = valueTypeBool
  948. v = false
  949. case 't':
  950. d.readStrIdx(0, 4) // true
  951. vt = valueTypeBool
  952. v = true
  953. case '{':
  954. vt = valueTypeMap
  955. decodeFurther = true
  956. case '[':
  957. vt = valueTypeArray
  958. decodeFurther = true
  959. case '"':
  960. vt = valueTypeString
  961. v = string(d.appendStringAsBytes(d.b[:0])) // same as d.DecodeString(), but skipping sep() call.
  962. default: // number
  963. d.decNum(true)
  964. n := &d.n
  965. // if the string had a any of [.eE], then decode as float.
  966. switch {
  967. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  968. vt = valueTypeFloat
  969. v = n.floatVal()
  970. case n.exponent == 0:
  971. u := n.mantissa
  972. switch {
  973. case n.neg:
  974. vt = valueTypeInt
  975. v = -int64(u)
  976. case d.h.SignedInteger:
  977. vt = valueTypeInt
  978. v = int64(u)
  979. default:
  980. vt = valueTypeUint
  981. v = u
  982. }
  983. default:
  984. u, overflow := n.uintExp()
  985. switch {
  986. case overflow:
  987. vt = valueTypeFloat
  988. v = n.floatVal()
  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. }
  1000. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  1001. }
  1002. if decodeFurther {
  1003. d.s.sc.retryRead()
  1004. }
  1005. return
  1006. }
  1007. //----------------------
  1008. // JsonHandle is a handle for JSON encoding format.
  1009. //
  1010. // Json is comprehensively supported:
  1011. // - decodes numbers into interface{} as int, uint or float64
  1012. // - configurable way to encode/decode []byte .
  1013. // by default, encodes and decodes []byte using base64 Std Encoding
  1014. // - UTF-8 support for encoding and decoding
  1015. //
  1016. // It has better performance than the json library in the standard library,
  1017. // by leveraging the performance improvements of the codec library and
  1018. // minimizing allocations.
  1019. //
  1020. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1021. // reading multiple values from a stream containing json and non-json content.
  1022. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1023. // all from the same stream in sequence.
  1024. type JsonHandle struct {
  1025. BasicHandle
  1026. textEncodingType
  1027. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1028. // If not configured, raw bytes are encoded to/from base64 text.
  1029. RawBytesExt InterfaceExt
  1030. }
  1031. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1032. hd := jsonEncDriver{e: e, w: e.w, h: h}
  1033. hd.se.i = h.RawBytesExt
  1034. return &hd
  1035. }
  1036. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1037. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1038. hd := jsonDecDriver{d: d, r: d.r, h: h}
  1039. hd.se.i = h.RawBytesExt
  1040. hd.n.bytes = d.b[:]
  1041. return &hd
  1042. }
  1043. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1044. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1045. }
  1046. var jsonEncodeTerminate = []byte{' '}
  1047. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1048. return jsonEncodeTerminate
  1049. }
  1050. var _ decDriver = (*jsonDecDriver)(nil)
  1051. var _ encDriver = (*jsonEncDriver)(nil)