json.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. "math"
  34. "reflect"
  35. "strconv"
  36. "time"
  37. "unicode"
  38. "unicode/utf16"
  39. "unicode/utf8"
  40. )
  41. //--------------------------------
  42. var jsonLiterals = [...]byte{
  43. '"',
  44. 't', 'r', 'u', 'e',
  45. '"',
  46. '"',
  47. 'f', 'a', 'l', 's', 'e',
  48. '"',
  49. '"',
  50. 'n', 'u', 'l', 'l',
  51. '"',
  52. }
  53. const (
  54. jsonLitTrueQ = 0
  55. jsonLitTrue = 1
  56. jsonLitFalseQ = 6
  57. jsonLitFalse = 7
  58. jsonLitNullQ = 13
  59. jsonLitNull = 14
  60. )
  61. var (
  62. // jsonFloat64Pow10 = [...]float64{
  63. // 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  64. // 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  65. // 1e20, 1e21, 1e22,
  66. // }
  67. // jsonUint64Pow10 = [...]uint64{
  68. // 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  69. // 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  70. // }
  71. // jsonTabs and jsonSpaces are used as caches for indents
  72. jsonTabs, jsonSpaces string
  73. jsonCharHtmlSafeSet bitset128
  74. jsonCharSafeSet bitset128
  75. jsonCharWhitespaceSet bitset256
  76. jsonNumSet bitset256
  77. // jsonIsFloatSet bitset256
  78. jsonU4Set [256]byte
  79. )
  80. const (
  81. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  82. // - If we see first character of null, false or true,
  83. // do not validate subsequent characters.
  84. // - e.g. if we see a n, assume null and skip next 3 characters,
  85. // and do not validate they are ull.
  86. // P.S. Do not expect a significant decoding boost from this.
  87. jsonValidateSymbols = true
  88. jsonSpacesOrTabsLen = 128
  89. jsonU4SetErrVal = 128
  90. jsonAlwaysReturnInternString = false
  91. )
  92. func init() {
  93. var bs [jsonSpacesOrTabsLen]byte
  94. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  95. bs[i] = ' '
  96. }
  97. jsonSpaces = string(bs[:])
  98. for i := 0; i < jsonSpacesOrTabsLen; i++ {
  99. bs[i] = '\t'
  100. }
  101. jsonTabs = string(bs[:])
  102. // populate the safe values as true: note: ASCII control characters are (0-31)
  103. // jsonCharSafeSet: all true except (0-31) " \
  104. // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
  105. var i byte
  106. for i = 32; i < utf8.RuneSelf; i++ {
  107. switch i {
  108. case '"', '\\':
  109. case '<', '>', '&':
  110. jsonCharSafeSet.set(i) // = true
  111. default:
  112. jsonCharSafeSet.set(i)
  113. jsonCharHtmlSafeSet.set(i)
  114. }
  115. }
  116. for i = 0; i <= utf8.RuneSelf; i++ {
  117. switch i {
  118. case ' ', '\t', '\r', '\n':
  119. jsonCharWhitespaceSet.set(i)
  120. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
  121. jsonNumSet.set(i)
  122. }
  123. }
  124. for j := range jsonU4Set {
  125. switch i = byte(j); i {
  126. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  127. jsonU4Set[i] = i - '0'
  128. case 'a', 'b', 'c', 'd', 'e', 'f':
  129. jsonU4Set[i] = i - 'a' + 10
  130. case 'A', 'B', 'C', 'D', 'E', 'F':
  131. jsonU4Set[i] = i - 'A' + 10
  132. default:
  133. jsonU4Set[i] = jsonU4SetErrVal
  134. }
  135. // switch i = byte(j); i {
  136. // case 'e', 'E', '.':
  137. // jsonIsFloatSet.set(i)
  138. // }
  139. }
  140. // jsonU4Set[255] = jsonU4SetErrVal
  141. }
  142. type jsonEncDriver struct {
  143. noBuiltInTypes
  144. e *Encoder
  145. h *JsonHandle
  146. w encWriter // encWriter // *encWriterSwitch
  147. se setExtWrapper
  148. // ---- cpu cache line boundary?
  149. ds string // indent string
  150. d bool // indent
  151. dt bool // indent using tabs
  152. // ---- writable fields during execution --- *try* to keep in sep cache line
  153. c containerState
  154. dl uint16 // indent level
  155. bs []byte // scratch
  156. // ---- cpu cache line boundary?
  157. b [64]byte // scratch
  158. }
  159. // indent is done as below:
  160. // - newline and indent are added before each mapKey or arrayElem
  161. // - newline and indent are added before each ending,
  162. // except there was no entry (so we can have {} or [])
  163. func (e *jsonEncDriver) WriteArrayStart(length int) {
  164. if e.d {
  165. e.dl++
  166. }
  167. e.w.writen1('[')
  168. e.c = containerArrayStart
  169. }
  170. func (e *jsonEncDriver) WriteArrayElem() {
  171. if e.c != containerArrayStart {
  172. e.w.writen1(',')
  173. }
  174. if e.d {
  175. e.writeIndent()
  176. }
  177. e.c = containerArrayElem
  178. }
  179. func (e *jsonEncDriver) WriteArrayEnd() {
  180. if e.d {
  181. e.dl--
  182. if e.c != containerArrayStart {
  183. e.writeIndent()
  184. }
  185. }
  186. e.w.writen1(']')
  187. e.c = containerArrayEnd
  188. }
  189. func (e *jsonEncDriver) WriteMapStart(length int) {
  190. if e.d {
  191. e.dl++
  192. }
  193. e.w.writen1('{')
  194. e.c = containerMapStart
  195. }
  196. func (e *jsonEncDriver) WriteMapElemKey() {
  197. if e.c != containerMapStart {
  198. e.w.writen1(',')
  199. }
  200. if e.d {
  201. e.writeIndent()
  202. }
  203. e.c = containerMapKey
  204. }
  205. func (e *jsonEncDriver) WriteMapElemValue() {
  206. if e.d {
  207. e.w.writen2(':', ' ')
  208. } else {
  209. e.w.writen1(':')
  210. }
  211. e.c = containerMapValue
  212. }
  213. func (e *jsonEncDriver) WriteMapEnd() {
  214. if e.d {
  215. e.dl--
  216. if e.c != containerMapStart {
  217. e.writeIndent()
  218. }
  219. }
  220. e.w.writen1('}')
  221. e.c = containerMapEnd
  222. }
  223. func (e *jsonEncDriver) writeIndent() {
  224. e.w.writen1('\n')
  225. if x := len(e.ds) * int(e.dl); x <= jsonSpacesOrTabsLen {
  226. if e.dt {
  227. e.w.writestr(jsonTabs[:x])
  228. } else {
  229. e.w.writestr(jsonSpaces[:x])
  230. }
  231. } else {
  232. for i := uint16(0); i < e.dl; i++ {
  233. e.w.writestr(e.ds)
  234. }
  235. }
  236. }
  237. func (e *jsonEncDriver) EncodeNil() {
  238. // We always encode nil as just null (never in quotes)
  239. // This allows us to easily decode if a nil in the json stream
  240. // ie if initial token is n.
  241. e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
  242. // if e.h.MapKeyAsString && e.c == containerMapKey {
  243. // e.w.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6])
  244. // } else {
  245. // e.w.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
  246. // }
  247. }
  248. func (e *jsonEncDriver) EncodeTime(t time.Time) {
  249. // Do NOT use MarshalJSON, as it allocates internally.
  250. // instead, we call AppendFormat directly, using our scratch buffer (e.b)
  251. if t.IsZero() {
  252. e.EncodeNil()
  253. } else {
  254. e.b[0] = '"'
  255. b := t.AppendFormat(e.b[1:1], time.RFC3339Nano)
  256. e.b[len(b)+1] = '"'
  257. e.w.writeb(e.b[:len(b)+2])
  258. }
  259. // fmt.Printf(">>>> time as a string: '%s'\n", e.b[:len(b)+2])
  260. // v, err := t.MarshalJSON(); if err != nil { e.e.error(err) } e.w.writeb(v)
  261. }
  262. func (e *jsonEncDriver) EncodeBool(b bool) {
  263. if e.h.MapKeyAsString && e.c == containerMapKey {
  264. if b {
  265. e.w.writeb(jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6])
  266. } else {
  267. e.w.writeb(jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7])
  268. }
  269. } else {
  270. if b {
  271. e.w.writeb(jsonLiterals[jsonLitTrue : jsonLitTrue+4])
  272. } else {
  273. e.w.writeb(jsonLiterals[jsonLitFalse : jsonLitFalse+5])
  274. }
  275. }
  276. }
  277. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  278. // e.encodeFloat(float64(f), 32)
  279. e.EncodeFloat64(float64(f))
  280. }
  281. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  282. var blen int
  283. // instead of using 'g', specify whether to use 'e' or 'f'
  284. var abs = math.Abs(f)
  285. var fmt byte
  286. var prec int = -1
  287. if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
  288. fmt = 'e'
  289. } else {
  290. fmt = 'f'
  291. // set prec to 1 iff mod is 0.
  292. // better than using jsonIsFloatBytesB2 to check if a . or E in the float bytes.
  293. // this ensures that every float has an e or .0 in it.
  294. if abs <= 1 {
  295. if abs == 0 || abs == 1 {
  296. prec = 1
  297. }
  298. } else if _, mod := math.Modf(abs); mod == 0 {
  299. prec = 1
  300. }
  301. }
  302. if e.h.MapKeyAsString && e.c == containerMapKey {
  303. blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, prec, 64))
  304. e.b[0] = '"'
  305. e.b[blen-1] = '"'
  306. } else {
  307. blen = len(strconv.AppendFloat(e.b[:0], f, fmt, prec, 64))
  308. }
  309. e.w.writeb(e.b[:blen])
  310. }
  311. // func (e *jsonEncDriver) EncodeFloat64(f float64) {
  312. // e.encodeFloat(f, 64)
  313. // }
  314. // func (e *jsonEncDriver) encodeFloat(f float64, bits int) {
  315. // var blen int
  316. // // instead of using 'g', specify whether to use 'e' or 'f'
  317. // var abs = math.Abs(f)
  318. // var fmt byte
  319. // var prec int = -1
  320. // if abs != 0 && (bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21)) {
  321. // fmt = 'e'
  322. // } else {
  323. // fmt = 'f'
  324. // // set prec to 1 iff mod is 0.
  325. // // better than using jsonIsFloatBytesB2 to check if a . or E in the float bytes.
  326. // // this ensures that every float has an e or .0 in it.
  327. // if abs <= 1 {
  328. // if abs == 0 || abs == 1 {
  329. // prec = 1
  330. // }
  331. // } else if _, mod := math.Modf(abs); mod == 0 {
  332. // prec = 1
  333. // }
  334. // }
  335. // if e.h.MapKeyAsString && e.c == containerMapKey {
  336. // blen = 2 + len(strconv.AppendFloat(e.b[1:1], f, fmt, prec, bits))
  337. // e.b[0] = '"'
  338. // e.b[blen-1] = '"'
  339. // } else {
  340. // blen = len(strconv.AppendFloat(e.b[:0], f, fmt, prec, bits))
  341. // }
  342. // e.w.writeb(e.b[:blen])
  343. // }
  344. func (e *jsonEncDriver) EncodeInt(v int64) {
  345. x := e.h.IntegerAsString
  346. if x == 'A' || x == 'L' && (v > 1<<53 || v < -(1<<53)) || (e.h.MapKeyAsString && e.c == containerMapKey) {
  347. blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
  348. e.b[0] = '"'
  349. e.b[blen-1] = '"'
  350. e.w.writeb(e.b[:blen])
  351. return
  352. }
  353. e.w.writeb(strconv.AppendInt(e.b[:0], v, 10))
  354. }
  355. func (e *jsonEncDriver) EncodeUint(v uint64) {
  356. x := e.h.IntegerAsString
  357. if x == 'A' || x == 'L' && v > 1<<53 || (e.h.MapKeyAsString && e.c == containerMapKey) {
  358. blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
  359. e.b[0] = '"'
  360. e.b[blen-1] = '"'
  361. e.w.writeb(e.b[:blen])
  362. return
  363. }
  364. e.w.writeb(strconv.AppendUint(e.b[:0], v, 10))
  365. }
  366. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, en *Encoder) {
  367. if v := ext.ConvertExt(rv); v == nil {
  368. e.EncodeNil()
  369. } else {
  370. en.encode(v)
  371. }
  372. }
  373. func (e *jsonEncDriver) EncodeRawExt(re *RawExt, en *Encoder) {
  374. // only encodes re.Value (never re.Data)
  375. if re.Value == nil {
  376. e.EncodeNil()
  377. } else {
  378. en.encode(re.Value)
  379. }
  380. }
  381. func (e *jsonEncDriver) EncodeString(c charEncoding, v string) {
  382. e.quoteStr(v)
  383. }
  384. func (e *jsonEncDriver) EncodeSymbol(v string) {
  385. e.quoteStr(v)
  386. }
  387. func (e *jsonEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  388. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  389. if v == nil {
  390. e.EncodeNil()
  391. return
  392. }
  393. if c == cRAW {
  394. if e.se.i != nil {
  395. e.EncodeExt(v, 0, &e.se, e.e)
  396. return
  397. }
  398. slen := base64.StdEncoding.EncodedLen(len(v))
  399. if cap(e.bs) >= slen {
  400. e.bs = e.bs[:slen]
  401. } else {
  402. e.bs = make([]byte, slen)
  403. }
  404. base64.StdEncoding.Encode(e.bs, v)
  405. e.w.writen1('"')
  406. e.w.writeb(e.bs)
  407. e.w.writen1('"')
  408. } else {
  409. e.quoteStr(stringView(v))
  410. }
  411. }
  412. func (e *jsonEncDriver) EncodeAsis(v []byte) {
  413. e.w.writeb(v)
  414. }
  415. func (e *jsonEncDriver) quoteStr(s string) {
  416. // adapted from std pkg encoding/json
  417. const hex = "0123456789abcdef"
  418. w := e.w
  419. w.writen1('"')
  420. var start int
  421. for i, slen := 0, len(s); i < slen; {
  422. // encode all bytes < 0x20 (except \r, \n).
  423. // also encode < > & to prevent security holes when served to some browsers.
  424. if b := s[i]; b < utf8.RuneSelf {
  425. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  426. if jsonCharHtmlSafeSet.isset(b) || (e.h.HTMLCharsAsIs && jsonCharSafeSet.isset(b)) {
  427. i++
  428. continue
  429. }
  430. if start < i {
  431. w.writestr(s[start:i])
  432. }
  433. switch b {
  434. case '\\', '"':
  435. w.writen2('\\', b)
  436. case '\n':
  437. w.writen2('\\', 'n')
  438. case '\r':
  439. w.writen2('\\', 'r')
  440. case '\b':
  441. w.writen2('\\', 'b')
  442. case '\f':
  443. w.writen2('\\', 'f')
  444. case '\t':
  445. w.writen2('\\', 't')
  446. default:
  447. w.writestr(`\u00`)
  448. w.writen2(hex[b>>4], hex[b&0xF])
  449. }
  450. i++
  451. start = i
  452. continue
  453. }
  454. c, size := utf8.DecodeRuneInString(s[i:])
  455. if c == utf8.RuneError && size == 1 {
  456. if start < i {
  457. w.writestr(s[start:i])
  458. }
  459. w.writestr(`\ufffd`)
  460. i += size
  461. start = i
  462. continue
  463. }
  464. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  465. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  466. if c == '\u2028' || c == '\u2029' {
  467. if start < i {
  468. w.writestr(s[start:i])
  469. }
  470. w.writestr(`\u202`)
  471. w.writen1(hex[c&0xF])
  472. i += size
  473. start = i
  474. continue
  475. }
  476. i += size
  477. }
  478. if start < len(s) {
  479. w.writestr(s[start:])
  480. }
  481. w.writen1('"')
  482. }
  483. func (e *jsonEncDriver) atEndOfEncode() {
  484. if e.h.TermWhitespace {
  485. if e.d {
  486. e.w.writen1('\n')
  487. } else {
  488. e.w.writen1(' ')
  489. }
  490. }
  491. }
  492. type jsonDecDriver struct {
  493. noBuiltInTypes
  494. d *Decoder
  495. h *JsonHandle
  496. r decReader // *decReaderSwitch // decReader
  497. se setExtWrapper
  498. // ---- writable fields during execution --- *try* to keep in sep cache line
  499. c containerState
  500. // tok is used to store the token read right after skipWhiteSpace.
  501. tok uint8
  502. fnull bool // found null from appendStringAsBytes
  503. bs []byte // scratch. Initialized from b. Used for parsing strings or numbers.
  504. bstr [8]byte // scratch used for string \UXXX parsing
  505. // ---- cpu cache line boundary?
  506. b [64]byte // scratch 1, used for parsing strings or numbers or time.Time
  507. b2 [64]byte // scratch 2, used only for readUntil, decNumBytes
  508. // n jsonNum
  509. }
  510. // func jsonIsWS(b byte) bool {
  511. // // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  512. // return jsonCharWhitespaceSet.isset(b)
  513. // }
  514. func (d *jsonDecDriver) uncacheRead() {
  515. if d.tok != 0 {
  516. d.r.unreadn1()
  517. d.tok = 0
  518. }
  519. }
  520. func (d *jsonDecDriver) ReadMapStart() int {
  521. if d.tok == 0 {
  522. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  523. }
  524. const xc uint8 = '{'
  525. if d.tok != xc {
  526. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  527. }
  528. d.tok = 0
  529. d.c = containerMapStart
  530. return -1
  531. }
  532. func (d *jsonDecDriver) ReadArrayStart() int {
  533. if d.tok == 0 {
  534. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  535. }
  536. const xc uint8 = '['
  537. if d.tok != xc {
  538. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  539. }
  540. d.tok = 0
  541. d.c = containerArrayStart
  542. return -1
  543. }
  544. func (d *jsonDecDriver) CheckBreak() bool {
  545. if d.tok == 0 {
  546. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  547. }
  548. return d.tok == '}' || d.tok == ']'
  549. }
  550. func (d *jsonDecDriver) ReadArrayElem() {
  551. if d.tok == 0 {
  552. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  553. }
  554. if d.c != containerArrayStart {
  555. const xc uint8 = ','
  556. if d.tok != xc {
  557. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  558. }
  559. d.tok = 0
  560. }
  561. d.c = containerArrayElem
  562. }
  563. func (d *jsonDecDriver) ReadArrayEnd() {
  564. if d.tok == 0 {
  565. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  566. }
  567. const xc uint8 = ']'
  568. if d.tok != xc {
  569. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  570. }
  571. d.tok = 0
  572. d.c = containerArrayEnd
  573. }
  574. func (d *jsonDecDriver) ReadMapElemKey() {
  575. if d.tok == 0 {
  576. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  577. }
  578. if d.c != containerMapStart {
  579. const xc uint8 = ','
  580. if d.tok != xc {
  581. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  582. }
  583. d.tok = 0
  584. }
  585. d.c = containerMapKey
  586. }
  587. func (d *jsonDecDriver) ReadMapElemValue() {
  588. if d.tok == 0 {
  589. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  590. }
  591. const xc uint8 = ':'
  592. if d.tok != xc {
  593. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  594. }
  595. d.tok = 0
  596. d.c = containerMapValue
  597. }
  598. func (d *jsonDecDriver) ReadMapEnd() {
  599. if d.tok == 0 {
  600. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  601. }
  602. const xc uint8 = '}'
  603. if d.tok != xc {
  604. d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  605. }
  606. d.tok = 0
  607. d.c = containerMapEnd
  608. }
  609. // func (d *jsonDecDriver) readContainerState(c containerState, xc uint8, check bool) {
  610. // if d.tok == 0 {
  611. // d.tok = d.r.skip(&jsonCharWhitespaceSet)
  612. // }
  613. // if check {
  614. // if d.tok != xc {
  615. // d.d.errorf("json: expect char '%c' but got char '%c'", xc, d.tok)
  616. // }
  617. // d.tok = 0
  618. // }
  619. // d.c = c
  620. // }
  621. func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
  622. bs := d.r.readx(int(length))
  623. d.tok = 0
  624. if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  625. d.d.errorf("json: expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  626. return
  627. }
  628. }
  629. func (d *jsonDecDriver) TryDecodeAsNil() bool {
  630. if d.tok == 0 {
  631. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  632. }
  633. // we shouldn't try to see if "null" was here, right?
  634. // only the plain string: `null` denotes a nil (ie not quotes)
  635. if d.tok == 'n' {
  636. d.readLit(3, jsonLitNull+1) // (n)ull
  637. return true
  638. }
  639. return false
  640. }
  641. func (d *jsonDecDriver) DecodeBool() (v bool) {
  642. if d.tok == 0 {
  643. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  644. }
  645. fquot := d.c == containerMapKey && d.tok == '"'
  646. if fquot {
  647. d.tok = d.r.readn1()
  648. }
  649. switch d.tok {
  650. case 'f':
  651. d.readLit(4, jsonLitFalse+1) // (f)alse
  652. // v = false
  653. case 't':
  654. d.readLit(3, jsonLitTrue+1) // (t)rue
  655. v = true
  656. default:
  657. d.d.errorf("json: decode bool: got first char %c", d.tok)
  658. // v = false // "unreachable"
  659. }
  660. if fquot {
  661. d.r.readn1()
  662. }
  663. return
  664. }
  665. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  666. // read string, and pass the string into json.unmarshal
  667. d.appendStringAsBytes()
  668. if d.fnull {
  669. return
  670. }
  671. t, err := time.Parse(time.RFC3339, stringView(d.bs))
  672. if err != nil {
  673. d.d.errorv(err)
  674. }
  675. return
  676. }
  677. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  678. // check container type by checking the first char
  679. if d.tok == 0 {
  680. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  681. }
  682. if b := d.tok; b == '{' {
  683. return valueTypeMap
  684. } else if b == '[' {
  685. return valueTypeArray
  686. } else if b == 'n' {
  687. return valueTypeNil
  688. } else if b == '"' {
  689. return valueTypeString
  690. }
  691. return valueTypeUnset
  692. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  693. // return false // "unreachable"
  694. }
  695. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  696. // stores num bytes in d.bs
  697. if d.tok == 0 {
  698. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  699. }
  700. if d.tok == '"' {
  701. bs = d.r.readUntil(d.b2[:0], '"')
  702. bs = bs[:len(bs)-1]
  703. } else {
  704. d.r.unreadn1()
  705. bs = d.r.readTo(d.bs[:0], &jsonNumSet)
  706. }
  707. d.tok = 0
  708. return bs
  709. }
  710. func (d *jsonDecDriver) DecodeUint(bitsize uint8) (u uint64) {
  711. bs := d.decNumBytes()
  712. u, err := strconv.ParseUint(stringView(bs), 10, int(bitsize))
  713. if err != nil {
  714. d.d.errorf("json: decode uint from %s: %v", bs, err)
  715. return
  716. }
  717. return
  718. }
  719. func (d *jsonDecDriver) DecodeInt(bitsize uint8) (i int64) {
  720. bs := d.decNumBytes()
  721. i, err := strconv.ParseInt(stringView(bs), 10, int(bitsize))
  722. if err != nil {
  723. d.d.errorv(err)
  724. }
  725. return
  726. }
  727. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  728. bs := d.decNumBytes()
  729. f, err := strconv.ParseFloat(stringView(bs), 64)
  730. if err != nil {
  731. d.d.errorv(err)
  732. }
  733. return
  734. }
  735. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  736. if ext == nil {
  737. re := rv.(*RawExt)
  738. re.Tag = xtag
  739. d.d.decode(&re.Value)
  740. } else {
  741. var v interface{}
  742. d.d.decode(&v)
  743. ext.UpdateExt(rv, v)
  744. }
  745. return
  746. }
  747. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  748. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  749. if d.se.i != nil {
  750. bsOut = bs
  751. d.DecodeExt(&bsOut, 0, &d.se)
  752. return
  753. }
  754. if d.tok == 0 {
  755. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  756. }
  757. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  758. if d.tok == '[' {
  759. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  760. return
  761. }
  762. d.appendStringAsBytes()
  763. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  764. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  765. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.bs.
  766. // However, it sets a fnull field to true, so we can check if a null was found.
  767. if len(d.bs) == 0 {
  768. if d.fnull {
  769. return nil
  770. }
  771. return []byte{}
  772. }
  773. bs0 := d.bs
  774. slen := base64.StdEncoding.DecodedLen(len(bs0))
  775. if slen <= cap(bs) {
  776. bsOut = bs[:slen]
  777. } else if zerocopy && slen <= cap(d.b2) {
  778. bsOut = d.b2[:slen]
  779. } else {
  780. bsOut = make([]byte, slen)
  781. }
  782. slen2, err := base64.StdEncoding.Decode(bsOut, bs0)
  783. if err != nil {
  784. d.d.errorf("json: error decoding base64 binary '%s': %v", bs0, err)
  785. return nil
  786. }
  787. if slen != slen2 {
  788. bsOut = bsOut[:slen2]
  789. }
  790. return
  791. }
  792. func (d *jsonDecDriver) DecodeString() (s string) {
  793. d.appendStringAsBytes()
  794. return d.bsToString()
  795. }
  796. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  797. d.appendStringAsBytes()
  798. return d.bs
  799. }
  800. func (d *jsonDecDriver) appendStringAsBytes() {
  801. if d.tok == 0 {
  802. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  803. }
  804. d.fnull = false
  805. if d.tok != '"' {
  806. // d.d.errorf("json: expect char '%c' but got char '%c'", '"', d.tok)
  807. // handle non-string scalar: null, true, false or a number
  808. switch d.tok {
  809. case 'n':
  810. d.readLit(3, jsonLitNull+1) // (n)ull
  811. d.bs = d.bs[:0]
  812. d.fnull = true
  813. case 'f':
  814. d.readLit(4, jsonLitFalse+1) // (f)alse
  815. d.bs = d.bs[:5]
  816. copy(d.bs, "false")
  817. case 't':
  818. d.readLit(3, jsonLitTrue+1) // (t)rue
  819. d.bs = d.bs[:4]
  820. copy(d.bs, "true")
  821. default:
  822. // try to parse a valid number
  823. bs := d.decNumBytes()
  824. if len(bs) <= cap(d.bs) {
  825. d.bs = d.bs[:len(bs)]
  826. } else {
  827. d.bs = make([]byte, len(bs))
  828. }
  829. copy(d.bs, bs)
  830. }
  831. return
  832. }
  833. d.tok = 0
  834. r := d.r
  835. var cs = r.readUntil(d.b2[:0], '"')
  836. var cslen = len(cs)
  837. var c uint8
  838. v := d.bs[:0]
  839. // append on each byte seen can be expensive, so we just
  840. // keep track of where we last read a contiguous set of
  841. // non-special bytes (using cursor variable),
  842. // and when we see a special byte
  843. // e.g. end-of-slice, " or \,
  844. // we will append the full range into the v slice before proceeding
  845. for i, cursor := 0, 0; ; {
  846. if i == cslen {
  847. v = append(v, cs[cursor:]...)
  848. cs = r.readUntil(d.b2[:0], '"')
  849. cslen = len(cs)
  850. i, cursor = 0, 0
  851. }
  852. c = cs[i]
  853. if c == '"' {
  854. v = append(v, cs[cursor:i]...)
  855. break
  856. }
  857. if c != '\\' {
  858. i++
  859. continue
  860. }
  861. v = append(v, cs[cursor:i]...)
  862. i++
  863. c = cs[i]
  864. switch c {
  865. case '"', '\\', '/', '\'':
  866. v = append(v, c)
  867. case 'b':
  868. v = append(v, '\b')
  869. case 'f':
  870. v = append(v, '\f')
  871. case 'n':
  872. v = append(v, '\n')
  873. case 'r':
  874. v = append(v, '\r')
  875. case 't':
  876. v = append(v, '\t')
  877. case 'u':
  878. var r rune
  879. var rr uint32
  880. if len(cs) < i+4 { // may help reduce bounds-checking
  881. d.d.errorf(`json: need at least 4 more bytes for unicode sequence`)
  882. }
  883. // c = cs[i+4] // may help reduce bounds-checking
  884. for j := 1; j < 5; j++ {
  885. c = jsonU4Set[cs[i+j]]
  886. if c == jsonU4SetErrVal {
  887. // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  888. r = unicode.ReplacementChar
  889. i += 4
  890. goto encode_rune
  891. }
  892. rr = rr*16 + uint32(c)
  893. }
  894. r = rune(rr)
  895. i += 4
  896. if utf16.IsSurrogate(r) {
  897. if len(cs) >= i+6 && cs[i+2] == 'u' && cs[i+1] == '\\' {
  898. i += 2
  899. // c = cs[i+4] // may help reduce bounds-checking
  900. var rr1 uint32
  901. for j := 1; j < 5; j++ {
  902. c = jsonU4Set[cs[i+j]]
  903. if c == jsonU4SetErrVal {
  904. // d.d.errorf(`json: unquoteStr: invalid hex char in \u unicode sequence: %q`, c)
  905. r = unicode.ReplacementChar
  906. i += 4
  907. goto encode_rune
  908. }
  909. rr1 = rr1*16 + uint32(c)
  910. }
  911. r = utf16.DecodeRune(r, rune(rr1))
  912. i += 4
  913. } else {
  914. r = unicode.ReplacementChar
  915. goto encode_rune
  916. }
  917. }
  918. encode_rune:
  919. w2 := utf8.EncodeRune(d.bstr[:], r)
  920. v = append(v, d.bstr[:w2]...)
  921. default:
  922. d.d.errorf("json: unsupported escaped value: %c", c)
  923. }
  924. i++
  925. cursor = i
  926. }
  927. d.bs = v
  928. }
  929. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  930. if d.h.PreferFloat || jsonIsFloatBytesB3(bs) { // bytes.IndexByte(bs, '.') != -1 ||...
  931. // } else if d.h.PreferFloat || bytes.ContainsAny(bs, ".eE") {
  932. z.v = valueTypeFloat
  933. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  934. } else if d.h.SignedInteger || bs[0] == '-' {
  935. z.v = valueTypeInt
  936. z.i, err = strconv.ParseInt(stringView(bs), 10, 64)
  937. } else {
  938. z.v = valueTypeUint
  939. z.u, err = strconv.ParseUint(stringView(bs), 10, 64)
  940. }
  941. if err != nil && z.v != valueTypeFloat {
  942. if v, ok := err.(*strconv.NumError); ok && (v.Err == strconv.ErrRange || v.Err == strconv.ErrSyntax) {
  943. z.v = valueTypeFloat
  944. z.f, err = strconv.ParseFloat(stringView(bs), 64)
  945. }
  946. }
  947. return
  948. }
  949. func (d *jsonDecDriver) bsToString() string {
  950. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  951. if jsonAlwaysReturnInternString || d.c == containerMapKey {
  952. return d.d.string(d.bs)
  953. }
  954. return string(d.bs)
  955. }
  956. func (d *jsonDecDriver) DecodeNaked() {
  957. z := d.d.n
  958. // var decodeFurther bool
  959. if d.tok == 0 {
  960. d.tok = d.r.skip(&jsonCharWhitespaceSet)
  961. }
  962. switch d.tok {
  963. case 'n':
  964. d.readLit(3, jsonLitNull+1) // (n)ull
  965. z.v = valueTypeNil
  966. case 'f':
  967. d.readLit(4, jsonLitFalse+1) // (f)alse
  968. z.v = valueTypeBool
  969. z.b = false
  970. case 't':
  971. d.readLit(3, jsonLitTrue+1) // (t)rue
  972. z.v = valueTypeBool
  973. z.b = true
  974. case '{':
  975. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  976. case '[':
  977. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  978. case '"':
  979. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  980. d.appendStringAsBytes()
  981. if len(d.bs) > 0 && d.c == containerMapKey && d.h.MapKeyAsString {
  982. switch stringView(d.bs) {
  983. case "null":
  984. z.v = valueTypeNil
  985. case "true":
  986. z.v = valueTypeBool
  987. z.b = true
  988. case "false":
  989. z.v = valueTypeBool
  990. z.b = false
  991. default:
  992. // check if a number: float, int or uint
  993. if err := d.nakedNum(z, d.bs); err != nil {
  994. z.v = valueTypeString
  995. z.s = d.bsToString()
  996. }
  997. }
  998. } else {
  999. z.v = valueTypeString
  1000. z.s = d.bsToString()
  1001. }
  1002. default: // number
  1003. bs := d.decNumBytes()
  1004. if len(bs) == 0 {
  1005. d.d.errorf("json: decode number from empty string")
  1006. return
  1007. }
  1008. if err := d.nakedNum(z, bs); err != nil {
  1009. d.d.errorf("json: decode number from %s: %v", bs, err)
  1010. return
  1011. }
  1012. }
  1013. // if decodeFurther {
  1014. // d.s.sc.retryRead()
  1015. // }
  1016. return
  1017. }
  1018. //----------------------
  1019. // JsonHandle is a handle for JSON encoding format.
  1020. //
  1021. // Json is comprehensively supported:
  1022. // - decodes numbers into interface{} as int, uint or float64
  1023. // - configurable way to encode/decode []byte .
  1024. // by default, encodes and decodes []byte using base64 Std Encoding
  1025. // - UTF-8 support for encoding and decoding
  1026. //
  1027. // It has better performance than the json library in the standard library,
  1028. // by leveraging the performance improvements of the codec library and
  1029. // minimizing allocations.
  1030. //
  1031. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1032. // reading multiple values from a stream containing json and non-json content.
  1033. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1034. // all from the same stream in sequence.
  1035. //
  1036. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs
  1037. // are not treated as an error.
  1038. // Instead, they are replaced by the Unicode replacement character U+FFFD.
  1039. type JsonHandle struct {
  1040. textEncodingType
  1041. BasicHandle
  1042. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1043. // If not configured, raw bytes are encoded to/from base64 text.
  1044. RawBytesExt InterfaceExt
  1045. // Indent indicates how a value is encoded.
  1046. // - If positive, indent by that number of spaces.
  1047. // - If negative, indent by that number of tabs.
  1048. Indent int8
  1049. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1050. //
  1051. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1052. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1053. // This can be mitigated by configuring how to encode integers.
  1054. //
  1055. // IntegerAsString interpretes the following values:
  1056. // - if 'L', then encode integers > 2^53 as a json string.
  1057. // - if 'A', then encode all integers as a json string
  1058. // containing the exact integer representation as a decimal.
  1059. // - else encode all integers as a json number (default)
  1060. IntegerAsString uint8
  1061. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1062. //
  1063. // By default, we encode them as \uXXX
  1064. // to prevent security holes when served from some browsers.
  1065. HTMLCharsAsIs bool
  1066. // PreferFloat says that we will default to decoding a number as a float.
  1067. // If not set, we will examine the characters of the number and decode as an
  1068. // integer type if it doesn't have any of the characters [.eE].
  1069. PreferFloat bool
  1070. // TermWhitespace says that we add a whitespace character
  1071. // at the end of an encoding.
  1072. //
  1073. // The whitespace is important, especially if using numbers in a context
  1074. // where multiple items are written to a stream.
  1075. TermWhitespace bool
  1076. // MapKeyAsString says to encode all map keys as strings.
  1077. //
  1078. // Use this to enforce strict json output.
  1079. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1080. MapKeyAsString bool
  1081. }
  1082. // Name returns the name of the handle: json
  1083. func (h *JsonHandle) Name() string { return "json" }
  1084. func (h *JsonHandle) hasElemSeparators() bool { return true }
  1085. // SetInterfaceExt sets an extension
  1086. func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  1087. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  1088. }
  1089. func (h *JsonHandle) newEncDriver(e *Encoder) encDriver {
  1090. hd := jsonEncDriver{e: e, h: h}
  1091. hd.bs = hd.b[:0]
  1092. hd.reset()
  1093. return &hd
  1094. }
  1095. func (h *JsonHandle) newDecDriver(d *Decoder) decDriver {
  1096. // d := jsonDecDriver{r: r.(*bytesDecReader), h: h}
  1097. hd := jsonDecDriver{d: d, h: h}
  1098. hd.bs = hd.b[:0]
  1099. hd.reset()
  1100. return &hd
  1101. }
  1102. func (e *jsonEncDriver) reset() {
  1103. e.w = e.e.w // e.e.w // &e.e.encWriterSwitch
  1104. e.se.i = e.h.RawBytesExt
  1105. if e.bs != nil {
  1106. e.bs = e.bs[:0]
  1107. }
  1108. e.d, e.dt, e.dl, e.ds = false, false, 0, ""
  1109. e.c = 0
  1110. if e.h.Indent > 0 {
  1111. e.d = true
  1112. e.ds = jsonSpaces[:e.h.Indent]
  1113. } else if e.h.Indent < 0 {
  1114. e.d = true
  1115. e.dt = true
  1116. e.ds = jsonTabs[:-(e.h.Indent)]
  1117. }
  1118. }
  1119. func (d *jsonDecDriver) reset() {
  1120. d.r = d.d.r // &d.d.decReaderSwitch // d.d.r
  1121. d.se.i = d.h.RawBytesExt
  1122. if d.bs != nil {
  1123. d.bs = d.bs[:0]
  1124. }
  1125. d.c, d.tok = 0, 0
  1126. // d.n.reset()
  1127. }
  1128. // func jsonIsFloatBytes(bs []byte) bool {
  1129. // for _, v := range bs {
  1130. // // if v == '.' || v == 'e' || v == 'E' {
  1131. // if jsonIsFloatSet.isset(v) {
  1132. // return true
  1133. // }
  1134. // }
  1135. // return false
  1136. // }
  1137. // func jsonIsFloatBytesB2(bs []byte) bool {
  1138. // return bytes.IndexByte(bs, '.') != -1 ||
  1139. // bytes.IndexByte(bs, 'E') != -1
  1140. // }
  1141. func jsonIsFloatBytesB3(bs []byte) bool {
  1142. return bytes.IndexByte(bs, '.') != -1 ||
  1143. bytes.IndexByte(bs, 'E') != -1 ||
  1144. bytes.IndexByte(bs, 'e') != -1
  1145. }
  1146. var _ decDriver = (*jsonDecDriver)(nil)
  1147. var _ encDriver = (*jsonEncDriver)(nil)