json.go 34 KB

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