json.go 25 KB

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