json.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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], 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. // encode all bytes < 0x20 (except \r, \n).
  276. // also encode < > & to prevent security holes when served to some browsers.
  277. if b := s[i]; b < utf8.RuneSelf {
  278. if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  279. i++
  280. continue
  281. }
  282. if start < i {
  283. w.writestr(s[start:i])
  284. }
  285. switch b {
  286. case '\\', '"':
  287. w.writen2('\\', b)
  288. case '\n':
  289. w.writen2('\\', 'n')
  290. case '\r':
  291. w.writen2('\\', 'r')
  292. case '\b':
  293. w.writen2('\\', 'b')
  294. case '\f':
  295. w.writen2('\\', 'f')
  296. case '\t':
  297. w.writen2('\\', 't')
  298. case '<', '>', '&':
  299. if e.h.HTMLCharsAsIs {
  300. w.writen1(b)
  301. } else {
  302. w.writestr(`\u00`)
  303. w.writen2(hex[b>>4], hex[b&0xF])
  304. }
  305. default:
  306. w.writestr(`\u00`)
  307. w.writen2(hex[b>>4], hex[b&0xF])
  308. }
  309. i++
  310. start = i
  311. continue
  312. }
  313. c, size := utf8.DecodeRuneInString(s[i:])
  314. if c == utf8.RuneError && size == 1 {
  315. if start < i {
  316. w.writestr(s[start:i])
  317. }
  318. w.writestr(`\ufffd`)
  319. i += size
  320. start = i
  321. continue
  322. }
  323. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  324. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  325. if c == '\u2028' || c == '\u2029' {
  326. if start < i {
  327. w.writestr(s[start:i])
  328. }
  329. w.writestr(`\u202`)
  330. w.writen1(hex[c&0xF])
  331. i += size
  332. start = i
  333. continue
  334. }
  335. i += size
  336. }
  337. if start < len(s) {
  338. w.writestr(s[start:])
  339. }
  340. w.writen1('"')
  341. }
  342. //--------------------------------
  343. type jsonNum struct {
  344. // bytes []byte // may have [+-.eE0-9]
  345. mantissa uint64 // where mantissa ends, and maybe dot begins.
  346. exponent int16 // exponent value.
  347. manOverflow bool
  348. neg bool // started with -. No initial sign in the bytes above.
  349. dot bool // has dot
  350. explicitExponent bool // explicit exponent
  351. }
  352. func (x *jsonNum) reset() {
  353. x.manOverflow = false
  354. x.neg = false
  355. x.dot = false
  356. x.explicitExponent = false
  357. x.mantissa = 0
  358. x.exponent = 0
  359. }
  360. // uintExp is called only if exponent > 0.
  361. func (x *jsonNum) uintExp() (n uint64, overflow bool) {
  362. n = x.mantissa
  363. e := x.exponent
  364. if e >= int16(len(jsonUint64Pow10)) {
  365. overflow = true
  366. return
  367. }
  368. n *= jsonUint64Pow10[e]
  369. if n < x.mantissa || n > jsonNumUintMaxVal {
  370. overflow = true
  371. return
  372. }
  373. return
  374. // for i := int16(0); i < e; i++ {
  375. // if n >= jsonNumUintCutoff {
  376. // overflow = true
  377. // return
  378. // }
  379. // n *= 10
  380. // }
  381. // return
  382. }
  383. // these constants are only used withn floatVal.
  384. // They are brought out, so that floatVal can be inlined.
  385. const (
  386. jsonUint64MantissaBits = 52
  387. jsonMaxExponent = int16(len(jsonFloat64Pow10)) - 1
  388. )
  389. func (x *jsonNum) floatVal() (f float64, parseUsingStrConv bool) {
  390. // We do not want to lose precision.
  391. // Consequently, we will delegate to strconv.ParseFloat if any of the following happen:
  392. // - There are more digits than in math.MaxUint64: 18446744073709551615 (20 digits)
  393. // We expect up to 99.... (19 digits)
  394. // - The mantissa cannot fit into a 52 bits of uint64
  395. // - The exponent is beyond our scope ie beyong 22.
  396. parseUsingStrConv = x.manOverflow ||
  397. x.exponent > jsonMaxExponent ||
  398. (x.exponent < 0 && -(x.exponent) > jsonMaxExponent) ||
  399. x.mantissa>>jsonUint64MantissaBits != 0
  400. if parseUsingStrConv {
  401. return
  402. }
  403. // all good. so handle parse here.
  404. f = float64(x.mantissa)
  405. // fmt.Printf(".Float: uint64 value: %v, float: %v\n", m, f)
  406. if x.neg {
  407. f = -f
  408. }
  409. if x.exponent > 0 {
  410. f *= jsonFloat64Pow10[x.exponent]
  411. } else if x.exponent < 0 {
  412. f /= jsonFloat64Pow10[-x.exponent]
  413. }
  414. return
  415. }
  416. type jsonDecDriver struct {
  417. noBuiltInTypes
  418. d *Decoder
  419. h *JsonHandle
  420. r decReader
  421. c containerState
  422. // tok is used to store the token read right after skipWhiteSpace.
  423. tok uint8
  424. bstr [8]byte // scratch used for string \UXXX parsing
  425. b [64]byte // scratch, used for parsing strings or numbers
  426. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  427. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  428. se setExtWrapper
  429. n jsonNum
  430. }
  431. func jsonIsWS(b byte) bool {
  432. return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  433. }
  434. // // This will skip whitespace characters and return the next byte to read.
  435. // // The next byte determines what the value will be one of.
  436. // func (d *jsonDecDriver) skipWhitespace() {
  437. // // fast-path: do not enter loop. Just check first (in case no whitespace).
  438. // b := d.r.readn1()
  439. // if jsonIsWS(b) {
  440. // r := d.r
  441. // for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  442. // }
  443. // }
  444. // d.tok = b
  445. // }
  446. func (d *jsonDecDriver) uncacheRead() {
  447. if d.tok != 0 {
  448. d.r.unreadn1()
  449. d.tok = 0
  450. }
  451. }
  452. func (d *jsonDecDriver) sendContainerState(c containerState) {
  453. if d.tok == 0 {
  454. var b byte
  455. r := d.r
  456. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  457. }
  458. d.tok = b
  459. }
  460. var xc uint8 // char expected
  461. if c == containerMapKey {
  462. if d.c != containerMapStart {
  463. xc = ','
  464. }
  465. } else if c == containerMapValue {
  466. xc = ':'
  467. } else if c == containerMapEnd {
  468. xc = '}'
  469. } else if c == containerArrayElem {
  470. if d.c != containerArrayStart {
  471. xc = ','
  472. }
  473. } else if c == containerArrayEnd {
  474. xc = ']'
  475. }
  476. if xc != 0 {
  477. if d.tok != xc {
  478. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  479. }
  480. d.tok = 0
  481. }
  482. d.c = c
  483. }
  484. func (d *jsonDecDriver) CheckBreak() bool {
  485. if d.tok == 0 {
  486. var b byte
  487. r := d.r
  488. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  489. }
  490. d.tok = b
  491. }
  492. if d.tok == '}' || d.tok == ']' {
  493. // d.tok = 0 // only checking, not consuming
  494. return true
  495. }
  496. return false
  497. }
  498. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  499. bs := d.r.readx(int(toIdx - fromIdx))
  500. d.tok = 0
  501. if jsonValidateSymbols {
  502. if !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  503. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  504. return
  505. }
  506. }
  507. }
  508. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  509. if d.tok == 0 {
  510. var b byte
  511. r := d.r
  512. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  513. }
  514. d.tok = b
  515. }
  516. if d.tok == 'n' {
  517. d.readStrIdx(10, 13) // ull
  518. return true
  519. }
  520. return false
  521. }
  522. func (d *jsonDecDriver) DecodeBool() bool {
  523. if d.tok == 0 {
  524. var b byte
  525. r := d.r
  526. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  527. }
  528. d.tok = b
  529. }
  530. if d.tok == 'f' {
  531. d.readStrIdx(5, 9) // alse
  532. return false
  533. }
  534. if d.tok == 't' {
  535. d.readStrIdx(1, 4) // rue
  536. return true
  537. }
  538. d.d.errorf("json: decode bool: got first char %c", d.tok)
  539. return false // "unreachable"
  540. }
  541. func (d *jsonDecDriver) ReadMapStart() int {
  542. if d.tok == 0 {
  543. var b byte
  544. r := d.r
  545. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  546. }
  547. d.tok = b
  548. }
  549. if d.tok != '{' {
  550. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  551. }
  552. d.tok = 0
  553. d.c = containerMapStart
  554. return -1
  555. }
  556. func (d *jsonDecDriver) ReadArrayStart() int {
  557. if d.tok == 0 {
  558. var b byte
  559. r := d.r
  560. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  561. }
  562. d.tok = b
  563. }
  564. if d.tok != '[' {
  565. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  566. }
  567. d.tok = 0
  568. d.c = containerArrayStart
  569. return -1
  570. }
  571. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  572. // check container type by checking the first char
  573. if d.tok == 0 {
  574. var b byte
  575. r := d.r
  576. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  577. }
  578. d.tok = b
  579. }
  580. if b := d.tok; b == '{' {
  581. return valueTypeMap
  582. } else if b == '[' {
  583. return valueTypeArray
  584. } else if b == 'n' {
  585. return valueTypeNil
  586. } else if b == '"' {
  587. return valueTypeString
  588. }
  589. return valueTypeUnset
  590. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  591. // return false // "unreachable"
  592. }
  593. func (d *jsonDecDriver) decNum(storeBytes bool) {
  594. // If it is has a . or an e|E, decode as a float; else decode as an int.
  595. if d.tok == 0 {
  596. var b byte
  597. r := d.r
  598. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  599. }
  600. d.tok = b
  601. }
  602. b := d.tok
  603. var str bool
  604. if b == '"' {
  605. str = true
  606. b = d.r.readn1()
  607. }
  608. if !(b == '+' || b == '-' || b == '.' || (b >= '0' && b <= '9')) {
  609. d.d.errorf("json: decNum: got first char '%c'", b)
  610. return
  611. }
  612. d.tok = 0
  613. const cutoff = (1<<64-1)/uint64(10) + 1 // cutoff64(base)
  614. const jsonNumUintMaxVal = 1<<uint64(64) - 1
  615. n := &d.n
  616. r := d.r
  617. n.reset()
  618. d.bs = d.bs[:0]
  619. if str && storeBytes {
  620. d.bs = append(d.bs, '"')
  621. }
  622. // The format of a number is as below:
  623. // parsing: sign? digit* dot? digit* e? sign? digit*
  624. // states: 0 1* 2 3* 4 5* 6 7
  625. // We honor this state so we can break correctly.
  626. var state uint8 = 0
  627. var eNeg bool
  628. var e int16
  629. var eof bool
  630. LOOP:
  631. for !eof {
  632. // fmt.Printf("LOOP: b: %q\n", b)
  633. switch b {
  634. case '+':
  635. switch state {
  636. case 0:
  637. state = 2
  638. // do not add sign to the slice ...
  639. b, eof = r.readn1eof()
  640. continue
  641. case 6: // typ = jsonNumFloat
  642. state = 7
  643. default:
  644. break LOOP
  645. }
  646. case '-':
  647. switch state {
  648. case 0:
  649. state = 2
  650. n.neg = true
  651. // do not add sign to the slice ...
  652. b, eof = r.readn1eof()
  653. continue
  654. case 6: // typ = jsonNumFloat
  655. eNeg = true
  656. state = 7
  657. default:
  658. break LOOP
  659. }
  660. case '.':
  661. switch state {
  662. case 0, 2: // typ = jsonNumFloat
  663. state = 4
  664. n.dot = true
  665. default:
  666. break LOOP
  667. }
  668. case 'e', 'E':
  669. switch state {
  670. case 0, 2, 4: // typ = jsonNumFloat
  671. state = 6
  672. // n.mantissaEndIndex = int16(len(n.bytes))
  673. n.explicitExponent = true
  674. default:
  675. break LOOP
  676. }
  677. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  678. switch state {
  679. case 0:
  680. state = 2
  681. fallthrough
  682. case 2:
  683. fallthrough
  684. case 4:
  685. if n.dot {
  686. n.exponent--
  687. }
  688. if n.mantissa >= jsonNumUintCutoff {
  689. n.manOverflow = true
  690. break
  691. }
  692. v := uint64(b - '0')
  693. n.mantissa *= 10
  694. if v != 0 {
  695. n1 := n.mantissa + v
  696. if n1 < n.mantissa || n1 > jsonNumUintMaxVal {
  697. n.manOverflow = true // n+v overflows
  698. break
  699. }
  700. n.mantissa = n1
  701. }
  702. case 6:
  703. state = 7
  704. fallthrough
  705. case 7:
  706. if !(b == '0' && e == 0) {
  707. e = e*10 + int16(b-'0')
  708. }
  709. default:
  710. break LOOP
  711. }
  712. case '"':
  713. if str {
  714. if storeBytes {
  715. d.bs = append(d.bs, '"')
  716. }
  717. b, eof = r.readn1eof()
  718. }
  719. break LOOP
  720. default:
  721. break LOOP
  722. }
  723. if storeBytes {
  724. d.bs = append(d.bs, b)
  725. }
  726. b, eof = r.readn1eof()
  727. }
  728. if jsonTruncateMantissa && n.mantissa != 0 {
  729. for n.mantissa%10 == 0 {
  730. n.mantissa /= 10
  731. n.exponent++
  732. }
  733. }
  734. if e != 0 {
  735. if eNeg {
  736. n.exponent -= e
  737. } else {
  738. n.exponent += e
  739. }
  740. }
  741. // d.n = n
  742. if !eof {
  743. if jsonUnreadAfterDecNum {
  744. r.unreadn1()
  745. } else {
  746. if !jsonIsWS(b) {
  747. d.tok = b
  748. }
  749. }
  750. }
  751. // fmt.Printf("1: n: bytes: %s, neg: %v, dot: %v, exponent: %v, mantissaEndIndex: %v\n",
  752. // n.bytes, n.neg, n.dot, n.exponent, n.mantissaEndIndex)
  753. return
  754. }
  755. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  756. d.decNum(false)
  757. n := &d.n
  758. if n.manOverflow {
  759. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  760. return
  761. }
  762. var u uint64
  763. if n.exponent == 0 {
  764. u = n.mantissa
  765. } else if n.exponent < 0 {
  766. d.d.errorf("json: fractional integer")
  767. return
  768. } else if n.exponent > 0 {
  769. var overflow bool
  770. if u, overflow = n.uintExp(); overflow {
  771. d.d.errorf("json: overflow integer")
  772. return
  773. }
  774. }
  775. i = int64(u)
  776. if n.neg {
  777. i = -i
  778. }
  779. if chkOvf.Int(i, bitsize) {
  780. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  781. return
  782. }
  783. // fmt.Printf("DecodeInt: %v\n", i)
  784. return
  785. }
  786. // floatVal MUST only be called after a decNum, as d.bs now contains the bytes of the number
  787. func (d *jsonDecDriver) floatVal() (f float64) {
  788. f, useStrConv := d.n.floatVal()
  789. if useStrConv {
  790. var err error
  791. if f, err = strconv.ParseFloat(stringView(d.bs), 64); err != nil {
  792. panic(fmt.Errorf("parse float: %s, %v", d.bs, err))
  793. }
  794. if d.n.neg {
  795. f = -f
  796. }
  797. }
  798. return
  799. }
  800. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  801. d.decNum(false)
  802. n := &d.n
  803. if n.neg {
  804. d.d.errorf("json: unsigned integer cannot be negative")
  805. return
  806. }
  807. if n.manOverflow {
  808. d.d.errorf("json: overflow integer after: %v", n.mantissa)
  809. return
  810. }
  811. if n.exponent == 0 {
  812. u = n.mantissa
  813. } else if n.exponent < 0 {
  814. d.d.errorf("json: fractional integer")
  815. return
  816. } else if n.exponent > 0 {
  817. var overflow bool
  818. if u, overflow = n.uintExp(); overflow {
  819. d.d.errorf("json: overflow integer")
  820. return
  821. }
  822. }
  823. if chkOvf.Uint(u, bitsize) {
  824. d.d.errorf("json: overflow %v bits: %s", bitsize, d.bs)
  825. return
  826. }
  827. // fmt.Printf("DecodeUint: %v\n", u)
  828. return
  829. }
  830. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  831. d.decNum(true)
  832. f = d.floatVal()
  833. if chkOverflow32 && chkOvf.Float32(f) {
  834. d.d.errorf("json: overflow float32: %v, %s", f, d.bs)
  835. return
  836. }
  837. return
  838. }
  839. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  840. if ext == nil {
  841. re := rv.(*RawExt)
  842. re.Tag = xtag
  843. d.d.decode(&re.Value)
  844. } else {
  845. var v interface{}
  846. d.d.decode(&v)
  847. ext.UpdateExt(rv, v)
  848. }
  849. return
  850. }
  851. func (d *jsonDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  852. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  853. if !isstring && d.se.i != nil {
  854. bsOut = bs
  855. d.DecodeExt(&bsOut, 0, &d.se)
  856. return
  857. }
  858. d.appendStringAsBytes()
  859. // if isstring, then just return the bytes, even if it is using the scratch buffer.
  860. // the bytes will be converted to a string as needed.
  861. if isstring {
  862. return d.bs
  863. }
  864. // if appendStringAsBytes returned a zero-len slice, then treat as nil.
  865. // This should only happen for null, and "".
  866. if len(d.bs) == 0 {
  867. return nil
  868. }
  869. bs0 := d.bs
  870. slen := base64.StdEncoding.DecodedLen(len(bs0))
  871. if slen <= cap(bs) {
  872. bsOut = bs[:slen]
  873. } else if zerocopy && slen <= cap(d.b2) {
  874. bsOut = d.b2[:slen]
  875. } else {
  876. bsOut = make([]byte, slen)
  877. }
  878. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  879. if err != nil {
  880. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  881. return nil
  882. }
  883. if slen != slen2 {
  884. bsOut = bsOut[:slen2]
  885. }
  886. return
  887. }
  888. func (d *jsonDecDriver) DecodeString() (s string) {
  889. d.appendStringAsBytes()
  890. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  891. if d.c == containerMapKey {
  892. return d.d.string(d.bs)
  893. }
  894. return string(d.bs)
  895. }
  896. func (d *jsonDecDriver) appendStringAsBytes() {
  897. if d.tok == 0 {
  898. var b byte
  899. r := d.r
  900. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  901. }
  902. d.tok = b
  903. }
  904. // handle null as a string
  905. if d.tok == 'n' {
  906. d.readStrIdx(10, 13) // ull
  907. d.bs = d.bs[:0]
  908. return
  909. }
  910. if d.tok != '"' {
  911. d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  912. }
  913. d.tok = 0
  914. v := d.bs[:0]
  915. var c uint8
  916. r := d.r
  917. for {
  918. c = r.readn1()
  919. if c == '"' {
  920. break
  921. } else if c == '\\' {
  922. c = r.readn1()
  923. switch c {
  924. case '"', '\\', '/', '\'':
  925. v = append(v, c)
  926. case 'b':
  927. v = append(v, '\b')
  928. case 'f':
  929. v = append(v, '\f')
  930. case 'n':
  931. v = append(v, '\n')
  932. case 'r':
  933. v = append(v, '\r')
  934. case 't':
  935. v = append(v, '\t')
  936. case 'u':
  937. rr := d.jsonU4(false)
  938. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  939. if utf16.IsSurrogate(rr) {
  940. rr = utf16.DecodeRune(rr, d.jsonU4(true))
  941. }
  942. w2 := utf8.EncodeRune(d.bstr[:], rr)
  943. v = append(v, d.bstr[:w2]...)
  944. default:
  945. d.d.errorf("json: unsupported escaped value: %c", c)
  946. }
  947. } else {
  948. v = append(v, c)
  949. }
  950. }
  951. d.bs = v
  952. }
  953. func (d *jsonDecDriver) jsonU4(checkSlashU bool) rune {
  954. r := d.r
  955. if checkSlashU && !(r.readn1() == '\\' && r.readn1() == 'u') {
  956. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  957. return 0
  958. }
  959. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  960. var u uint32
  961. for i := 0; i < 4; i++ {
  962. v := r.readn1()
  963. if '0' <= v && v <= '9' {
  964. v = v - '0'
  965. } else if 'a' <= v && v <= 'z' {
  966. v = v - 'a' + 10
  967. } else if 'A' <= v && v <= 'Z' {
  968. v = v - 'A' + 10
  969. } else {
  970. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  971. return 0
  972. }
  973. u = u*16 + uint32(v)
  974. }
  975. return rune(u)
  976. }
  977. func (d *jsonDecDriver) DecodeNaked() {
  978. z := &d.d.n
  979. // var decodeFurther bool
  980. if d.tok == 0 {
  981. var b byte
  982. r := d.r
  983. for b = r.readn1(); jsonIsWS(b); b = r.readn1() {
  984. }
  985. d.tok = b
  986. }
  987. switch d.tok {
  988. case 'n':
  989. d.readStrIdx(10, 13) // ull
  990. z.v = valueTypeNil
  991. case 'f':
  992. d.readStrIdx(5, 9) // alse
  993. z.v = valueTypeBool
  994. z.b = false
  995. case 't':
  996. d.readStrIdx(1, 4) // rue
  997. z.v = valueTypeBool
  998. z.b = true
  999. case '{':
  1000. z.v = valueTypeMap
  1001. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadMapStart
  1002. // decodeFurther = true
  1003. case '[':
  1004. z.v = valueTypeArray
  1005. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadArrayStart
  1006. // decodeFurther = true
  1007. case '"':
  1008. z.v = valueTypeString
  1009. z.s = d.DecodeString()
  1010. default: // number
  1011. d.decNum(true)
  1012. n := &d.n
  1013. // if the string had a any of [.eE], then decode as float.
  1014. switch {
  1015. case n.explicitExponent, n.dot, n.exponent < 0, n.manOverflow:
  1016. z.v = valueTypeFloat
  1017. z.f = d.floatVal()
  1018. case n.exponent == 0:
  1019. u := n.mantissa
  1020. switch {
  1021. case n.neg:
  1022. z.v = valueTypeInt
  1023. z.i = -int64(u)
  1024. case d.h.SignedInteger:
  1025. z.v = valueTypeInt
  1026. z.i = int64(u)
  1027. default:
  1028. z.v = valueTypeUint
  1029. z.u = u
  1030. }
  1031. default:
  1032. u, overflow := n.uintExp()
  1033. switch {
  1034. case overflow:
  1035. z.v = valueTypeFloat
  1036. z.f = d.floatVal()
  1037. case n.neg:
  1038. z.v = valueTypeInt
  1039. z.i = -int64(u)
  1040. case d.h.SignedInteger:
  1041. z.v = valueTypeInt
  1042. z.i = int64(u)
  1043. default:
  1044. z.v = valueTypeUint
  1045. z.u = u
  1046. }
  1047. }
  1048. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  1049. }
  1050. // if decodeFurther {
  1051. // d.s.sc.retryRead()
  1052. // }
  1053. return
  1054. }
  1055. //----------------------
  1056. // JsonHandle is a handle for JSON encoding format.
  1057. //
  1058. // Json is comprehensively supported:
  1059. // - decodes numbers into interface{} as int, uint or float64
  1060. // - configurable way to encode/decode []byte .
  1061. // by default, encodes and decodes []byte using base64 Std Encoding
  1062. // - UTF-8 support for encoding and decoding
  1063. //
  1064. // It has better performance than the json library in the standard library,
  1065. // by leveraging the performance improvements of the codec library and
  1066. // minimizing allocations.
  1067. //
  1068. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1069. // reading multiple values from a stream containing json and non-json content.
  1070. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1071. // all from the same stream in sequence.
  1072. type JsonHandle struct {
  1073. textEncodingType
  1074. BasicHandle
  1075. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1076. // If not configured, raw bytes are encoded to/from base64 text.
  1077. RawBytesExt InterfaceExt
  1078. // Indent indicates how a value is encoded.
  1079. // - If positive, indent by that number of spaces.
  1080. // - If negative, indent by that number of tabs.
  1081. Indent int8
  1082. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1083. //
  1084. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1085. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1086. // This can be mitigated by configuring how to encode integers.
  1087. //
  1088. // IntegerAsString interpretes the following values:
  1089. // - if 'L', then encode integers > 2^53 as a json string.
  1090. // - if 'A', then encode all integers as a json string
  1091. // containing the exact integer representation as a decimal.
  1092. // - else encode all integers as a json number (default)
  1093. IntegerAsString uint8
  1094. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1095. //
  1096. // By default, we encode them as \uXXX
  1097. // to prevent security holes when served from some browsers.
  1098. HTMLCharsAsIs bool
  1099. }
  1100. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1101. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1102. }
  1103. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1104. hd := jsonEncDriver{e: e, h: h}
  1105. hd.bs = hd.b[:0]
  1106. hd.reset()
  1107. return &hd
  1108. }
  1109. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1110. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1111. hd := jsonDecDriver{d: d, h: h}
  1112. hd.bs = hd.b[:0]
  1113. hd.reset()
  1114. return &hd
  1115. }
  1116. func (e *jsonEncDriver) reset() {
  1117. e.w = e.e.w
  1118. e.se.i = e.h.RawBytesExt
  1119. if e.bs != nil {
  1120. e.bs = e.bs[:0]
  1121. }
  1122. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1123. e.c = 0
  1124. if e.h.Indent > 0 {
  1125. e.d = true
  1126. e.ds = jsonSpaces[:e.h.Indent]
  1127. } else if e.h.Indent < 0 {
  1128. e.d = true
  1129. e.dt = true
  1130. e.ds = jsonTabs[:-(e.h.Indent)]
  1131. }
  1132. }
  1133. func (d *jsonDecDriver) reset() {
  1134. d.r = d.d.r
  1135. d.se.i = d.h.RawBytesExt
  1136. if d.bs != nil {
  1137. d.bs = d.bs[:0]
  1138. }
  1139. d.c, d.tok = 0, 0
  1140. d.n.reset()
  1141. }
  1142. var jsonEncodeTerminate = []byte{' '}
  1143. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  1144. return jsonEncodeTerminate
  1145. }
  1146. var _ decDriver = (*jsonDecDriver)(nil)
  1147. var _ encDriver = (*jsonEncDriver)(nil)