json.go 35 KB

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