json.go 35 KB

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