json.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. // Copyright (c) 2012-2018 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. // Top-level methods of json(End|Dec)Driver (which are implementations of (en|de)cDriver
  19. // MUST not call one-another.
  20. import (
  21. "bytes"
  22. "encoding/base64"
  23. "math"
  24. "strconv"
  25. "time"
  26. "unicode"
  27. "unicode/utf16"
  28. "unicode/utf8"
  29. )
  30. //--------------------------------
  31. var jsonLiterals = [...]byte{
  32. '"', 't', 'r', 'u', 'e', '"',
  33. '"', 'f', 'a', 'l', 's', 'e', '"',
  34. '"', 'n', 'u', 'l', 'l', '"',
  35. }
  36. const (
  37. jsonLitTrueQ = 0
  38. jsonLitTrue = 1
  39. jsonLitFalseQ = 6
  40. jsonLitFalse = 7
  41. jsonLitNullQ = 13
  42. jsonLitNull = 14
  43. )
  44. var (
  45. // jsonLiteralTrueQ = jsonLiterals[jsonLitTrueQ : jsonLitTrueQ+6]
  46. // jsonLiteralFalseQ = jsonLiterals[jsonLitFalseQ : jsonLitFalseQ+7]
  47. // jsonLiteralNullQ = jsonLiterals[jsonLitNullQ : jsonLitNullQ+6]
  48. jsonLiteralTrue = jsonLiterals[jsonLitTrue : jsonLitTrue+4]
  49. jsonLiteralFalse = jsonLiterals[jsonLitFalse : jsonLitFalse+5]
  50. jsonLiteralNull = jsonLiterals[jsonLitNull : jsonLitNull+4]
  51. // these are used, after consuming the first char
  52. jsonLiteral4True = jsonLiterals[jsonLitTrue+1 : jsonLitTrue+4]
  53. jsonLiteral4False = jsonLiterals[jsonLitFalse+1 : jsonLitFalse+5]
  54. jsonLiteral4Null = jsonLiterals[jsonLitNull+1 : jsonLitNull+4]
  55. )
  56. const (
  57. jsonU4Chk2 = '0'
  58. jsonU4Chk1 = 'a' - 10
  59. jsonU4Chk0 = 'A' - 10
  60. // jsonScratchArrayLen = cacheLineSize + 32 // 96
  61. )
  62. const (
  63. // If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
  64. // - If we see first character of null, false or true,
  65. // do not validate subsequent characters.
  66. // - e.g. if we see a n, assume null and skip next 3 characters,
  67. // and do not validate they are ull.
  68. // P.S. Do not expect a significant decoding boost from this.
  69. jsonValidateSymbols = true
  70. jsonSpacesOrTabsLen = 128
  71. jsonAlwaysReturnInternString = false
  72. )
  73. var (
  74. // jsonTabs and jsonSpaces are used as caches for indents
  75. jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte
  76. jsonCharHtmlSafeSet bitset256
  77. jsonCharSafeSet bitset256
  78. jsonCharWhitespaceSet bitset256
  79. jsonNumSet bitset256
  80. )
  81. func init() {
  82. var i byte
  83. for i = 0; i < jsonSpacesOrTabsLen; i++ {
  84. jsonSpaces[i] = ' '
  85. jsonTabs[i] = '\t'
  86. }
  87. // populate the safe values as true: note: ASCII control characters are (0-31)
  88. // jsonCharSafeSet: all true except (0-31) " \
  89. // jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
  90. for i = 32; i < utf8.RuneSelf; i++ {
  91. switch i {
  92. case '"', '\\':
  93. case '<', '>', '&':
  94. jsonCharSafeSet.set(i) // = true
  95. default:
  96. jsonCharSafeSet.set(i)
  97. jsonCharHtmlSafeSet.set(i)
  98. }
  99. }
  100. for i = 0; i <= utf8.RuneSelf; i++ {
  101. switch i {
  102. case ' ', '\t', '\r', '\n':
  103. jsonCharWhitespaceSet.set(i)
  104. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-':
  105. jsonNumSet.set(i)
  106. }
  107. }
  108. }
  109. // ----------------
  110. type jsonEncDriver struct {
  111. noBuiltInTypes
  112. // w *encWr
  113. h *JsonHandle
  114. // bs []byte // for encoding strings
  115. se interfaceExtWrapper
  116. // ---- cpu cache line boundary?
  117. // ds string // indent string
  118. di int8 // indent per: if negative, use tabs
  119. d bool // indenting?
  120. // dt bool // indent using tabs
  121. dl uint16 // indent level
  122. ks bool // map key as string
  123. is byte // integer as string
  124. typical bool
  125. s *bitset256 // safe set for characters (taking h.HTMLAsIs into consideration)
  126. // scratch: encode time, numbers, etc. Note: leave 1 byte for containerState
  127. b [cacheLineSize + 24]byte // buffer for encoding numbers and time
  128. e Encoder
  129. }
  130. // Keep writeIndent, WriteArrayElem, WriteMapElemKey, WriteMapElemValue
  131. // in jsonEncDriver, so that *Encoder can directly call them
  132. func (e *jsonEncDriver) encoder() *Encoder { return &e.e }
  133. func (e *jsonEncDriver) writeIndent() {
  134. e.e.encWr.writen1('\n')
  135. x := int(e.di) * int(e.dl)
  136. if e.di < 0 {
  137. x = -x
  138. for x > jsonSpacesOrTabsLen {
  139. e.e.encWr.writeb(jsonTabs[:])
  140. x -= jsonSpacesOrTabsLen
  141. }
  142. e.e.encWr.writeb(jsonTabs[:x])
  143. } else {
  144. for x > jsonSpacesOrTabsLen {
  145. e.e.encWr.writeb(jsonSpaces[:])
  146. x -= jsonSpacesOrTabsLen
  147. }
  148. e.e.encWr.writeb(jsonSpaces[:x])
  149. }
  150. }
  151. func (e *jsonEncDriver) WriteArrayElem() {
  152. if e.e.c != containerArrayStart {
  153. e.e.encWr.writen1(',')
  154. }
  155. if e.d {
  156. e.writeIndent()
  157. }
  158. }
  159. func (e *jsonEncDriver) WriteMapElemKey() {
  160. if e.e.c != containerMapStart {
  161. e.e.encWr.writen1(',')
  162. }
  163. if e.d {
  164. e.writeIndent()
  165. }
  166. }
  167. func (e *jsonEncDriver) WriteMapElemValue() {
  168. if e.d {
  169. e.e.encWr.writen2(':', ' ')
  170. } else {
  171. e.e.encWr.writen1(':')
  172. }
  173. }
  174. func (e *jsonEncDriver) EncodeNil() {
  175. // We always encode nil as just null (never in quotes)
  176. // This allows us to easily decode if a nil in the json stream
  177. // ie if initial token is n.
  178. // e.e.encWr.writeb(jsonLiteralNull)
  179. e.e.encWr.writen([rwNLen]byte{'n', 'u', 'l', 'l'}, 4)
  180. // if e.h.MapKeyAsString && e.e.c == containerMapKey {
  181. // e.e.encWr.writeb(jsonLiterals[jsonLitNullQ : jsonLitNullQ+6])
  182. // } else {
  183. // e.e.encWr.writeb(jsonLiterals[jsonLitNull : jsonLitNull+4])
  184. // }
  185. }
  186. func (e *jsonEncDriver) EncodeTime(t time.Time) {
  187. // Do NOT use MarshalJSON, as it allocates internally.
  188. // instead, we call AppendFormat directly, using our scratch buffer (e.b)
  189. if t.IsZero() {
  190. e.EncodeNil()
  191. } else {
  192. e.b[0] = '"'
  193. // b := t.AppendFormat(e.b[1:1], time.RFC3339Nano)
  194. b := fmtTime(t, e.b[1:1])
  195. e.b[len(b)+1] = '"'
  196. e.e.encWr.writeb(e.b[:len(b)+2])
  197. }
  198. // v, err := t.MarshalJSON(); if err != nil { e.e.error(err) } e.e.encWr.writeb(v)
  199. }
  200. func (e *jsonEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext) {
  201. if ext == SelfExt {
  202. rv2 := baseRV(rv)
  203. e.e.encodeValue(rv2, e.h.fnNoExt(rv2.Type()))
  204. } else if v := ext.ConvertExt(rv); v == nil {
  205. e.EncodeNil()
  206. } else {
  207. e.e.encode(v)
  208. }
  209. }
  210. func (e *jsonEncDriver) EncodeRawExt(re *RawExt) {
  211. // only encodes re.Value (never re.Data)
  212. if re.Value == nil {
  213. e.EncodeNil()
  214. } else {
  215. e.e.encode(re.Value)
  216. }
  217. }
  218. func (e *jsonEncDriver) EncodeBool(b bool) {
  219. if e.ks && e.e.c == containerMapKey {
  220. if b {
  221. // e.e.encWr.writeb(jsonLiteralTrueQ)
  222. e.e.encWr.writen([rwNLen]byte{'"', 't', 'r', 'u', 'e', '"'}, 6)
  223. } else {
  224. // e.e.encWr.writeb(jsonLiteralFalseQ)
  225. e.e.encWr.writen([rwNLen]byte{'"', 'f', 'a', 'l', 's', 'e', '"'}, 7)
  226. }
  227. } else {
  228. if b {
  229. // e.e.encWr.writeb(jsonLiteralTrue)
  230. e.e.encWr.writen([rwNLen]byte{'t', 'r', 'u', 'e'}, 4)
  231. } else {
  232. // e.e.encWr.writeb(jsonLiteralFalse)
  233. e.e.encWr.writen([rwNLen]byte{'f', 'a', 'l', 's', 'e'}, 5)
  234. }
  235. }
  236. }
  237. func (e *jsonEncDriver) encodeFloat(f float64, bitsize, fmt byte, prec int8) {
  238. var blen uint
  239. if e.ks && e.e.c == containerMapKey {
  240. blen = 2 + uint(len(strconv.AppendFloat(e.b[1:1], f, fmt, int(prec), int(bitsize))))
  241. // _ = e.b[:blen]
  242. e.b[0] = '"'
  243. e.b[blen-1] = '"'
  244. e.e.encWr.writeb(e.b[:blen])
  245. } else {
  246. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), int(bitsize)))
  247. }
  248. }
  249. func (e *jsonEncDriver) EncodeFloat64(f float64) {
  250. fmt, prec := jsonFloatStrconvFmtPrec64(f)
  251. e.encodeFloat(f, 64, fmt, prec)
  252. }
  253. func (e *jsonEncDriver) EncodeFloat32(f float32) {
  254. fmt, prec := jsonFloatStrconvFmtPrec32(f)
  255. e.encodeFloat(float64(f), 32, fmt, prec)
  256. }
  257. func (e *jsonEncDriver) EncodeInt(v int64) {
  258. if e.is == 'A' || e.is == 'L' && (v > 1<<53 || v < -(1<<53)) ||
  259. (e.ks && e.e.c == containerMapKey) {
  260. blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
  261. e.b[0] = '"'
  262. e.b[blen-1] = '"'
  263. e.e.encWr.writeb(e.b[:blen])
  264. return
  265. }
  266. e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
  267. }
  268. func (e *jsonEncDriver) EncodeUint(v uint64) {
  269. if e.is == 'A' || e.is == 'L' && v > 1<<53 || (e.ks && e.e.c == containerMapKey) {
  270. blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
  271. e.b[0] = '"'
  272. e.b[blen-1] = '"'
  273. e.e.encWr.writeb(e.b[:blen])
  274. return
  275. }
  276. e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
  277. }
  278. // func (e *jsonEncDriver) EncodeFloat32(f float32) {
  279. // // e.encodeFloat(float64(f), 32)
  280. // // always encode all floats as IEEE 64-bit floating point.
  281. // // It also ensures that we can decode in full precision even if into a float32,
  282. // // as what is written is always to float64 precision.
  283. // e.EncodeFloat64(float64(f))
  284. // }
  285. func (e *jsonEncDriver) EncodeString(v string) {
  286. if e.h.StringToRaw {
  287. e.EncodeStringBytesRaw(bytesView(v))
  288. return
  289. }
  290. e.quoteStr(v)
  291. }
  292. func (e *jsonEncDriver) EncodeStringBytesRaw(v []byte) {
  293. // if encoding raw bytes and RawBytesExt is configured, use it to encode
  294. if v == nil {
  295. e.EncodeNil()
  296. return
  297. }
  298. if e.se.InterfaceExt != nil {
  299. e.EncodeExt(v, 0, &e.se)
  300. return
  301. }
  302. slen := base64.StdEncoding.EncodedLen(len(v)) + 2
  303. var bs []byte
  304. if len(e.b) < slen {
  305. bs = e.e.blist.get(slen)
  306. } else {
  307. bs = e.b[:slen]
  308. }
  309. // if cap(e.bs) >= slen {
  310. // e.bs = e.bs[:slen]
  311. // } else {
  312. // e.bs = make([]byte, slen)
  313. // }
  314. bs[0] = '"'
  315. base64.StdEncoding.Encode(bs[1:], v)
  316. bs[len(bs)-1] = '"'
  317. e.e.encWr.writeb(bs)
  318. if len(e.b) < slen {
  319. e.e.blist.put(bs)
  320. }
  321. }
  322. // func (e *jsonEncDriver) EncodeAsis(v []byte) {
  323. // e.e.encWr.writeb(v)
  324. // }
  325. // indent is done as below:
  326. // - newline and indent are added before each mapKey or arrayElem
  327. // - newline and indent are added before each ending,
  328. // except there was no entry (so we can have {} or [])
  329. func (e *jsonEncDriver) WriteArrayStart(length int) {
  330. if e.d {
  331. e.dl++
  332. }
  333. e.e.encWr.writen1('[')
  334. }
  335. func (e *jsonEncDriver) WriteArrayEnd() {
  336. if e.d {
  337. e.dl--
  338. e.writeIndent()
  339. }
  340. e.e.encWr.writen1(']')
  341. }
  342. func (e *jsonEncDriver) WriteMapStart(length int) {
  343. if e.d {
  344. e.dl++
  345. }
  346. e.e.encWr.writen1('{')
  347. }
  348. func (e *jsonEncDriver) WriteMapEnd() {
  349. if e.d {
  350. e.dl--
  351. if e.e.c != containerMapStart {
  352. e.writeIndent()
  353. }
  354. }
  355. e.e.encWr.writen1('}')
  356. }
  357. func (e *jsonEncDriver) quoteStr(s string) {
  358. // adapted from std pkg encoding/json
  359. const hex = "0123456789abcdef"
  360. w := e.e.w()
  361. w.writen1('"')
  362. var i, start uint
  363. for i < uint(len(s)) {
  364. // encode all bytes < 0x20 (except \r, \n).
  365. // also encode < > & to prevent security holes when served to some browsers.
  366. // We optimize for ascii, by assumining that most characters are in the BMP
  367. // and natively consumed by json without much computation.
  368. // if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
  369. // if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) {
  370. b := s[i]
  371. if e.s.isset(b) {
  372. i++
  373. continue
  374. }
  375. if b < utf8.RuneSelf {
  376. if start < i {
  377. w.writestr(s[start:i])
  378. }
  379. switch b {
  380. case '\\', '"':
  381. w.writen2('\\', b)
  382. case '\n':
  383. w.writen2('\\', 'n')
  384. case '\r':
  385. w.writen2('\\', 'r')
  386. case '\b':
  387. w.writen2('\\', 'b')
  388. case '\f':
  389. w.writen2('\\', 'f')
  390. case '\t':
  391. w.writen2('\\', 't')
  392. default:
  393. w.writestr(`\u00`)
  394. w.writen2(hex[b>>4], hex[b&0xF])
  395. }
  396. i++
  397. start = i
  398. continue
  399. }
  400. c, size := utf8.DecodeRuneInString(s[i:])
  401. if c == utf8.RuneError {
  402. if size == 1 {
  403. if start < i {
  404. w.writestr(s[start:i])
  405. }
  406. w.writestr(`\ufffd`)
  407. i++
  408. start = i
  409. }
  410. continue
  411. }
  412. // U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
  413. // Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
  414. if c == '\u2028' || c == '\u2029' {
  415. if start < i {
  416. w.writestr(s[start:i])
  417. }
  418. w.writestr(`\u202`)
  419. w.writen1(hex[c&0xF])
  420. i += uint(size)
  421. start = i
  422. continue
  423. }
  424. i += uint(size)
  425. }
  426. if start < uint(len(s)) {
  427. w.writestr(s[start:])
  428. }
  429. w.writen1('"')
  430. }
  431. func (e *jsonEncDriver) atEndOfEncode() {
  432. // if e.e.c == 0 { // scalar written, output space
  433. // e.e.encWr.writen1(' ')
  434. // } else if e.h.TermWhitespace { // container written, output new-line
  435. // e.e.encWr.writen1('\n')
  436. // }
  437. if e.h.TermWhitespace {
  438. if e.e.c == 0 { // scalar written, output space
  439. e.e.encWr.writen1(' ')
  440. } else { // container written, output new-line
  441. e.e.encWr.writen1('\n')
  442. }
  443. }
  444. }
  445. // ----------------
  446. /*
  447. type jsonEncDriverTypical jsonEncDriver
  448. func (e *jsonEncDriverTypical) WriteArrayStart(length int) {
  449. e.e.encWr.writen1('[')
  450. }
  451. func (e *jsonEncDriverTypical) WriteArrayElem() {
  452. if e.e.c != containerArrayStart {
  453. e.e.encWr.writen1(',')
  454. }
  455. }
  456. func (e *jsonEncDriverTypical) WriteArrayEnd() {
  457. e.e.encWr.writen1(']')
  458. }
  459. func (e *jsonEncDriverTypical) WriteMapStart(length int) {
  460. e.e.encWr.writen1('{')
  461. }
  462. func (e *jsonEncDriverTypical) WriteMapElemKey() {
  463. if e.e.c != containerMapStart {
  464. e.e.encWr.writen1(',')
  465. }
  466. }
  467. func (e *jsonEncDriverTypical) WriteMapElemValue() {
  468. e.e.encWr.writen1(':')
  469. }
  470. func (e *jsonEncDriverTypical) WriteMapEnd() {
  471. e.e.encWr.writen1('}')
  472. }
  473. func (e *jsonEncDriverTypical) EncodeBool(b bool) {
  474. if b {
  475. // e.e.encWr.writeb(jsonLiteralTrue)
  476. e.e.encWr.writen([rwNLen]byte{'t', 'r', 'u', 'e'}, 4)
  477. } else {
  478. // e.e.encWr.writeb(jsonLiteralFalse)
  479. e.e.encWr.writen([rwNLen]byte{'f', 'a', 'l', 's', 'e'}, 5)
  480. }
  481. }
  482. func (e *jsonEncDriverTypical) EncodeInt(v int64) {
  483. e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
  484. }
  485. func (e *jsonEncDriverTypical) EncodeUint(v uint64) {
  486. e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
  487. }
  488. func (e *jsonEncDriverTypical) EncodeFloat64(f float64) {
  489. fmt, prec := jsonFloatStrconvFmtPrec64(f)
  490. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), 64))
  491. // e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, jsonFloatStrconvFmtPrec64(f), 64))
  492. }
  493. func (e *jsonEncDriverTypical) EncodeFloat32(f float32) {
  494. fmt, prec := jsonFloatStrconvFmtPrec32(f)
  495. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], float64(f), fmt, int(prec), 32))
  496. }
  497. // func (e *jsonEncDriverTypical) encodeFloat(f float64, bitsize uint8) {
  498. // fmt, prec := jsonFloatStrconvFmtPrec(f, bitsize == 32)
  499. // e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, prec, int(bitsize)))
  500. // }
  501. // func (e *jsonEncDriverTypical) atEndOfEncode() {
  502. // if e.tw {
  503. // e.e.encWr.writen1(' ')
  504. // }
  505. // }
  506. */
  507. // ----------
  508. type jsonDecDriver struct {
  509. noBuiltInTypes
  510. h *JsonHandle
  511. // r *decRd
  512. tok uint8 // used to store the token read right after skipWhiteSpace
  513. fnil bool // found null
  514. _ [2]byte // padding
  515. bstr [4]byte // scratch used for string \UXXX parsing
  516. // c containerState
  517. // ---- cpu cache line boundary (half - way)
  518. // b [jsonScratchArrayLen]byte // scratch 1, used for parsing strings or numbers or time.Time
  519. // ---- cpu cache line boundary?
  520. // ---- writable fields during execution --- *try* to keep in sep cache line
  521. // bs []byte // scratch - for parsing strings, bytes
  522. buf []byte
  523. se interfaceExtWrapper
  524. _ uint64 // padding
  525. // ---- cpu cache line boundary?
  526. // b2 [cacheLineSize + 32]byte // scratch 2, used only for readUntil, decNumBytes
  527. // n jsonNum
  528. // ---- cpu cache line boundary?
  529. d Decoder
  530. }
  531. // func jsonIsWS(b byte) bool {
  532. // // return b == ' ' || b == '\t' || b == '\r' || b == '\n'
  533. // return jsonCharWhitespaceSet.isset(b)
  534. // }
  535. func (d *jsonDecDriver) decoder() *Decoder {
  536. return &d.d
  537. }
  538. func (d *jsonDecDriver) uncacheRead() {
  539. if d.tok != 0 {
  540. d.d.decRd.unreadn1()
  541. d.tok = 0
  542. }
  543. }
  544. func (d *jsonDecDriver) ReadMapStart() int {
  545. d.advance()
  546. if d.tok == 'n' {
  547. d.readLit4Null()
  548. return decContainerLenNil
  549. }
  550. if d.tok != '{' {
  551. d.d.errorf("read map - expect char '%c' but got char '%c'", '{', d.tok)
  552. }
  553. d.tok = 0
  554. return decContainerLenUnknown
  555. }
  556. func (d *jsonDecDriver) ReadArrayStart() int {
  557. d.advance()
  558. if d.tok == 'n' {
  559. d.readLit4Null()
  560. return decContainerLenNil
  561. }
  562. if d.tok != '[' {
  563. d.d.errorf("read array - expect char '%c' but got char '%c'", '[', d.tok)
  564. }
  565. d.tok = 0
  566. return decContainerLenUnknown
  567. }
  568. func (d *jsonDecDriver) CheckBreak() bool {
  569. d.advance()
  570. return d.tok == '}' || d.tok == ']'
  571. }
  572. // For the ReadXXX methods below, we could just delegate to helper functions
  573. // readContainerState(c containerState, xc uint8, check bool)
  574. // - ReadArrayElem would become:
  575. // readContainerState(containerArrayElem, ',', d.d.c != containerArrayStart)
  576. //
  577. // However, until mid-stack inlining comes in go1.11 which supports inlining of
  578. // one-liners, we explicitly write them all 5 out to elide the extra func call.
  579. //
  580. // TODO: For Go 1.11, if inlined, consider consolidating these.
  581. func (d *jsonDecDriver) ReadArrayElem() {
  582. const xc uint8 = ','
  583. d.advance()
  584. if d.d.c != containerArrayStart {
  585. if d.tok != xc {
  586. d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok)
  587. }
  588. d.tok = 0
  589. }
  590. }
  591. func (d *jsonDecDriver) ReadArrayEnd() {
  592. const xc uint8 = ']'
  593. d.advance()
  594. if d.tok != xc {
  595. d.d.errorf("read array end - expect char '%c' but got char '%c'", xc, d.tok)
  596. }
  597. d.tok = 0
  598. }
  599. func (d *jsonDecDriver) ReadMapElemKey() {
  600. const xc uint8 = ','
  601. d.advance()
  602. if d.d.c != containerMapStart {
  603. if d.tok != xc {
  604. d.d.errorf("read map key - expect char '%c' but got char '%c'", xc, d.tok)
  605. }
  606. d.tok = 0
  607. }
  608. }
  609. func (d *jsonDecDriver) ReadMapElemValue() {
  610. const xc uint8 = ':'
  611. d.advance()
  612. if d.tok != xc {
  613. d.d.errorf("read map value - expect char '%c' but got char '%c'", xc, d.tok)
  614. }
  615. d.tok = 0
  616. }
  617. func (d *jsonDecDriver) ReadMapEnd() {
  618. const xc uint8 = '}'
  619. d.advance()
  620. if d.tok != xc {
  621. d.d.errorf("read map end - expect char '%c' but got char '%c'", xc, d.tok)
  622. }
  623. d.tok = 0
  624. }
  625. // func (d *jsonDecDriver) readLit(length, fromIdx uint8) {
  626. // // length here is always less than 8 (literals are: null, true, false)
  627. // bs := d.d.decRd.readx(int(length))
  628. // d.tok = 0
  629. // if jsonValidateSymbols && !bytes.Equal(bs, jsonLiterals[fromIdx:fromIdx+length]) {
  630. // d.d.errorf("expecting %s: got %s", jsonLiterals[fromIdx:fromIdx+length], bs)
  631. // }
  632. // }
  633. func (d *jsonDecDriver) readLit4True() {
  634. bs := d.d.decRd.readn(3)
  635. d.tok = 0
  636. if jsonValidateSymbols && bs != [rwNLen]byte{'r', 'u', 'e'} { // !Equal jsonLiteral4True
  637. d.d.errorf("expecting %s: got %s", jsonLiteral4True, bs)
  638. }
  639. }
  640. func (d *jsonDecDriver) readLit4False() {
  641. bs := d.d.decRd.readn(4)
  642. d.tok = 0
  643. if jsonValidateSymbols && bs != [rwNLen]byte{'a', 'l', 's', 'e'} { // !Equal jsonLiteral4False
  644. d.d.errorf("expecting %s: got %s", jsonLiteral4False, bs)
  645. }
  646. }
  647. func (d *jsonDecDriver) readLit4Null() {
  648. bs := d.d.decRd.readn(3) // readx(3)
  649. d.tok = 0
  650. if jsonValidateSymbols && bs != [rwNLen]byte{'u', 'l', 'l'} { // !Equal jsonLiteral4Null
  651. d.d.errorf("expecting %s: got %s", jsonLiteral4Null, bs)
  652. }
  653. d.fnil = true
  654. }
  655. func (d *jsonDecDriver) advance() {
  656. if d.tok == 0 {
  657. d.fnil = false
  658. d.tok = d.d.decRd.skip(&jsonCharWhitespaceSet)
  659. }
  660. }
  661. func (d *jsonDecDriver) TryNil() bool {
  662. d.advance()
  663. // we shouldn't try to see if quoted "null" was here, right?
  664. // only the plain string: `null` denotes a nil (ie not quotes)
  665. if d.tok == 'n' {
  666. d.readLit4Null()
  667. return true
  668. }
  669. return false
  670. }
  671. func (d *jsonDecDriver) Nil() bool {
  672. return d.fnil
  673. }
  674. func (d *jsonDecDriver) DecodeBool() (v bool) {
  675. d.advance()
  676. if d.tok == 'n' {
  677. d.readLit4Null()
  678. return
  679. }
  680. fquot := d.d.c == containerMapKey && d.tok == '"'
  681. if fquot {
  682. d.tok = d.d.decRd.readn1()
  683. }
  684. switch d.tok {
  685. case 'f':
  686. d.readLit4False()
  687. // v = false
  688. case 't':
  689. d.readLit4True()
  690. v = true
  691. default:
  692. d.d.errorf("decode bool: got first char %c", d.tok)
  693. // v = false // "unreachable"
  694. }
  695. if fquot {
  696. d.d.decRd.readn1()
  697. }
  698. return
  699. }
  700. func (d *jsonDecDriver) DecodeTime() (t time.Time) {
  701. // read string, and pass the string into json.unmarshal
  702. d.advance()
  703. if d.tok == 'n' {
  704. d.readLit4Null()
  705. return
  706. }
  707. bs := d.readString()
  708. t, err := time.Parse(time.RFC3339, stringView(bs))
  709. if err != nil {
  710. d.d.errorv(err)
  711. }
  712. return
  713. }
  714. func (d *jsonDecDriver) ContainerType() (vt valueType) {
  715. // check container type by checking the first char
  716. d.advance()
  717. // optimize this, so we don't do 4 checks but do one computation.
  718. // return jsonContainerSet[d.tok]
  719. // ContainerType is mostly called for Map and Array,
  720. // so this conditional is good enough (max 2 checks typically)
  721. if d.tok == '{' {
  722. return valueTypeMap
  723. } else if d.tok == '[' {
  724. return valueTypeArray
  725. } else if d.tok == 'n' {
  726. d.readLit4Null()
  727. return valueTypeNil
  728. } else if d.tok == '"' {
  729. return valueTypeString
  730. }
  731. return valueTypeUnset
  732. }
  733. func (d *jsonDecDriver) decNumBytes() (bs []byte) {
  734. d.advance()
  735. if d.tok == '"' {
  736. bs = d.d.decRd.readUntil('"', false)
  737. } else if d.tok == 'n' {
  738. d.readLit4Null()
  739. } else {
  740. d.d.decRd.unreadn1()
  741. bs = d.d.decRd.readTo(&jsonNumSet)
  742. }
  743. // xdebugf("decNumBytes: %s", bs)
  744. d.tok = 0
  745. return
  746. }
  747. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  748. bs := d.decNumBytes()
  749. if len(bs) == 0 {
  750. return
  751. }
  752. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  753. if overflow {
  754. d.d.errorf("overflow parsing unsigned integer: %s", bs)
  755. } else if neg {
  756. d.d.errorf("minus found parsing unsigned integer: %s", bs)
  757. } else if badsyntax {
  758. // fallback: try to decode as float, and cast
  759. n = d.decUint64ViaFloat(bs)
  760. }
  761. return n
  762. }
  763. func (d *jsonDecDriver) DecodeInt64() (i int64) {
  764. const cutoff = uint64(1 << uint(64-1))
  765. bs := d.decNumBytes()
  766. if len(bs) == 0 {
  767. return
  768. }
  769. n, neg, badsyntax, overflow := jsonParseInteger(bs)
  770. if overflow {
  771. d.d.errorf("overflow parsing integer: %s", bs)
  772. } else if badsyntax {
  773. // d.d.errorf("invalid syntax for integer: %s", bs)
  774. // fallback: try to decode as float, and cast
  775. if neg {
  776. n = d.decUint64ViaFloat(bs[1:])
  777. } else {
  778. n = d.decUint64ViaFloat(bs)
  779. }
  780. }
  781. if neg {
  782. if n > cutoff {
  783. d.d.errorf("overflow parsing integer: %s", bs)
  784. }
  785. i = -(int64(n))
  786. } else {
  787. if n >= cutoff {
  788. d.d.errorf("overflow parsing integer: %s", bs)
  789. }
  790. i = int64(n)
  791. }
  792. return
  793. }
  794. func (d *jsonDecDriver) decUint64ViaFloat(s []byte) (u uint64) {
  795. if len(s) == 0 {
  796. return
  797. }
  798. f, err := parseFloat64(s)
  799. if err != nil {
  800. d.d.errorf("invalid syntax for integer: %s", s)
  801. // d.d.errorv(err)
  802. }
  803. fi, ff := math.Modf(f)
  804. if ff > 0 {
  805. d.d.errorf("fractional part found parsing integer: %s", s)
  806. } else if fi > float64(math.MaxUint64) {
  807. d.d.errorf("overflow parsing integer: %s", s)
  808. }
  809. return uint64(fi)
  810. }
  811. // func (d *jsonDecDriver) decodeFloat(bitsize int) (f float64) {
  812. // bs := d.decNumBytes()
  813. // if len(bs) == 0 {
  814. // return
  815. // }
  816. // f, err := parseFloat(bs, bitsize)
  817. // if err != nil {
  818. // d.d.errorv(err)
  819. // }
  820. // return
  821. // }
  822. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  823. // return d.decodeFloat(64)
  824. var err error
  825. if bs := d.decNumBytes(); len(bs) > 0 {
  826. if f, err = parseFloat64(bs); err != nil {
  827. d.d.errorv(err)
  828. }
  829. }
  830. return
  831. }
  832. func (d *jsonDecDriver) DecodeFloat32() (f float32) {
  833. var err error
  834. if bs := d.decNumBytes(); len(bs) > 0 {
  835. if f, err = parseFloat32(bs); err != nil {
  836. d.d.errorv(err)
  837. }
  838. }
  839. return
  840. }
  841. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) {
  842. d.advance()
  843. if d.tok == 'n' {
  844. d.readLit4Null()
  845. return
  846. }
  847. if ext == nil {
  848. re := rv.(*RawExt)
  849. re.Tag = xtag
  850. d.d.decode(&re.Value)
  851. } else if ext == SelfExt {
  852. rv2 := baseRV(rv)
  853. d.d.decodeValue(rv2, d.h.fnNoExt(rv2.Type()))
  854. } else {
  855. d.d.interfaceExtConvertAndDecode(rv, ext)
  856. }
  857. }
  858. func (d *jsonDecDriver) decBytesFromArray(bs []byte) []byte {
  859. if bs == nil {
  860. bs = []byte{}
  861. } else {
  862. bs = bs[:0]
  863. }
  864. d.tok = 0
  865. bs = append(bs, uint8(d.DecodeUint64()))
  866. d.tok = d.d.decRd.skip(&jsonCharWhitespaceSet)
  867. for d.tok != ']' {
  868. if d.tok != ',' {
  869. d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
  870. }
  871. d.tok = 0
  872. bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
  873. d.tok = d.d.decRd.skip(&jsonCharWhitespaceSet)
  874. }
  875. d.tok = 0
  876. return bs
  877. }
  878. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  879. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  880. if d.se.InterfaceExt != nil {
  881. bsOut = bs
  882. d.DecodeExt(&bsOut, 0, &d.se)
  883. return
  884. }
  885. d.advance()
  886. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  887. if d.tok == '[' {
  888. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  889. if zerocopy && len(bs) == 0 {
  890. bs = d.d.b[:]
  891. }
  892. return d.decBytesFromArray(bs)
  893. }
  894. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  895. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  896. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.buf.
  897. // However, it sets a fnil field to true, so we can check if a null was found.
  898. // d.appendStringAsBytes()
  899. // if d.fnil {
  900. // return nil
  901. // }
  902. if d.tok == 'n' {
  903. d.readLit4Null()
  904. return nil
  905. }
  906. bs1 := d.readString()
  907. slen := base64.StdEncoding.DecodedLen(len(bs1))
  908. if slen == 0 {
  909. bsOut = []byte{}
  910. } else if slen <= cap(bs) {
  911. bsOut = bs[:slen]
  912. } else if zerocopy {
  913. // if d.buf == nil {
  914. // d.buf = d.bp.get(slen)
  915. // }
  916. d.buf = d.d.blist.check(d.buf, slen)
  917. bsOut = d.buf
  918. // if slen <= cap(d.buf) {
  919. // bsOut = d.buf[:slen]
  920. // } else {
  921. // d.bp.get(slen)
  922. // bsOut = d.buf
  923. // // bsOut = make([]byte, slen) // TODO: should i check pool? how to return it back?
  924. // }
  925. } else {
  926. bsOut = make([]byte, slen)
  927. }
  928. slen2, err := base64.StdEncoding.Decode(bsOut, bs1)
  929. if err != nil {
  930. d.d.errorf("error decoding base64 binary '%s': %v", bs1, err)
  931. return nil
  932. }
  933. if slen != slen2 {
  934. bsOut = bsOut[:slen2]
  935. }
  936. return
  937. }
  938. // func (d *jsonDecDriver) DecodeString() (s string) {
  939. // d.appendStringAsBytes()
  940. // return d.sliceToString()
  941. // }
  942. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  943. // defer func() { xdebug2f("DecodeStringAsBytes: %s", s) }()
  944. d.advance()
  945. if d.tok != '"' {
  946. // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
  947. // handle non-string scalar: null, true, false or a number
  948. switch d.tok {
  949. case 'n':
  950. d.readLit4Null()
  951. return []byte{}
  952. case 'f':
  953. d.readLit4False()
  954. return jsonLiteralFalse
  955. case 't':
  956. d.readLit4True()
  957. return jsonLiteralTrue
  958. }
  959. // try to parse a valid number
  960. return d.decNumBytes()
  961. }
  962. s = d.appendStringAsBytes()
  963. if d.fnil {
  964. return nil
  965. }
  966. return
  967. }
  968. func (d *jsonDecDriver) readString() (bs []byte) {
  969. if d.tok != '"' {
  970. d.d.errorf("expecting string starting with '\"'; got '%c'", d.tok)
  971. return
  972. }
  973. bs = d.d.decRd.readUntil('"', false)
  974. d.tok = 0
  975. return
  976. }
  977. func (d *jsonDecDriver) appendStringAsBytes() (bs []byte) {
  978. // xdebug2f("appendStringAsBytes: found: '%c'", d.tok)
  979. if d.buf != nil {
  980. d.buf = d.buf[:0]
  981. }
  982. d.tok = 0
  983. // append on each byte seen can be expensive, so we just
  984. // keep track of where we last read a contiguous set of
  985. // non-special bytes (using cursor variable),
  986. // and when we see a special byte
  987. // e.g. end-of-slice, " or \,
  988. // we will append the full range into the v slice before proceeding
  989. // xdebug2f("start")
  990. var cs = d.d.decRd.readUntil('"', true)
  991. // xdebugf("appendStringAsBytes: len: %d, cs: %s", len(cs), cs)
  992. // var cslen = uint(len(cs))
  993. var c uint8
  994. var i, cursor uint
  995. for {
  996. if i >= uint(len(cs)) {
  997. // d.bp.appends(cs[cursor:])
  998. // d.bp.ensureExtraCap(int(cslen - cursor))
  999. d.buf = append(d.buf, cs[cursor:]...)
  1000. cs = d.d.decRd.readUntil('"', true)
  1001. // xdebugf("appendStringAsBytes: len: %d, cs: %s", len(cs), cs)
  1002. // cslen = uint(len(cs))
  1003. i, cursor = 0, 0
  1004. continue // this continue helps elide the cs[i] below
  1005. }
  1006. c = cs[i]
  1007. if c == '"' {
  1008. // if len(d.buf) > 0 {
  1009. // // d.bp.appends(cs[cursor:i])
  1010. // // d.bp.ensureExtraCap(int(i - cursor))
  1011. // d.buf = append(d.buf, cs[cursor:i]...)
  1012. // }
  1013. break
  1014. }
  1015. if c != '\\' {
  1016. i++
  1017. continue
  1018. }
  1019. // d.bp.appends(cs[cursor:i])
  1020. // d.bp.ensureExtraCap(int(i - cursor))
  1021. d.buf = append(d.buf, cs[cursor:i]...)
  1022. // d.bp.ensureExtraCap(4) // NOTE: 1 is sufficient, but say 4 for now
  1023. i++
  1024. if i >= uint(len(cs)) {
  1025. d.d.errorf("need at least 1 more bytes for \\ escape sequence")
  1026. return // bounds-check elimination
  1027. }
  1028. c = cs[i]
  1029. switch c {
  1030. case '"', '\\', '/', '\'':
  1031. d.buf = append(d.buf, c)
  1032. case 'b':
  1033. d.buf = append(d.buf, '\b')
  1034. case 'f':
  1035. d.buf = append(d.buf, '\f')
  1036. case 'n':
  1037. d.buf = append(d.buf, '\n')
  1038. case 'r':
  1039. d.buf = append(d.buf, '\r')
  1040. case 't':
  1041. d.buf = append(d.buf, '\t')
  1042. case 'u':
  1043. i = d.appendStringAsBytesSlashU(cs, i)
  1044. default:
  1045. d.d.errorf("unsupported escaped value: %c", c)
  1046. }
  1047. i++
  1048. cursor = i
  1049. }
  1050. if len(cs) > 0 {
  1051. if len(d.buf) > 0 && cursor < uint(len(cs)) {
  1052. d.buf = append(d.buf, cs[cursor:i]...)
  1053. } else {
  1054. // if bytes, just return the cs got from readUntil.
  1055. // do not do it for io, especially bufio, as the buffer is needed for other things
  1056. cs = cs[:i]
  1057. if d.d.bytes {
  1058. return cs
  1059. }
  1060. // d.bp.ensureExtraCap(len(cs))
  1061. d.buf = d.d.blist.check(d.buf, len(cs))
  1062. copy(d.buf, cs)
  1063. }
  1064. }
  1065. return d.buf
  1066. // if len(d.buf) == 0 && len(cs) > 0 {
  1067. // // return cs[:len(cs)-1]
  1068. // // returning cs was failing for bufio, as it seems bufio needs the buffer for other things.
  1069. // // only return cs if bytesDecReader
  1070. // cs = cs[:len(cs)-1]
  1071. // if d.d.bytes {
  1072. // return cs
  1073. // }
  1074. // // d.bp.ensureExtraCap(len(cs))
  1075. // d.buf = d.d.blist.check(d.buf, len(cs))
  1076. // copy(d.buf, cs)
  1077. // // xdebugf("cs: '%s', d.buf: '%s'", cs, d.buf)
  1078. // return d.buf
  1079. // }
  1080. // // xdebug2f("returning d.buf: %s", d.buf)
  1081. // return d.buf
  1082. }
  1083. func (d *jsonDecDriver) appendStringAsBytesSlashU(cs []byte, i uint) uint {
  1084. var r rune
  1085. var rr uint32
  1086. var j uint
  1087. var c byte
  1088. if uint(len(cs)) < i+4 {
  1089. d.d.errorf("need at least 4 more bytes for unicode sequence")
  1090. return 0 // bounds-check elimination
  1091. }
  1092. for _, c = range cs[i+1 : i+5] { // bounds-check-elimination
  1093. // best to use explicit if-else
  1094. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  1095. if c >= '0' && c <= '9' {
  1096. rr = rr*16 + uint32(c-jsonU4Chk2)
  1097. } else if c >= 'a' && c <= 'f' {
  1098. rr = rr*16 + uint32(c-jsonU4Chk1)
  1099. } else if c >= 'A' && c <= 'F' {
  1100. rr = rr*16 + uint32(c-jsonU4Chk0)
  1101. } else {
  1102. r = unicode.ReplacementChar
  1103. i += 4
  1104. goto encode_rune
  1105. }
  1106. }
  1107. r = rune(rr)
  1108. i += 4
  1109. if utf16.IsSurrogate(r) {
  1110. if len(cs) >= int(i+6) {
  1111. var cx = cs[i+1:][:6:6] // [:6] affords bounds-check-elimination
  1112. //var cx [6]byte
  1113. //copy(cx[:], cs[i+1:])
  1114. if cx[0] == '\\' && cx[1] == 'u' {
  1115. i += 2
  1116. var rr1 uint32
  1117. for j = 2; j < 6; j++ {
  1118. c = cx[j]
  1119. if c >= '0' && c <= '9' {
  1120. rr = rr*16 + uint32(c-jsonU4Chk2)
  1121. } else if c >= 'a' && c <= 'f' {
  1122. rr = rr*16 + uint32(c-jsonU4Chk1)
  1123. } else if c >= 'A' && c <= 'F' {
  1124. rr = rr*16 + uint32(c-jsonU4Chk0)
  1125. } else {
  1126. r = unicode.ReplacementChar
  1127. i += 4
  1128. goto encode_rune
  1129. }
  1130. }
  1131. r = utf16.DecodeRune(r, rune(rr1))
  1132. i += 4
  1133. goto encode_rune
  1134. }
  1135. }
  1136. r = unicode.ReplacementChar
  1137. }
  1138. encode_rune:
  1139. w2 := utf8.EncodeRune(d.bstr[:], r)
  1140. d.buf = append(d.buf, d.bstr[:w2]...)
  1141. return i
  1142. }
  1143. func (d *jsonDecDriver) nakedNum(z *decNaked, bs []byte) (err error) {
  1144. const cutoff = uint64(1 << uint(64-1))
  1145. var n uint64
  1146. var neg, badsyntax, overflow bool
  1147. if len(bs) == 0 {
  1148. if d.h.PreferFloat {
  1149. z.v = valueTypeFloat
  1150. z.f = 0
  1151. } else if d.h.SignedInteger {
  1152. z.v = valueTypeInt
  1153. z.i = 0
  1154. } else {
  1155. z.v = valueTypeUint
  1156. z.u = 0
  1157. }
  1158. return
  1159. }
  1160. if d.h.PreferFloat {
  1161. goto F
  1162. }
  1163. n, neg, badsyntax, overflow = jsonParseInteger(bs)
  1164. if badsyntax || overflow {
  1165. goto F
  1166. }
  1167. if neg {
  1168. if n > cutoff {
  1169. goto F
  1170. }
  1171. z.v = valueTypeInt
  1172. z.i = -(int64(n))
  1173. } else if d.h.SignedInteger {
  1174. if n >= cutoff {
  1175. goto F
  1176. }
  1177. z.v = valueTypeInt
  1178. z.i = int64(n)
  1179. } else {
  1180. z.v = valueTypeUint
  1181. z.u = n
  1182. }
  1183. return
  1184. F:
  1185. z.v = valueTypeFloat
  1186. z.f, err = parseFloat64(bs)
  1187. return
  1188. }
  1189. func (d *jsonDecDriver) sliceToString(bs []byte) string {
  1190. // if x := d.s.sc; x != nil && x.so && x.st == '}' { // map key
  1191. if d.d.is != nil && (jsonAlwaysReturnInternString || d.d.c == containerMapKey) {
  1192. return d.d.string(bs)
  1193. }
  1194. return string(bs)
  1195. }
  1196. func (d *jsonDecDriver) DecodeNaked() {
  1197. z := d.d.naked()
  1198. // var decodeFurther bool
  1199. d.advance()
  1200. var bs []byte
  1201. switch d.tok {
  1202. case 'n':
  1203. d.readLit4Null()
  1204. z.v = valueTypeNil
  1205. case 'f':
  1206. d.readLit4False()
  1207. z.v = valueTypeBool
  1208. z.b = false
  1209. case 't':
  1210. d.readLit4True()
  1211. z.v = valueTypeBool
  1212. z.b = true
  1213. case '{':
  1214. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  1215. case '[':
  1216. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  1217. case '"':
  1218. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  1219. bs = d.appendStringAsBytes()
  1220. if len(bs) > 0 && d.d.c == containerMapKey && d.h.MapKeyAsString {
  1221. if bytes.Equal(bs, jsonLiteralNull) {
  1222. z.v = valueTypeNil
  1223. } else if bytes.Equal(bs, jsonLiteralTrue) {
  1224. z.v = valueTypeBool
  1225. z.b = true
  1226. } else if bytes.Equal(bs, jsonLiteralFalse) {
  1227. z.v = valueTypeBool
  1228. z.b = false
  1229. } else {
  1230. // check if a number: float, int or uint
  1231. if err := d.nakedNum(z, bs); err != nil {
  1232. z.v = valueTypeString
  1233. z.s = d.sliceToString(bs)
  1234. }
  1235. }
  1236. } else {
  1237. z.v = valueTypeString
  1238. z.s = d.sliceToString(bs)
  1239. }
  1240. default: // number
  1241. bs = d.decNumBytes()
  1242. if len(bs) == 0 {
  1243. d.d.errorf("decode number from empty string")
  1244. return
  1245. }
  1246. if err := d.nakedNum(z, bs); err != nil {
  1247. d.d.errorf("decode number from %s: %v", bs, err)
  1248. return
  1249. }
  1250. }
  1251. // if decodeFurther {
  1252. // d.s.sc.retryRead()
  1253. // }
  1254. }
  1255. //----------------------
  1256. // JsonHandle is a handle for JSON encoding format.
  1257. //
  1258. // Json is comprehensively supported:
  1259. // - decodes numbers into interface{} as int, uint or float64
  1260. // based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
  1261. // - decode integers from float formatted numbers e.g. 1.27e+8
  1262. // - decode any json value (numbers, bool, etc) from quoted strings
  1263. // - configurable way to encode/decode []byte .
  1264. // by default, encodes and decodes []byte using base64 Std Encoding
  1265. // - UTF-8 support for encoding and decoding
  1266. //
  1267. // It has better performance than the json library in the standard library,
  1268. // by leveraging the performance improvements of the codec library.
  1269. //
  1270. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1271. // reading multiple values from a stream containing json and non-json content.
  1272. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1273. // all from the same stream in sequence.
  1274. //
  1275. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are
  1276. // not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
  1277. type JsonHandle struct {
  1278. textEncodingType
  1279. BasicHandle
  1280. // Indent indicates how a value is encoded.
  1281. // - If positive, indent by that number of spaces.
  1282. // - If negative, indent by that number of tabs.
  1283. Indent int8
  1284. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1285. //
  1286. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1287. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1288. // This can be mitigated by configuring how to encode integers.
  1289. //
  1290. // IntegerAsString interpretes the following values:
  1291. // - if 'L', then encode integers > 2^53 as a json string.
  1292. // - if 'A', then encode all integers as a json string
  1293. // containing the exact integer representation as a decimal.
  1294. // - else encode all integers as a json number (default)
  1295. IntegerAsString byte
  1296. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1297. //
  1298. // By default, we encode them as \uXXX
  1299. // to prevent security holes when served from some browsers.
  1300. HTMLCharsAsIs bool
  1301. // PreferFloat says that we will default to decoding a number as a float.
  1302. // If not set, we will examine the characters of the number and decode as an
  1303. // integer type if it doesn't have any of the characters [.eE].
  1304. PreferFloat bool
  1305. // TermWhitespace says that we add a whitespace character
  1306. // at the end of an encoding.
  1307. //
  1308. // The whitespace is important, especially if using numbers in a context
  1309. // where multiple items are written to a stream.
  1310. TermWhitespace bool
  1311. // MapKeyAsString says to encode all map keys as strings.
  1312. //
  1313. // Use this to enforce strict json output.
  1314. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1315. MapKeyAsString bool
  1316. // _ uint64 // padding (cache line)
  1317. // Note: below, we store hardly-used items
  1318. // e.g. RawBytesExt (which is already cached in the (en|de)cDriver).
  1319. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1320. // If not configured, raw bytes are encoded to/from base64 text.
  1321. RawBytesExt InterfaceExt
  1322. _ [5]uint64 // padding (cache line)
  1323. }
  1324. // Name returns the name of the handle: json
  1325. func (h *JsonHandle) Name() string { return "json" }
  1326. // func (h *JsonHandle) hasElemSeparators() bool { return true }
  1327. func (h *JsonHandle) typical() bool {
  1328. return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L'
  1329. }
  1330. // func (h *JsonHandle) recreateEncDriver(ed encDriver) (v bool) {
  1331. // _, v = ed.(*jsonEncDriverTypical)
  1332. // return v != h.typical()
  1333. // }
  1334. // func (h *JsonHandle) newEncDriver(e *Encoder) (ee encDriver) {
  1335. // const allowTypical = true
  1336. // var hd *jsonEncDriver
  1337. // if allowTypical && h.typical() {
  1338. // var v jsonEncDriverTypical
  1339. // ee = &v
  1340. // hd = &v.jsonEncDriver
  1341. // } else {
  1342. // var v jsonEncDriverGeneric
  1343. // ee = &v
  1344. // hd = &v.jsonEncDriver
  1345. // }
  1346. // hd.e, hd.h = e, h
  1347. // ee.reset()
  1348. // return
  1349. // }
  1350. func (h *JsonHandle) newEncDriver() encDriver {
  1351. var e = &jsonEncDriver{h: h}
  1352. e.e.e = e
  1353. // e.e.jenc = e
  1354. e.e.js = true
  1355. e.e.init(h)
  1356. e.reset()
  1357. return e
  1358. }
  1359. func (h *JsonHandle) newDecDriver() decDriver {
  1360. var d = &jsonDecDriver{h: h}
  1361. d.d.d = d
  1362. // d.d.jdec = d
  1363. d.d.js = true
  1364. d.d.jsms = h.MapKeyAsString
  1365. d.d.init(h)
  1366. d.reset()
  1367. return d
  1368. }
  1369. func (e *jsonEncDriver) reset() {
  1370. // e.w = e.e.w()
  1371. // (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b)
  1372. e.typical = e.h.typical()
  1373. if e.h.HTMLCharsAsIs {
  1374. e.s = &jsonCharSafeSet
  1375. } else {
  1376. e.s = &jsonCharHtmlSafeSet
  1377. }
  1378. e.se.InterfaceExt = e.h.RawBytesExt
  1379. // if e.bs == nil {
  1380. // e.bs = e.b[:0]
  1381. // } else {
  1382. // e.bs = e.bs[:0]
  1383. // }
  1384. e.d, e.dl, e.di = false, 0, 0
  1385. if e.h.Indent != 0 {
  1386. e.d = true
  1387. e.di = int8(e.h.Indent)
  1388. }
  1389. // if e.h.Indent > 0 {
  1390. // e.d = true
  1391. // e.di = int8(e.h.Indent)
  1392. // } else if e.h.Indent < 0 {
  1393. // e.d = true
  1394. // // e.dt = true
  1395. // e.di = int8(-e.h.Indent)
  1396. // }
  1397. e.ks = e.h.MapKeyAsString
  1398. e.is = e.h.IntegerAsString
  1399. }
  1400. func (d *jsonDecDriver) reset() {
  1401. // d.r = d.d.r()
  1402. d.se.InterfaceExt = d.h.RawBytesExt
  1403. d.buf = d.d.blist.check(d.buf, 256)[:0]
  1404. // if d.buf != nil {
  1405. // d.buf = d.buf[:0]
  1406. // }
  1407. d.tok = 0
  1408. d.fnil = false
  1409. }
  1410. func (d *jsonDecDriver) atEndOfDecode() {}
  1411. // func (d *jsonDecDriver) release() {
  1412. // l := d.bp.capacity()
  1413. // if l > 0 {
  1414. // d.bp.end()
  1415. // }
  1416. // }
  1417. // jsonFloatStrconvFmtPrec ...
  1418. //
  1419. // ensure that every float has an 'e' or '.' in it,/ for easy differentiation from integers.
  1420. // this is better/faster than checking if encoded value has [e.] and appending if needed.
  1421. // func jsonFloatStrconvFmtPrec(f float64, bits32 bool) (fmt byte, prec int) {
  1422. // fmt = 'f'
  1423. // prec = -1
  1424. // var abs = math.Abs(f)
  1425. // if abs == 0 || abs == 1 {
  1426. // prec = 1
  1427. // } else if !bits32 && (abs < 1e-6 || abs >= 1e21) ||
  1428. // bits32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
  1429. // fmt = 'e'
  1430. // } else if _, frac := math.Modf(abs); frac == 0 {
  1431. // // ensure that floats have a .0 at the end, for easy identification as floats
  1432. // prec = 1
  1433. // }
  1434. // return
  1435. // }
  1436. func jsonFloatStrconvFmtPrec64(f float64) (fmt byte, prec int8) {
  1437. fmt = 'f'
  1438. prec = -1
  1439. var abs = math.Abs(f)
  1440. if abs == 0 || abs == 1 {
  1441. prec = 1
  1442. } else if abs < 1e-6 || abs >= 1e21 {
  1443. fmt = 'e'
  1444. } else if noFrac64(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1445. prec = 1
  1446. }
  1447. return
  1448. }
  1449. func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) {
  1450. fmt = 'f'
  1451. prec = -1
  1452. var abs = abs32(f)
  1453. if abs == 0 || abs == 1 {
  1454. prec = 1
  1455. } else if abs < 1e-6 || abs >= 1e21 {
  1456. fmt = 'e'
  1457. } else if noFrac32(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1458. prec = 1
  1459. }
  1460. return
  1461. }
  1462. // custom-fitted version of strconv.Parse(Ui|I)nt.
  1463. // Also ensures we don't have to search for .eE to determine if a float or not.
  1464. // Note: s CANNOT be a zero-length slice.
  1465. func jsonParseInteger(s []byte) (n uint64, neg, badSyntax, overflow bool) {
  1466. const maxUint64 = (1<<64 - 1)
  1467. const cutoff = maxUint64/10 + 1
  1468. if len(s) == 0 { // bounds-check-elimination
  1469. // treat empty string as zero value
  1470. // badSyntax = true
  1471. return
  1472. }
  1473. switch s[0] {
  1474. case '+':
  1475. s = s[1:]
  1476. case '-':
  1477. s = s[1:]
  1478. neg = true
  1479. }
  1480. for _, c := range s {
  1481. if c < '0' || c > '9' {
  1482. badSyntax = true
  1483. return
  1484. }
  1485. // unsigned integers don't overflow well on multiplication, so check cutoff here
  1486. // e.g. (maxUint64-5)*10 doesn't overflow well ...
  1487. if n >= cutoff {
  1488. overflow = true
  1489. return
  1490. }
  1491. n *= 10
  1492. n1 := n + uint64(c-'0')
  1493. if n1 < n || n1 > maxUint64 {
  1494. overflow = true
  1495. return
  1496. }
  1497. n = n1
  1498. }
  1499. return
  1500. }
  1501. var _ decDriverContainerTracker = (*jsonDecDriver)(nil)
  1502. var _ encDriverContainerTracker = (*jsonEncDriver)(nil)
  1503. var _ decDriver = (*jsonDecDriver)(nil)
  1504. // var _ encDriver = (*jsonEncDriverGeneric)(nil)
  1505. // var _ encDriver = (*jsonEncDriverTypical)(nil)
  1506. // var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverTypical)(nil)
  1507. // var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriverGeneric)(nil)
  1508. // var _ (interface{ getJsonEncDriver() *jsonEncDriver }) = (*jsonEncDriver)(nil)
  1509. var _ encDriver = (*jsonEncDriver)(nil)