json.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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 [utf8.RuneSelf]bool
  53. jsonCharSafeSet [utf8.RuneSelf]bool
  54. jsonCharWhitespaceSet [256]bool
  55. jsonNumSet [256]bool
  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. for i := 32; i < utf8.RuneSelf; i++ {
  88. switch i {
  89. case '"', '\\':
  90. jsonCharSafeSet[i] = false
  91. jsonCharHtmlSafeSet[i] = false
  92. case '<', '>', '&':
  93. jsonCharHtmlSafeSet[i] = false
  94. jsonCharSafeSet[i] = true
  95. default:
  96. jsonCharSafeSet[i] = true
  97. jsonCharHtmlSafeSet[i] = true
  98. }
  99. }
  100. for i := 0; i < 256; i++ {
  101. switch i {
  102. case ' ', '\t', '\r', '\n':
  103. jsonCharWhitespaceSet[i] = true
  104. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
  105. jsonNumSet[i] = true
  106. }
  107. }
  108. }
  109. type jsonEncDriver struct {
  110. e *Encoder
  111. w encWriter
  112. h *JsonHandle
  113. b [64]byte // scratch
  114. bs []byte // scratch
  115. se setExtWrapper
  116. ds string // indent string
  117. dl uint16 // indent level
  118. dt bool // indent using tabs
  119. d bool // indent
  120. c containerState
  121. noBuiltInTypes
  122. }
  123. // indent is done as below:
  124. // - newline and indent are added before each mapKey or arrayElem
  125. // - newline and indent are added before each ending,
  126. // except there was no entry (so we can have {} or [])
  127. func (e *jsonEncDriver) sendContainerState(c containerState) {
  128. // determine whether to output separators
  129. if c == containerMapKey {
  130. if e.c != containerMapStart {
  131. e.w.writen1(',')
  132. }
  133. if e.d {
  134. e.writeIndent()
  135. }
  136. } else if c == containerMapValue {
  137. if e.d {
  138. e.w.writen2(':', ' ')
  139. } else {
  140. e.w.writen1(':')
  141. }
  142. } else if c == containerMapEnd {
  143. if e.d {
  144. e.dl--
  145. if e.c != containerMapStart {
  146. e.writeIndent()
  147. }
  148. }
  149. e.w.writen1('}')
  150. } else if c == containerArrayElem {
  151. if e.c != containerArrayStart {
  152. e.w.writen1(',')
  153. }
  154. if e.d {
  155. e.writeIndent()
  156. }
  157. } else if c == containerArrayEnd {
  158. if e.d {
  159. e.dl--
  160. if e.c != containerArrayStart {
  161. e.writeIndent()
  162. }
  163. }
  164. e.w.writen1(']')
  165. }
  166. e.c = c
  167. }
  168. func (e *jsonEncDriver) writeIndent() {
  169. e.w.writen1('\n')
  170. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  171. if e.dt {
  172. e.w.writestr(jsonTabs[:x])
  173. } else {
  174. e.w.writestr(jsonSpaces[:x])
  175. }
  176. } else {
  177. for i := uint16(0); i < e.dl; i++ {
  178. e.w.writestr(e.ds)
  179. }
  180. }
  181. }
  182. func (e *jsonEncDriver) EncodeNil() {
  183. e.w.writeb(jsonLiterals[9:13]) // null
  184. }
  185. func (e *jsonEncDriver) EncodeBool(b bool) {
  186. if b {
  187. e.w.writeb(jsonLiterals[0:4]) // true
  188. } else {
  189. e.w.writeb(jsonLiterals[4:9]) // false
  190. }
  191. }
  192. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  193. e.encodeFloat(float64(f), 32)
  194. }
  195. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  196. // e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64))
  197. e.encodeFloat(f, 64)
  198. }
  199. func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
  200. x := strconv.AppendFloat(e.b[:0], f, 'G', -1, numbits)
  201. e.w.writeb(x)
  202. if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
  203. e.w.writen2('.', '0')
  204. }
  205. }
  206. func (e *jsonEncDriver) EncodeInt(v int64) {
  207. // if e.h.IntegerAsString == 'A' || e.h.IntegerAsString == 'L' && (v > 1<<53 || v < -(1<<53)) {
  208. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) {
  209. e.w.writen1('"')
  210. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  211. e.w.writen1('"')
  212. return
  213. }
  214. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  215. }
  216. func (e *jsonEncDriver) EncodeUint(v uint64) {
  217. // if e.h.IntegerAsString == 'A' || e.h.IntegerAsString == 'L' && v > 1<<53 {
  218. if x := e.h.IntegerAsString; x == 'A' || x == 'L' && v > 1<<53 {
  219. e.w.writen1('"')
  220. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  221. e.w.writen1('"')
  222. return
  223. }
  224. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  225. }
  226. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  227. if v := ext.ConvertExt(rv); v == nil {
  228. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  229. } else {
  230. en.encode(v)
  231. }
  232. }
  233. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  234. // only encodes re.Value (never re.Data)
  235. if re.Value == nil {
  236. e.w.writeb(jsonLiterals[9:13]) // null // e.EncodeNil()
  237. } else {
  238. en.encode(re.Value)
  239. }
  240. }
  241. func (e *jsonEncDriver) EncodeArrayStart(length int) {
  242. if e.d {
  243. e.dl++
  244. }
  245. e.w.writen1('[')
  246. e.c = containerArrayStart
  247. }
  248. func (e *jsonEncDriver) EncodeMapStart(length int) {
  249. if e.d {
  250. e.dl++
  251. }
  252. e.w.writen1('{')
  253. e.c = containerMapStart
  254. }
  255. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  256. // e.w.writestr(strconv.Quote(v))
  257. e.quoteStr(v)
  258. }
  259. func (e *jsonEncDriver) EncodeSymbol(v string) {
  260. // e.EncodeString(c_UTF8, v)
  261. e.quoteStr(v)
  262. }
  263. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  264. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  265. if c == c_RAW && e.se.i != nil {
  266. e.EncodeExt(v, 0, &e.se, e.e)
  267. return
  268. }
  269. if c == c_RAW {
  270. slen := base64.StdEncoding.EncodedLen(len(v))
  271. if cap(e.bs) >= slen {
  272. e.bs = e.bs[:slen]
  273. } else {
  274. e.bs = make([]byte, slen)
  275. }
  276. base64.StdEncoding.Encode(e.bs, v)
  277. e.w.writen1('"')
  278. e.w.writeb(e.bs)
  279. e.w.writen1('"')
  280. } else {
  281. // e.EncodeString(c, string(v))
  282. e.quoteStr(stringView(v))
  283. }
  284. }
  285. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  286. e.w.writeb(v)
  287. }
  288. func (e *jsonEncDriver) quoteStr(s string) {
  289. // adapted from std pkg encoding/json
  290. const hex = "0123456789abcdef"
  291. w := e.w
  292. w.writen1('"')
  293. start := 0
  294. for i := 0; i < len(s); {
  295. // encode all bytes < 0x20 (except \r, \n).
  296. // also encode < > & to prevent security holes when served to some browsers.
  297. if b := s[i]; b < utf8.RuneSelf {
  298. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  299. if jsonCharHtmlSafeSet[b] || (e.h.HTMLCharsAsIs && jsonCharSafeSet[b]) {
  300. i++
  301. continue
  302. }
  303. if start < i {
  304. w.writestr(s[start:i])
  305. }
  306. switch b {
  307. case '\\', '"':
  308. w.writen2('\\', b)
  309. case '\n':
  310. w.writen2('\\', 'n')
  311. case '\r':
  312. w.writen2('\\', 'r')
  313. case '\b':
  314. w.writen2('\\', 'b')
  315. case '\f':
  316. w.writen2('\\', 'f')
  317. case '\t':
  318. w.writen2('\\', 't')
  319. default:
  320. w.writestr(`\u00`)
  321. w.writen2(hex[b>>4], hex[b&0xF])
  322. }
  323. i++
  324. start = i
  325. continue
  326. }
  327. c, size := utf8.DecodeRuneInString(s[i:])
  328. if c == utf8.RuneError && size == 1 {
  329. if start < i {
  330. w.writestr(s[start:i])
  331. }
  332. w.writestr(`\ufffd`)
  333. i += size
  334. start = i
  335. continue
  336. }
  337. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  338. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  339. if c == '\u2028' || c == '\u2029' {
  340. if start < i {
  341. w.writestr(s[start:i])
  342. }
  343. w.writestr(`\u202`)
  344. w.writen1(hex[c&0xF])
  345. i += size
  346. start = i
  347. continue
  348. }
  349. i += size
  350. }
  351. if start < len(s) {
  352. w.writestr(s[start:])
  353. }
  354. w.writen1('"')
  355. }
  356. type jsonDecDriver struct {
  357. noBuiltInTypes
  358. d *Decoder
  359. h *JsonHandle
  360. r decReader
  361. c containerState
  362. // tok is used to store the token read right after skipWhiteSpace.
  363. tok uint8
  364. bstr [8]byte // scratch used for string \UXXX parsing
  365. b [64]byte // scratch, used for parsing strings or numbers
  366. b2 [64]byte // scratch, used only for decodeBytes (after base64)
  367. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  368. se setExtWrapper
  369. // n jsonNum
  370. }
  371. func jsonIsWS(b byte) bool {
  372. // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  373. return jsonCharWhitespaceSet[b]
  374. }
  375. func (d *jsonDecDriver) uncacheRead() {
  376. if d.tok != 0 {
  377. d.r.unreadn1()
  378. d.tok = 0
  379. }
  380. }
  381. func (d *jsonDecDriver) sendContainerState(c containerState) {
  382. if d.tok == 0 {
  383. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  384. }
  385. var xc uint8 // char expected
  386. if c == containerMapKey {
  387. if d.c != containerMapStart {
  388. xc = ','
  389. }
  390. } else if c == containerMapValue {
  391. xc = ':'
  392. } else if c == containerMapEnd {
  393. xc = '}'
  394. } else if c == containerArrayElem {
  395. if d.c != containerArrayStart {
  396. xc = ','
  397. }
  398. } else if c == containerArrayEnd {
  399. xc = ']'
  400. }
  401. if xc != 0 {
  402. if d.tok != xc {
  403. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  404. }
  405. d.tok = 0
  406. }
  407. d.c = c
  408. }
  409. func (d *jsonDecDriver) CheckBreak() bool {
  410. if d.tok == 0 {
  411. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  412. }
  413. return d.tok == '}' || d.tok == ']'
  414. }
  415. func (d *jsonDecDriver) readStrIdx(fromIdx, toIdx uint8) {
  416. bs := d.r.readx(int(toIdx - fromIdx))
  417. d.tok = 0
  418. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:toIdx]) {
  419. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:toIdx], bs)
  420. return
  421. }
  422. }
  423. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  424. if d.tok == 0 {
  425. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  426. }
  427. if d.tok == 'n' {
  428. d.readStrIdx(10, 13) // ull
  429. return true
  430. }
  431. return false
  432. }
  433. func (d *jsonDecDriver) DecodeBool() bool {
  434. if d.tok == 0 {
  435. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  436. }
  437. if d.tok == 'f' {
  438. d.readStrIdx(5, 9) // alse
  439. return false
  440. }
  441. if d.tok == 't' {
  442. d.readStrIdx(1, 4) // rue
  443. return true
  444. }
  445. d.d.errorf("json: decode bool: got first char %c", d.tok)
  446. return false // "unreachable"
  447. }
  448. func (d *jsonDecDriver) ReadMapStart() int {
  449. if d.tok == 0 {
  450. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  451. }
  452. if d.tok != '{' {
  453. d.d.errorf("json: expect char '%c' but got char '%c'", '{', d.tok)
  454. }
  455. d.tok = 0
  456. d.c = containerMapStart
  457. return -1
  458. }
  459. func (d *jsonDecDriver) ReadArrayStart() 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 = containerArrayStart
  468. return -1
  469. }
  470. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  471. // check container type by checking the first char
  472. if d.tok == 0 {
  473. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  474. }
  475. if b := d.tok; b == '{' {
  476. return valueTypeMap
  477. } else if b == '[' {
  478. return valueTypeArray
  479. } else if b == 'n' {
  480. return valueTypeNil
  481. } else if b == '"' {
  482. return valueTypeString
  483. }
  484. return valueTypeUnset
  485. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  486. // return false // "unreachable"
  487. }
  488. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  489. // stores num bytes in d.bs
  490. if d.tok == 0 {
  491. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  492. }
  493. if d.tok == '"' {
  494. bs = d.r.readUntil(d.b2[:0], '"')
  495. bs = bs[:len(bs)-1]
  496. } else {
  497. d.r.unreadn1()
  498. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  499. // bs = d.r.readbUntilAny(d.bs[:0], " \t\n:,{}[]")
  500. }
  501. d.tok = 0
  502. // fmt.Printf(">>>> decNumBytes: returning: '%s'\n", bs)
  503. return bs
  504. }
  505. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  506. bs := d.decNumBytes()
  507. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  508. if err != nil {
  509. d.d.errorf("json: decode uint from %s: %v", bs, err)
  510. return
  511. }
  512. return
  513. }
  514. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  515. bs := d.decNumBytes()
  516. // if bytes.ContainsAny(bs, ".eE") {
  517. // d.d.errorf("json: decoding int, but found one or more of the chars: .eE: %s", bs)
  518. // return
  519. // }
  520. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  521. if err != nil {
  522. d.d.errorf("json: decode int from %s: %v", bs, err)
  523. return
  524. }
  525. return
  526. }
  527. func (d *jsonDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  528. bs := d.decNumBytes()
  529. bitsize := 64
  530. if chkOverflow32 {
  531. bitsize = 32
  532. }
  533. f, err := strconv.ParseFloat(stringView(bs), bitsize)
  534. if err != nil {
  535. d.d.errorf("json: decode float from %s: %v", bs, err)
  536. return
  537. }
  538. return
  539. }
  540. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  541. if ext == nil {
  542. re := rv.(*RawExt)
  543. re.Tag = xtag
  544. d.d.decode(&re.Value)
  545. } else {
  546. var v interface{}
  547. d.d.decode(&v)
  548. ext.UpdateExt(rv, v)
  549. }
  550. return
  551. }
  552. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  553. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  554. if d.se.i != nil {
  555. bsOut = bs
  556. d.DecodeExt(&bsOut, 0, &d.se)
  557. return
  558. }
  559. d.appendStringAsBytes()
  560. // if appendStringAsBytes returned a zero-len slice, then treat as nil.
  561. // This should only happen for null, and "".
  562. if len(d.bs) == 0 {
  563. return nil
  564. }
  565. bs0 := d.bs
  566. slen := base64.StdEncoding.DecodedLen(len(bs0))
  567. if slen <= cap(bs) {
  568. bsOut = bs[:slen]
  569. } else if zerocopy && slen <= cap(d.b2) {
  570. bsOut = d.b2[:slen]
  571. } else {
  572. bsOut = make([]byte, slen)
  573. }
  574. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  575. if err != nil {
  576. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  577. return nil
  578. }
  579. if slen != slen2 {
  580. bsOut = bsOut[:slen2]
  581. }
  582. return
  583. }
  584. const jsonAlwaysReturnInternString = false
  585. func (d *jsonDecDriver) DecodeString() (s string) {
  586. d.appendStringAsBytes()
  587. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  588. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  589. return d.d.string(d.bs)
  590. }
  591. return string(d.bs)
  592. }
  593. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  594. d.appendStringAsBytes()
  595. return d.bs
  596. }
  597. func (d *jsonDecDriver) appendStringAsBytes() {
  598. if d.tok == 0 {
  599. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  600. }
  601. if d.tok != '"' {
  602. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  603. // handle non-string scalar: null, true, false or a number
  604. switch d.tok {
  605. case 'n':
  606. d.readStrIdx(10, 13) // ull
  607. d.bs = d.bs[:0]
  608. case 'f':
  609. d.readStrIdx(5, 9) // alse
  610. d.bs = d.bs[:5]
  611. copy(d.bs, "false")
  612. case 't':
  613. d.readStrIdx(1, 4) // rue
  614. d.bs = d.bs[:4]
  615. copy(d.bs, "true")
  616. default:
  617. // try to parse a valid number
  618. bs := d.decNumBytes()
  619. d.bs = d.bs[:len(bs)]
  620. copy(d.bs, bs)
  621. }
  622. return
  623. }
  624. d.tok = 0
  625. r := d.r
  626. var cs []byte
  627. v := d.bs[:0]
  628. // var c uint8
  629. for i := 0; ; i++ {
  630. if i == len(cs) {
  631. cs = r.readUntil(d.b2[:0], '"')
  632. i = 0
  633. }
  634. if cs[i] == '"' {
  635. break
  636. }
  637. if cs[i] != '\\' {
  638. v = append(v, cs[i])
  639. continue
  640. }
  641. // cs[i] == '\\'
  642. i++
  643. switch cs[i] {
  644. case '"', '\\', '/', '\'':
  645. v = append(v, cs[i])
  646. case 'b':
  647. v = append(v, '\b')
  648. case 'f':
  649. v = append(v, '\f')
  650. case 'n':
  651. v = append(v, '\n')
  652. case 'r':
  653. v = append(v, '\r')
  654. case 't':
  655. v = append(v, '\t')
  656. case 'u':
  657. rr := d.jsonU4Arr([4]byte{cs[i+1], cs[i+2], cs[i+3], cs[i+4]})
  658. i += 4
  659. // fmt.Printf("$$$$$$$$$: is surrogate: %v\n", utf16.IsSurrogate(rr))
  660. if utf16.IsSurrogate(rr) {
  661. // fmt.Printf(">>>> checking utf16 surrogate\n")
  662. if !(cs[i+1] == '\\' && cs[i+2] == 'u') {
  663. d.d.errorf(`json: unquoteStr: invalid unicode sequence. Expecting \u`)
  664. return
  665. }
  666. i += 2
  667. rr = utf16.DecodeRune(rr, d.jsonU4Arr([4]byte{cs[i+1], cs[i+2], cs[i+3], cs[i+4]}))
  668. i += 4
  669. }
  670. w2 := utf8.EncodeRune(d.bstr[:], rr)
  671. v = append(v, d.bstr[:w2]...)
  672. default:
  673. d.d.errorf("json: unsupported escaped value: %c", cs[i])
  674. }
  675. }
  676. d.bs = v
  677. }
  678. func (d *jsonDecDriver) jsonU4Arr(bs [4]byte) (r rune) {
  679. // u, _ := strconv.ParseUint(string(d.bstr[:4]), 16, 64)
  680. var u uint32
  681. for _, v := range bs {
  682. if '0' <= v && v <= '9' {
  683. v = v - '0'
  684. } else if 'a' <= v && v <= 'z' {
  685. v = v - 'a' + 10
  686. } else if 'A' <= v && v <= 'Z' {
  687. v = v - 'A' + 10
  688. } else {
  689. d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, v)
  690. return 0
  691. }
  692. u = u*16 + uint32(v)
  693. }
  694. // fmt.Printf(">>>>>>>> jsonU4Arr: %v, %s\n", rune(u), string(rune(u)))
  695. return rune(u)
  696. }
  697. func (d *jsonDecDriver) DecodeNaked() {
  698. z := &d.d.n
  699. // var decodeFurther bool
  700. if d.tok == 0 {
  701. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  702. }
  703. switch d.tok {
  704. case 'n':
  705. d.readStrIdx(10, 13) // ull
  706. z.v = valueTypeNil
  707. case 'f':
  708. d.readStrIdx(5, 9) // alse
  709. z.v = valueTypeBool
  710. z.b = false
  711. case 't':
  712. d.readStrIdx(1, 4) // rue
  713. z.v = valueTypeBool
  714. z.b = true
  715. case '{':
  716. z.v = valueTypeMap
  717. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadMapStart
  718. // decodeFurther = true
  719. case '[':
  720. z.v = valueTypeArray
  721. // d.tok = 0 // don't consume. kInterfaceNaked will call ReadArrayStart
  722. // decodeFurther = true
  723. case '"':
  724. z.v = valueTypeString
  725. z.s = d.DecodeString()
  726. default: // number
  727. bs := d.decNumBytes()
  728. var err error
  729. if len(bs) == 0 {
  730. d.d.errorf("json: decode number from empty string")
  731. return
  732. } else if d.h.PreferFloat ||
  733. bytes.IndexByte(bs, '.') != -1 ||
  734. bytes.IndexByte(bs, 'e') != -1 ||
  735. bytes.IndexByte(bs, 'E') != -1 {
  736. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  737. z.v = valueTypeFloat
  738. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  739. } else if d.h.SignedInteger || bs[0] == '-' {
  740. z.v = valueTypeInt
  741. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  742. } else {
  743. z.v = valueTypeUint
  744. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  745. }
  746. if err != nil {
  747. if z.v == valueTypeInt || z.v == valueTypeUint {
  748. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  749. z.v = valueTypeFloat
  750. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  751. }
  752. }
  753. if err != nil {
  754. d.d.errorf("json: decode number from %s: %v", bs, err)
  755. return
  756. }
  757. }
  758. // fmt.Printf("DecodeNaked: Number: %T, %v\n", v, v)
  759. }
  760. // if decodeFurther {
  761. // d.s.sc.retryRead()
  762. // }
  763. return
  764. }
  765. // func jsonAcceptNonWS(b byte) bool {
  766. // return !jsonCharWhitespaceSet[b]
  767. // }
  768. // func jsonAcceptDQuote(b byte) bool {
  769. // return b == '"'
  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)