json.go 40 KB

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