json.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. "reflect"
  34. "strconv"
  35. "unicode/utf16"
  36. "unicode/utf8"
  37. )
  38. //--------------------------------
  39. var (
  40. // jsonLiterals = [...]byte{'t', 'r', 'u', 'e', 'f', 'a', 'l', 's', 'e', 'n', 'u', 'l', 'l'}
  41. 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. 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. // jsonTabs and jsonSpaces are used as caches for indents
  51. jsonTabs, jsonSpaces string
  52. jsonCharHtmlSafeSet bitset128
  53. jsonCharSafeSet bitset128
  54. jsonCharWhitespaceSet bitset256
  55. jsonNumSet bitset256
  56. )
  57. const (
  58. // jsonUnreadAfterDecNum controls whether we unread after decoding a number.
  59. //
  60. // instead of unreading, just update d.tok (iff it's not a whitespace char)
  61. // However, doing this means that we may HOLD onto some data which belongs to another stream.
  62. // Thus, it is safest to unread the data when done.
  63. // keep behind a constant flag for now.
  64. jsonUnreadAfterDecNum = true
  65. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  66. // - If we see first character of null, false or true,
  67. // do not validate subsequent characters.
  68. // - e.g. if we see a n, assume null and skip next 3 characters,
  69. // and do not validate they are ull.
  70. // P.S. Do not expect a significant decoding boost from this.
  71. jsonValidateSymbols = true
  72. jsonSpacesOrTabsLen = 128
  73. )
  74. func init() {
  75. var bs [jsonSpacesOrTabsLen]byte
  76. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  77. bs[i] = ' '
  78. }
  79. jsonSpaces = string(bs[:])
  80. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  81. bs[i] = '\t'
  82. }
  83. jsonTabs = string(bs[:])
  84. // populate the safe values as true: note: ASCII control characters are (0-31)
  85. // jsonCharSafeSet: all true except (0-31) " \
  86. // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
  87. var i byte
  88. for i = 32; i < utf8.RuneSelf; i++ {
  89. switch i {
  90. case '"', '\\':
  91. case '<', '>', '&':
  92. jsonCharSafeSet.set(i) // = true
  93. default:
  94. jsonCharSafeSet.set(i)
  95. jsonCharHtmlSafeSet.set(i)
  96. }
  97. }
  98. for i = 0; i <= utf8.RuneSelf; i++ {
  99. switch i {
  100. case ' ', '\t', '\r', '\n':
  101. jsonCharWhitespaceSet.set(i)
  102. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
  103. jsonNumSet.set(i)
  104. }
  105. }
  106. }
  107. type jsonEncDriver struct {
  108. e *Encoder
  109. w encWriter
  110. h *JsonHandle
  111. b [64]byte // scratch
  112. bs []byte // scratch
  113. se setExtWrapper
  114. ds string // indent string
  115. dl uint16 // indent level
  116. dt bool // indent using tabs
  117. d bool // indent
  118. c containerState
  119. noBuiltInTypes
  120. }
  121. // indent is done as below:
  122. // - newline and indent are added before each mapKey or arrayElem
  123. // - newline and indent are added before each ending,
  124. // except there was no entry (so we can have {} or [])
  125. func (e *jsonEncDriver) sendContainerState(c containerState) {
  126. // determine whether to output separators
  127. switch c {
  128. case containerMapKey:
  129. if e.c != containerMapStart {
  130. e.w.writen1(',')
  131. }
  132. if e.d {
  133. e.writeIndent()
  134. }
  135. case containerMapValue:
  136. if e.d {
  137. e.w.writen2(':', ' ')
  138. } else {
  139. e.w.writen1(':')
  140. }
  141. case containerMapEnd:
  142. if e.d {
  143. e.dl--
  144. if e.c != containerMapStart {
  145. e.writeIndent()
  146. }
  147. }
  148. e.w.writen1('}')
  149. case containerArrayElem:
  150. if e.c != containerArrayStart {
  151. e.w.writen1(',')
  152. }
  153. if e.d {
  154. e.writeIndent()
  155. }
  156. case containerArrayEnd:
  157. if e.d {
  158. e.dl--
  159. if e.c != containerArrayStart {
  160. e.writeIndent()
  161. }
  162. }
  163. e.w.writen1(']')
  164. }
  165. e.c = c
  166. }
  167. func (e *jsonEncDriver) writeIndent() {
  168. e.w.writen1('\n')
  169. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  170. if e.dt {
  171. e.w.writestr(jsonTabs[:x])
  172. } else {
  173. e.w.writestr(jsonSpaces[:x])
  174. }
  175. } else {
  176. for i := uint16(0); i < e.dl; i++ {
  177. e.w.writestr(e.ds)
  178. }
  179. }
  180. }
  181. func (e *jsonEncDriver) EncodeNil() {
  182. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null
  183. }
  184. func (e *jsonEncDriver) EncodeBool(b bool) {
  185. if b {
  186. e.w.writen4('t', 'r', 'u', 'e') // e.w.writeb(jsonLiterals[0:4]) // true
  187. } else {
  188. e.w.writen5('f', 'a', 'l', 's', 'e') // e.w.writeb(jsonLiterals[4:9]) // false
  189. }
  190. }
  191. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  192. e.encodeFloat(float64(f), 32)
  193. }
  194. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  195. e.encodeFloat(f, 64)
  196. }
  197. func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
  198. x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
  199. e.w.writeb(x)
  200. if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
  201. e.w.writen2('.', '0')
  202. }
  203. }
  204. func (e *jsonEncDriver) EncodeInt(v int64) {
  205. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  206. e.w.writen1('"')
  207. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  208. e.w.writen1('"')
  209. return
  210. }
  211. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  212. }
  213. func (e *jsonEncDriver) EncodeUint(v uint64) {
  214. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  215. e.w.writen1('"')
  216. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  217. e.w.writen1('"')
  218. return
  219. }
  220. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  221. }
  222. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  223. if v := ext.ConvertExt(rv); v == nil {
  224. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  225. } else {
  226. en.encode(v)
  227. }
  228. }
  229. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  230. // only encodes re.Value (never re.Data)
  231. if re.Value == nil {
  232. e.w.writen4('n', 'u', 'l', 'l') // e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  233. } else {
  234. en.encode(re.Value)
  235. }
  236. }
  237. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  238. if e.d {
  239. e.dl++
  240. }
  241. e.w.writen1('[')
  242. e.c = containerArrayStart
  243. }
  244. func (e *jsonEncDriver) EncodeMapStart(length int) {
  245. if e.d {
  246. e.dl++
  247. }
  248. e.w.writen1('{')
  249. e.c = containerMapStart
  250. }
  251. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  252. e.quoteStr(v)
  253. }
  254. func (e *jsonEncDriver) EncodeSymbol(v string) {
  255. e.quoteStr(v)
  256. }
  257. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  258. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  259. if c == c_RAW && e.se.i != nil {
  260. e.EncodeExt(v, 0, &e.se, e.e)
  261. return
  262. }
  263. if c == c_RAW {
  264. slen := base64.StdEncoding.EncodedLen(len(v))
  265. if cap(e.bs) >= slen {
  266. e.bs = e.bs[:slen]
  267. } else {
  268. e.bs = make([]byte, slen)
  269. }
  270. base64.StdEncoding.Encode(e.bs, v)
  271. e.w.writen1('"')
  272. e.w.writeb(e.bs)
  273. e.w.writen1('"')
  274. } else {
  275. e.quoteStr(stringView(v))
  276. }
  277. }
  278. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  279. e.w.writeb(v)
  280. }
  281. func (e *jsonEncDriver) quoteStr(s string) {
  282. // adapted from std pkg encoding/json
  283. const hex = "0123456789abcdef"
  284. w := e.w
  285. w.writen1('"')
  286. start := 0
  287. for i := 0; i < len(s); {
  288. // encode all bytes < 0x20 (except \r, \n).
  289. // also encode < > & to prevent security holes when served to some browsers.
  290. if b := s[i]; b < utf8.RuneSelf {
  291. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  292. if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
  293. i++
  294. continue
  295. }
  296. if start < i {
  297. w.writestr(s[start:i])
  298. }
  299. switch b {
  300. case '\\', '"':
  301. w.writen2('\\', b)
  302. case '\n':
  303. w.writen2('\\', 'n')
  304. case '\r':
  305. w.writen2('\\', 'r')
  306. case '\b':
  307. w.writen2('\\', 'b')
  308. case '\f':
  309. w.writen2('\\', 'f')
  310. case '\t':
  311. w.writen2('\\', 't')
  312. default:
  313. w.writestr(`\u00`)
  314. w.writen2(hex[b>>4], hex[b&0xF])
  315. }
  316. i++
  317. start = i
  318. continue
  319. }
  320. c, size := utf8.DecodeRuneInString(s[i:])
  321. if c == utf8.RuneError && size == 1 {
  322. if start < i {
  323. w.writestr(s[start:i])
  324. }
  325. w.writestr(`\ufffd`)
  326. i += size
  327. start = i
  328. continue
  329. }
  330. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  331. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  332. if c == '\u2028' || c == '\u2029' {
  333. if start < i {
  334. w.writestr(s[start:i])
  335. }
  336. w.writestr(`\u202`)
  337. w.writen1(hex[c&0xF])
  338. i += size
  339. start = i
  340. continue
  341. }
  342. i += size
  343. }
  344. if start < len(s) {
  345. w.writestr(s[start:])
  346. }
  347. w.writen1('"')
  348. }
  349. type jsonDecDriver struct {
  350. noBuiltInTypes
  351. d *Decoder
  352. h *JsonHandle
  353. r decReader
  354. c containerState
  355. // tok is used to store the token read right after skipWhiteSpace.
  356. tok uint8
  357. fnull bool // found null from appendStringAsBytes
  358. bstr [8]byte // scratch used for string \UXXX parsing
  359. b [64]byte // scratch, used for parsing strings or numbers
  360. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  361. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  362. se setExtWrapper
  363. // n jsonNum
  364. }
  365. func jsonIsWS(b byte) bool {
  366. // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  367. return jsonCharWhitespaceSet.isset(b)
  368. }
  369. func (d *jsonDecDriver) uncacheRead() {
  370. if d.tok != 0 {
  371. d.r.unreadn1()
  372. d.tok = 0
  373. }
  374. }
  375. func (d *jsonDecDriver) sendContainerState(c containerState) {
  376. if d.tok == 0 {
  377. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  378. }
  379. var xc uint8 // char expected
  380. switch c {
  381. case containerMapKey:
  382. if d.c != containerMapStart {
  383. xc = ','
  384. }
  385. case containerMapValue:
  386. xc = ':'
  387. case containerMapEnd:
  388. xc = '}'
  389. case containerArrayElem:
  390. if d.c != containerArrayStart {
  391. xc = ','
  392. }
  393. case containerArrayEnd:
  394. xc = ']'
  395. }
  396. if xc != 0 {
  397. if d.tok != xc {
  398. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  399. }
  400. d.tok = 0
  401. }
  402. d.c = c
  403. }
  404. func (d *jsonDecDriver) CheckBreak() bool {
  405. if d.tok == 0 {
  406. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  407. }
  408. return d.tok == '}' || d.tok == ']'
  409. }
  410. // func (d *jsonDecDriver) readLiteralIdx(fromIdx, toIdx uint8) {
  411. // bs := d.r.readx(int(toIdx - fromIdx))
  412. // d.tok = 0
  413. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  414. // d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  415. // return
  416. // }
  417. // }
  418. func (d *jsonDecDriver) readSymbol3(v1, v2, v3 uint8) {
  419. b1, b2, b3 := d.r.readn3()
  420. d.tok = 0
  421. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3) {
  422. d.d.errorf("json: expecting %c, %c, %c: got %c, %c, %c", b1, b2, b3, v1, v2, v3)
  423. return
  424. }
  425. }
  426. func (d *jsonDecDriver) readSymbol4(v1, v2, v3, v4 uint8) {
  427. b1, b2, b3, b4 := d.r.readn4()
  428. d.tok = 0
  429. if jsonValidateSymbols && (b1 != v1 || b2 != v2 || b3 != v3 || b4 != v4) {
  430. d.d.errorf("json: expecting %c, %c, %c, %c: got %c, %c, %c, %c", b1, b2, b3, b4, v1, v2, v3, v4)
  431. return
  432. }
  433. }
  434. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  435. if d.tok == 0 {
  436. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  437. }
  438. if d.tok == 'n' {
  439. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  440. return true
  441. }
  442. return false
  443. }
  444. func (d *jsonDecDriver) DecodeBool() bool {
  445. if d.tok == 0 {
  446. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  447. }
  448. if d.tok == 'f' {
  449. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  450. return false
  451. }
  452. if d.tok == 't' {
  453. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  454. return true
  455. }
  456. d.d.errorf("json: decode bool: got first char %c", d.tok)
  457. return false // "unreachable"
  458. }
  459. func (d *jsonDecDriver) ReadMapStart() int {
  460. if d.tok == 0 {
  461. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  462. }
  463. if d.tok != '{' {
  464. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  465. }
  466. d.tok = 0
  467. d.c = containerMapStart
  468. return -1
  469. }
  470. func (d *jsonDecDriver) ReadArrayStart() int {
  471. if d.tok == 0 {
  472. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  473. }
  474. if d.tok != '[' {
  475. d.d.errorf("json: expect char '%c' but got char '%c'", '[', d.tok)
  476. }
  477. d.tok = 0
  478. d.c = containerArrayStart
  479. return -1
  480. }
  481. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  482. // check container type by checking the first char
  483. if d.tok == 0 {
  484. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  485. }
  486. if b := d.tok; b == '{' {
  487. return valueTypeMap
  488. } else if b == '[' {
  489. return valueTypeArray
  490. } else if b == 'n' {
  491. return valueTypeNil
  492. } else if b == '"' {
  493. return valueTypeString
  494. }
  495. return valueTypeUnset
  496. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  497. // return false // "unreachable"
  498. }
  499. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  500. // stores num bytes in d.bs
  501. if d.tok == 0 {
  502. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  503. }
  504. if d.tok == '"' {
  505. bs = d.r.readUntil(d.b2[:0], '"')
  506. bs = bs[:len(bs)-1]
  507. } else {
  508. d.r.unreadn1()
  509. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  510. }
  511. d.tok = 0
  512. return bs
  513. }
  514. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  515. bs := d.decNumBytes()
  516. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  517. if err != nil {
  518. d.d.errorf("json: decode uint from %s: %v", bs, err)
  519. return
  520. }
  521. return
  522. }
  523. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  524. bs := d.decNumBytes()
  525. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  526. if err != nil {
  527. d.d.errorf("json: decode int from %s: %v", bs, err)
  528. return
  529. }
  530. return
  531. }
  532. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  533. bs := d.decNumBytes()
  534. bitsize := 64
  535. if chkOverflow32 {
  536. bitsize = 32
  537. }
  538. f, err := strconv.ParseFloat(stringView(bs), bitsize)
  539. if err != nil {
  540. d.d.errorf("json: decode float from %s: %v", bs, err)
  541. return
  542. }
  543. return
  544. }
  545. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  546. if ext == nil {
  547. re := rv.(*RawExt)
  548. re.Tag = xtag
  549. d.d.decode(&re.Value)
  550. } else {
  551. var v interface{}
  552. d.d.decode(&v)
  553. ext.UpdateExt(rv, v)
  554. }
  555. return
  556. }
  557. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  558. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  559. if d.se.i != nil {
  560. bsOut = bs
  561. d.DecodeExt(&bsOut, 0, &d.se)
  562. return
  563. }
  564. d.appendStringAsBytes()
  565. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  566. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  567. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  568. // However, it sets a fnull field to true, so we can check if a null was found.
  569. if len(d.bs) == 0 {
  570. if d.fnull {
  571. return nil
  572. }
  573. return []byte{}
  574. }
  575. bs0 := d.bs
  576. slen := base64.StdEncoding.DecodedLen(len(bs0))
  577. if slen <= cap(bs) {
  578. bsOut = bs[:slen]
  579. } else if zerocopy && slen <= cap(d.b2) {
  580. bsOut = d.b2[:slen]
  581. } else {
  582. bsOut = make([]byte, slen)
  583. }
  584. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  585. if err != nil {
  586. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  587. return nil
  588. }
  589. if slen != slen2 {
  590. bsOut = bsOut[:slen2]
  591. }
  592. return
  593. }
  594. const jsonAlwaysReturnInternString = false
  595. func (d *jsonDecDriver) DecodeString() (s string) {
  596. d.appendStringAsBytes()
  597. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  598. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  599. return d.d.string(d.bs)
  600. }
  601. return string(d.bs)
  602. }
  603. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  604. d.appendStringAsBytes()
  605. return d.bs
  606. }
  607. func (d *jsonDecDriver) appendStringAsBytes() {
  608. if d.tok == 0 {
  609. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  610. }
  611. d.fnull = false
  612. if d.tok != '"' {
  613. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  614. // handle non-string scalar: null, true, false or a number
  615. switch d.tok {
  616. case 'n':
  617. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  618. d.bs = d.bs[:0]
  619. d.fnull = true
  620. case 'f':
  621. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  622. d.bs = d.bs[:5]
  623. copy(d.bs, "false")
  624. case 't':
  625. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  626. d.bs = d.bs[:4]
  627. copy(d.bs, "true")
  628. default:
  629. // try to parse a valid number
  630. bs := d.decNumBytes()
  631. d.bs = d.bs[:len(bs)]
  632. copy(d.bs, bs)
  633. }
  634. return
  635. }
  636. d.tok = 0
  637. r := d.r
  638. var cs []byte
  639. v := d.bs[:0]
  640. var c uint8
  641. for i := 0; ; i++ {
  642. if i == len(cs) {
  643. cs = r.readUntil(d.b2[:0], '"')
  644. i = 0
  645. }
  646. c = cs[i]
  647. if c == '"' {
  648. break
  649. }
  650. if c != '\\' {
  651. v = append(v, c)
  652. continue
  653. }
  654. // cs[i] == '\\'
  655. i++
  656. c = cs[i]
  657. switch c {
  658. case '"', '\\', '/', '\'':
  659. v = append(v, c)
  660. case 'b':
  661. v = append(v, '\b')
  662. case 'f':
  663. v = append(v, '\f')
  664. case 'n':
  665. v = append(v, '\n')
  666. case 'r':
  667. v = append(v, '\r')
  668. case 't':
  669. v = append(v, '\t')
  670. case 'u':
  671. rr := d.jsonU4Arr([4]byte{cs[i+1], cs[i+2], cs[i+3], cs[i+4]})
  672. i += 4
  673. if utf16.IsSurrogate(rr) {
  674. if !(cs[i+1] == '\\' && cs[i+2] == 'u') {
  675. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  676. return
  677. }
  678. i += 2
  679. rr = utf16.DecodeRune(rr, d.jsonU4Arr([4]byte{cs[i+1], cs[i+2], cs[i+3], cs[i+4]}))
  680. i += 4
  681. }
  682. w2 := utf8.EncodeRune(d.bstr[:], rr)
  683. v = append(v, d.bstr[:w2]...)
  684. default:
  685. d.d.errorf("json: unsupported escaped value: %c", c)
  686. }
  687. }
  688. d.bs = v
  689. }
  690. func (d *jsonDecDriver) jsonU4Arr(bs [4]byte) (r rune) {
  691. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  692. var u uint32
  693. for _, v := range bs {
  694. if '0' <= v && v <= '9' {
  695. v = v - '0'
  696. } else if 'a' <= v && v <= 'z' {
  697. v = v - 'a' + 10
  698. } else if 'A' <= v && v <= 'Z' {
  699. v = v - 'A' + 10
  700. } else {
  701. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  702. return 0
  703. }
  704. u = u*16 + uint32(v)
  705. }
  706. return rune(u)
  707. }
  708. func (d *jsonDecDriver) DecodeNaked() {
  709. z := d.d.n
  710. // var decodeFurther bool
  711. if d.tok == 0 {
  712. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  713. }
  714. switch d.tok {
  715. case 'n':
  716. d.readSymbol3('u', 'l', 'l') // d.readLiteralIdx(10, 13) // ull
  717. z.v = valueTypeNil
  718. case 'f':
  719. d.readSymbol4('a', 'l', 's', 'e') // d.readLiteralIdx(5, 9) // alse
  720. z.v = valueTypeBool
  721. z.b = false
  722. case 't':
  723. d.readSymbol3('r', 'u', 'e') // d.readLiteralIdx(1, 4) // rue
  724. z.v = valueTypeBool
  725. z.b = true
  726. case '{':
  727. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  728. case '[':
  729. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  730. case '"':
  731. z.v = valueTypeString
  732. z.s = d.DecodeString()
  733. default: // number
  734. bs := d.decNumBytes()
  735. var err error
  736. if len(bs) == 0 {
  737. d.d.errorf("json: decode number from empty string")
  738. return
  739. } else if d.h.PreferFloat ||
  740. bytes.IndexByte(bs, '.') != -1 ||
  741. bytes.IndexByte(bs, 'e') != -1 ||
  742. bytes.IndexByte(bs, 'E') != -1 {
  743. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  744. z.v = valueTypeFloat
  745. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  746. } else if d.h.SignedInteger || bs[0] == '-' {
  747. z.v = valueTypeInt
  748. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  749. } else {
  750. z.v = valueTypeUint
  751. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  752. }
  753. if err != nil {
  754. if z.v == valueTypeInt || z.v == valueTypeUint {
  755. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  756. z.v = valueTypeFloat
  757. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  758. }
  759. }
  760. if err != nil {
  761. d.d.errorf("json: decode number from %s: %v", bs, err)
  762. return
  763. }
  764. }
  765. }
  766. // if decodeFurther {
  767. // d.s.sc.retryRead()
  768. // }
  769. return
  770. }
  771. //----------------------
  772. // JsonHandle is a handle for JSON encoding format.
  773. //
  774. // Json is comprehensively supported:
  775. // - decodes numbers into interface{} as int, uint or float64
  776. // - configurable way to encode/decode []byte .
  777. // by default, encodes and decodes []byte using base64 Std Encoding
  778. // - UTF-8 support for encoding and decoding
  779. //
  780. // It has better performance than the json library in the standard library,
  781. // by leveraging the performance improvements of the codec library and
  782. // minimizing allocations.
  783. //
  784. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  785. // reading multiple values from a stream containing json and non-json content.
  786. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  787. // all from the same stream in sequence.
  788. type JsonHandle struct {
  789. textEncodingType
  790. BasicHandle
  791. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  792. // If not configured, raw bytes are encoded to/from base64 text.
  793. RawBytesExt InterfaceExt
  794. // Indent indicates how a value is encoded.
  795. // - If positive, indent by that number of spaces.
  796. // - If negative, indent by that number of tabs.
  797. Indent int8
  798. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  799. //
  800. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  801. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  802. // This can be mitigated by configuring how to encode integers.
  803. //
  804. // IntegerAsString interpretes the following values:
  805. // - if 'L', then encode integers > 2^53 as a json string.
  806. // - if 'A', then encode all integers as a json string
  807. // containing the exact integer representation as a decimal.
  808. // - else encode all integers as a json number (default)
  809. IntegerAsString uint8
  810. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  811. //
  812. // By default, we encode them as \uXXX
  813. // to prevent security holes when served from some browsers.
  814. HTMLCharsAsIs bool
  815. // PreferFloat says that we will default to decoding a number as a float.
  816. // If not set, we will examine the characters of the number and decode as an
  817. // integer type if it doesn't have any of the characters [.eE].
  818. PreferFloat bool
  819. }
  820. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  821. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  822. }
  823. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  824. hd := jsonEncDriver{e: e, h: h}
  825. hd.bs = hd.b[:0]
  826. hd.reset()
  827. return &hd
  828. }
  829. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  830. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  831. hd := jsonDecDriver{d: d, h: h}
  832. hd.bs = hd.b[:0]
  833. hd.reset()
  834. return &hd
  835. }
  836. func (e *jsonEncDriver) reset() {
  837. e.w = e.e.w
  838. e.se.i = e.h.RawBytesExt
  839. if e.bs != nil {
  840. e.bs = e.bs[:0]
  841. }
  842. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  843. e.c = 0
  844. if e.h.Indent > 0 {
  845. e.d = true
  846. e.ds = jsonSpaces[:e.h.Indent]
  847. } else if e.h.Indent < 0 {
  848. e.d = true
  849. e.dt = true
  850. e.ds = jsonTabs[:-(e.h.Indent)]
  851. }
  852. }
  853. func (d *jsonDecDriver) reset() {
  854. d.r = d.d.r
  855. d.se.i = d.h.RawBytesExt
  856. if d.bs != nil {
  857. d.bs = d.bs[:0]
  858. }
  859. d.c, d.tok = 0, 0
  860. // d.n.reset()
  861. }
  862. var jsonEncodeTerminate = []byte{' '}
  863. func (h *JsonHandle) rpcEncodeTerminate() []byte {
  864. return jsonEncodeTerminate
  865. }
  866. var _ decDriver = (*jsonDecDriver)(nil)
  867. var _ encDriver = (*jsonEncDriver)(nil)