json.go 28 KB

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