json.go 26 KB

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