json.go 24 KB

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