json.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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. bs = d.d.decRd.readNumberWithLastByte()
  612. }
  613. d.tok = 0
  614. return
  615. }
  616. func (d *jsonDecDriver) DecodeUint64() (u uint64) {
  617. bs := d.decNumBytes()
  618. if len(bs) == 0 {
  619. return
  620. }
  621. if bs[0] == '-' {
  622. d.d.errorf("negative number cannot be decoded as uint64")
  623. }
  624. var r readFloatResult
  625. u, r.ok = parseUint64_simple(bs)
  626. if r.ok {
  627. return
  628. }
  629. r = readFloat(bs, fi64u)
  630. if r.ok {
  631. u, r.bad = parseUint64_reader(r)
  632. if r.bad {
  633. d.d.errorv(strconvParseErr(bs, "ParseUint"))
  634. }
  635. return
  636. }
  637. d.d.errorv(strconvParseErr(bs, "ParseUint"))
  638. return
  639. }
  640. // func (d *jsonDecDriver) DecodeInt64() (i int64) {
  641. // bs := d.decNumBytes()
  642. // if len(bs) == 0 {
  643. // return
  644. // }
  645. // i, err := parseInt64(bs)
  646. // if err != nil {
  647. // d.d.errorv(err)
  648. // }
  649. // return
  650. // }
  651. func (d *jsonDecDriver) DecodeInt64() (v int64) {
  652. b := d.decNumBytes()
  653. if len(b) == 0 {
  654. return
  655. }
  656. var r readFloatResult
  657. var neg bool
  658. if b[0] == '-' {
  659. neg = true
  660. b = b[1:]
  661. }
  662. r.mantissa, r.ok = parseUint64_simple(b)
  663. // xdebugf("parseuint64_simple: %v, %v", f, ok)
  664. if r.ok {
  665. if chkOvf.Uint2Int(r.mantissa, neg) {
  666. d.d.errorf("overflow decoding number from %s", b)
  667. }
  668. if neg {
  669. v = -int64(r.mantissa)
  670. } else {
  671. v = int64(r.mantissa)
  672. }
  673. return
  674. }
  675. r = readFloat(b, fi64i)
  676. // xdebugf("readFloat ok: %v", r.ok)
  677. if r.ok {
  678. r.neg = neg
  679. v, r.bad = parseInt64_reader(r)
  680. if r.bad {
  681. d.d.errorv(strconvParseErr(b, "ParseInt"))
  682. }
  683. return
  684. }
  685. d.d.errorv(strconvParseErr(b, "ParseInt"))
  686. return
  687. }
  688. func (d *jsonDecDriver) DecodeFloat64() (f float64) {
  689. var err error
  690. bs := d.decNumBytes()
  691. if len(bs) == 0 {
  692. return
  693. }
  694. f, err = parseFloat64(bs)
  695. if err != nil {
  696. d.d.errorv(err)
  697. }
  698. return
  699. }
  700. func (d *jsonDecDriver) DecodeFloat32() (f float32) {
  701. var err error
  702. bs := d.decNumBytes()
  703. if len(bs) == 0 {
  704. return
  705. }
  706. f, err = parseFloat32(bs)
  707. if err != nil {
  708. d.d.errorv(err)
  709. }
  710. return
  711. }
  712. func (d *jsonDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) {
  713. d.advance()
  714. if d.tok == 'n' {
  715. d.readLit4Null()
  716. return
  717. }
  718. if ext == nil {
  719. re := rv.(*RawExt)
  720. re.Tag = xtag
  721. d.d.decode(&re.Value)
  722. } else if ext == SelfExt {
  723. rv2 := baseRV(rv)
  724. d.d.decodeValue(rv2, d.h.fnNoExt(rv2.Type()))
  725. } else {
  726. d.d.interfaceExtConvertAndDecode(rv, ext)
  727. }
  728. }
  729. func (d *jsonDecDriver) decBytesFromArray(bs []byte) []byte {
  730. if bs == nil {
  731. bs = []byte{}
  732. } else {
  733. bs = bs[:0]
  734. }
  735. d.tok = 0
  736. bs = append(bs, uint8(d.DecodeUint64()))
  737. d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
  738. for d.tok != ']' {
  739. if d.tok != ',' {
  740. d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
  741. }
  742. d.tok = 0
  743. bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
  744. d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
  745. }
  746. d.tok = 0
  747. return bs
  748. }
  749. func (d *jsonDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  750. // if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
  751. if d.se.InterfaceExt != nil {
  752. bsOut = bs
  753. d.DecodeExt(&bsOut, 0, &d.se)
  754. return
  755. }
  756. d.advance()
  757. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  758. if d.tok == '[' {
  759. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  760. if zerocopy && len(bs) == 0 {
  761. bs = d.d.b[:]
  762. }
  763. return d.decBytesFromArray(bs)
  764. }
  765. // base64 encodes []byte{} as "", and we encode nil []byte as null.
  766. // Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
  767. // appendStringAsBytes returns a zero-len slice for both, so as not to reset d.buf.
  768. // However, it sets a fnil field to true, so we can check if a null was found.
  769. if d.tok == 'n' {
  770. d.readLit4Null()
  771. return nil
  772. }
  773. bs1 := d.readUnescapedString()
  774. slen := base64.StdEncoding.DecodedLen(len(bs1))
  775. if slen == 0 {
  776. bsOut = []byte{}
  777. } else if slen <= cap(bs) {
  778. bsOut = bs[:slen]
  779. } else if zerocopy {
  780. d.buf = d.d.blist.check(d.buf, slen)
  781. bsOut = d.buf
  782. } else {
  783. bsOut = make([]byte, slen)
  784. }
  785. slen2, err := base64.StdEncoding.Decode(bsOut, bs1)
  786. if err != nil {
  787. d.d.errorf("error decoding base64 binary '%s': %v", bs1, err)
  788. return nil
  789. }
  790. if slen != slen2 {
  791. bsOut = bsOut[:slen2]
  792. }
  793. return
  794. }
  795. func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
  796. d.advance()
  797. // common case
  798. if d.tok == '"' {
  799. d.appendStringAsBytes()
  800. return d.buf
  801. }
  802. // d.d.errorf("expect char '%c' but got char '%c'", '"', d.tok)
  803. // handle non-string scalar: null, true, false or a number
  804. switch d.tok {
  805. case 'n':
  806. d.readLit4Null()
  807. return nil // []byte{}
  808. case 'f':
  809. d.readLit4False()
  810. return jsonLiteralFalse
  811. case 't':
  812. d.readLit4True()
  813. return jsonLiteralTrue
  814. }
  815. // try to parse a valid number
  816. d.tok = 0
  817. return d.d.decRd.readNumberWithLastByte()
  818. }
  819. func (d *jsonDecDriver) readUnescapedString() (bs []byte) {
  820. if d.tok != '"' {
  821. d.d.errorf("expecting string starting with '\"'; got '%c'", d.tok)
  822. return
  823. }
  824. bs = d.d.decRd.readUntil('"', false)
  825. d.tok = 0
  826. return
  827. }
  828. func (d *jsonDecDriver) appendStringAsBytes() {
  829. if d.buf != nil {
  830. d.buf = d.buf[:0]
  831. }
  832. d.tok = 0
  833. var c uint8
  834. for {
  835. c = d.d.decRd.readn1()
  836. if c == '"' {
  837. break
  838. }
  839. if c != '\\' {
  840. d.buf = append(d.buf, c)
  841. continue
  842. }
  843. c = d.d.decRd.readn1()
  844. switch c {
  845. case '"', '\\', '/', '\'':
  846. d.buf = append(d.buf, c)
  847. case 'b':
  848. d.buf = append(d.buf, '\b')
  849. case 'f':
  850. d.buf = append(d.buf, '\f')
  851. case 'n':
  852. d.buf = append(d.buf, '\n')
  853. case 'r':
  854. d.buf = append(d.buf, '\r')
  855. case 't':
  856. d.buf = append(d.buf, '\t')
  857. case 'u':
  858. d.appendStringAsBytesSlashU()
  859. default:
  860. d.d.errorf("unsupported escaped value: %c", c)
  861. }
  862. }
  863. }
  864. func (d *jsonDecDriver) appendStringAsBytesSlashU() {
  865. var r rune
  866. var rr uint32
  867. var j uint
  868. var c byte
  869. var cs [7]byte
  870. cs = d.d.decRd.readn(4)
  871. for _, c = range cs[:4] { // bounds-check-elimination
  872. // best to use explicit if-else
  873. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  874. if c >= '0' && c <= '9' {
  875. rr = rr*16 + uint32(c-jsonU4Chk2)
  876. } else if c >= 'a' && c <= 'f' {
  877. rr = rr*16 + uint32(c-jsonU4Chk1)
  878. } else if c >= 'A' && c <= 'F' {
  879. rr = rr*16 + uint32(c-jsonU4Chk0)
  880. } else {
  881. r = unicode.ReplacementChar
  882. goto encode_rune
  883. }
  884. }
  885. r = rune(rr)
  886. if utf16.IsSurrogate(r) {
  887. cs = d.d.decRd.readn(6)
  888. if cs[0] == '\\' && cs[1] == 'u' {
  889. var rr1 uint32
  890. for j = 2; j < 6; j++ {
  891. c = cs[j]
  892. if c >= '0' && c <= '9' {
  893. rr = rr*16 + uint32(c-jsonU4Chk2)
  894. } else if c >= 'a' && c <= 'f' {
  895. rr = rr*16 + uint32(c-jsonU4Chk1)
  896. } else if c >= 'A' && c <= 'F' {
  897. rr = rr*16 + uint32(c-jsonU4Chk0)
  898. } else {
  899. r = unicode.ReplacementChar
  900. goto encode_rune
  901. }
  902. }
  903. r = utf16.DecodeRune(r, rune(rr1))
  904. goto encode_rune
  905. }
  906. r = unicode.ReplacementChar
  907. }
  908. encode_rune:
  909. w2 := utf8.EncodeRune(d.bstr[:], r)
  910. d.buf = append(d.buf, d.bstr[:w2]...)
  911. }
  912. func (d *jsonDecDriver) nakedNum(z *fauxUnion, bs []byte) (err error) {
  913. // const cutoff = uint64(1 << uint(64-1))
  914. if len(bs) == 0 {
  915. if d.h.PreferFloat {
  916. z.v = valueTypeFloat
  917. z.f = 0
  918. } else if d.h.SignedInteger {
  919. z.v = valueTypeInt
  920. z.i = 0
  921. } else {
  922. z.v = valueTypeUint
  923. z.u = 0
  924. }
  925. return
  926. }
  927. if d.h.PreferFloat {
  928. z.v = valueTypeFloat
  929. z.f, err = parseFloat64(bs)
  930. } else {
  931. err = parseNumber(bs, z, d.h.SignedInteger)
  932. }
  933. return
  934. }
  935. func (d *jsonDecDriver) sliceToString(bs []byte) string {
  936. if d.d.is != nil && (jsonAlwaysReturnInternString || d.d.c == containerMapKey) {
  937. return d.d.string(bs)
  938. }
  939. return string(bs)
  940. }
  941. func (d *jsonDecDriver) DecodeNaked() {
  942. z := d.d.naked()
  943. d.advance()
  944. var bs []byte
  945. switch d.tok {
  946. case 'n':
  947. d.readLit4Null()
  948. z.v = valueTypeNil
  949. case 'f':
  950. d.readLit4False()
  951. z.v = valueTypeBool
  952. z.b = false
  953. case 't':
  954. d.readLit4True()
  955. z.v = valueTypeBool
  956. z.b = true
  957. case '{':
  958. z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
  959. case '[':
  960. z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
  961. case '"':
  962. // if a string, and MapKeyAsString, then try to decode it as a nil, bool or number first
  963. d.appendStringAsBytes()
  964. bs = d.buf
  965. if len(bs) > 0 && d.d.c == containerMapKey && d.h.MapKeyAsString {
  966. if bytes.Equal(bs, jsonLiteralNull) {
  967. z.v = valueTypeNil
  968. } else if bytes.Equal(bs, jsonLiteralTrue) {
  969. z.v = valueTypeBool
  970. z.b = true
  971. } else if bytes.Equal(bs, jsonLiteralFalse) {
  972. z.v = valueTypeBool
  973. z.b = false
  974. } else {
  975. // check if a number: float, int or uint
  976. if err := d.nakedNum(z, bs); err != nil {
  977. z.v = valueTypeString
  978. z.s = d.sliceToString(bs)
  979. }
  980. }
  981. } else {
  982. z.v = valueTypeString
  983. z.s = d.sliceToString(bs)
  984. }
  985. default: // number
  986. bs = d.d.decRd.readNumberWithLastByte()
  987. d.tok = 0
  988. if len(bs) == 0 {
  989. d.d.errorf("decode number from empty string")
  990. return
  991. }
  992. if err := d.nakedNum(z, bs); err != nil {
  993. d.d.errorf("decode number from %s: %v", bs, err)
  994. return
  995. }
  996. }
  997. }
  998. //----------------------
  999. // JsonHandle is a handle for JSON encoding format.
  1000. //
  1001. // Json is comprehensively supported:
  1002. // - decodes numbers into interface{} as int, uint or float64
  1003. // based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
  1004. // - decode integers from float formatted numbers e.g. 1.27e+8
  1005. // - decode any json value (numbers, bool, etc) from quoted strings
  1006. // - configurable way to encode/decode []byte .
  1007. // by default, encodes and decodes []byte using base64 Std Encoding
  1008. // - UTF-8 support for encoding and decoding
  1009. //
  1010. // It has better performance than the json library in the standard library,
  1011. // by leveraging the performance improvements of the codec library.
  1012. //
  1013. // In addition, it doesn't read more bytes than necessary during a decode, which allows
  1014. // reading multiple values from a stream containing json and non-json content.
  1015. // For example, a user can read a json value, then a cbor value, then a msgpack value,
  1016. // all from the same stream in sequence.
  1017. //
  1018. // Note that, when decoding quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are
  1019. // not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.
  1020. type JsonHandle struct {
  1021. textEncodingType
  1022. BasicHandle
  1023. // Indent indicates how a value is encoded.
  1024. // - If positive, indent by that number of spaces.
  1025. // - If negative, indent by that number of tabs.
  1026. Indent int8
  1027. // IntegerAsString controls how integers (signed and unsigned) are encoded.
  1028. //
  1029. // Per the JSON Spec, JSON numbers are 64-bit floating point numbers.
  1030. // Consequently, integers > 2^53 cannot be represented as a JSON number without losing precision.
  1031. // This can be mitigated by configuring how to encode integers.
  1032. //
  1033. // IntegerAsString interpretes the following values:
  1034. // - if 'L', then encode integers > 2^53 as a json string.
  1035. // - if 'A', then encode all integers as a json string
  1036. // containing the exact integer representation as a decimal.
  1037. // - else encode all integers as a json number (default)
  1038. IntegerAsString byte
  1039. // HTMLCharsAsIs controls how to encode some special characters to html: < > &
  1040. //
  1041. // By default, we encode them as \uXXX
  1042. // to prevent security holes when served from some browsers.
  1043. HTMLCharsAsIs bool
  1044. // PreferFloat says that we will default to decoding a number as a float.
  1045. // If not set, we will examine the characters of the number and decode as an
  1046. // integer type if it doesn't have any of the characters [.eE].
  1047. PreferFloat bool
  1048. // TermWhitespace says that we add a whitespace character
  1049. // at the end of an encoding.
  1050. //
  1051. // The whitespace is important, especially if using numbers in a context
  1052. // where multiple items are written to a stream.
  1053. TermWhitespace bool
  1054. // MapKeyAsString says to encode all map keys as strings.
  1055. //
  1056. // Use this to enforce strict json output.
  1057. // The only caveat is that nil value is ALWAYS written as null (never as "null")
  1058. MapKeyAsString bool
  1059. // _ uint64 // padding (cache line)
  1060. // Note: below, we store hardly-used items
  1061. // e.g. RawBytesExt (which is already cached in the (en|de)cDriver).
  1062. // RawBytesExt, if configured, is used to encode and decode raw bytes in a custom way.
  1063. // If not configured, raw bytes are encoded to/from base64 text.
  1064. RawBytesExt InterfaceExt
  1065. _ [5]uint64 // padding (cache line)
  1066. }
  1067. // Name returns the name of the handle: json
  1068. func (h *JsonHandle) Name() string { return "json" }
  1069. // func (h *JsonHandle) hasElemSeparators() bool { return true }
  1070. func (h *JsonHandle) typical() bool {
  1071. return h.Indent == 0 && !h.MapKeyAsString && h.IntegerAsString != 'A' && h.IntegerAsString != 'L'
  1072. }
  1073. func (h *JsonHandle) newEncDriver() encDriver {
  1074. var e = &jsonEncDriver{h: h}
  1075. e.e.e = e
  1076. e.e.js = true
  1077. e.e.init(h)
  1078. e.reset()
  1079. return e
  1080. }
  1081. func (h *JsonHandle) newDecDriver() decDriver {
  1082. var d = &jsonDecDriver{h: h}
  1083. d.d.d = d
  1084. d.d.js = true
  1085. d.d.jsms = h.MapKeyAsString
  1086. d.d.init(h)
  1087. d.reset()
  1088. return d
  1089. }
  1090. func (e *jsonEncDriver) reset() {
  1091. // (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b)
  1092. e.typical = e.h.typical()
  1093. if e.h.HTMLCharsAsIs {
  1094. e.s = &jsonCharSafeSet
  1095. } else {
  1096. e.s = &jsonCharHtmlSafeSet
  1097. }
  1098. e.se.InterfaceExt = e.h.RawBytesExt
  1099. e.d, e.dl, e.di = false, 0, 0
  1100. if e.h.Indent != 0 {
  1101. e.d = true
  1102. e.di = int8(e.h.Indent)
  1103. }
  1104. e.ks = e.h.MapKeyAsString
  1105. e.is = e.h.IntegerAsString
  1106. }
  1107. func (d *jsonDecDriver) reset() {
  1108. d.se.InterfaceExt = d.h.RawBytesExt
  1109. d.buf = d.d.blist.check(d.buf, 256)[:0]
  1110. d.tok = 0
  1111. d.fnil = false
  1112. }
  1113. func (d *jsonDecDriver) atEndOfDecode() {}
  1114. func jsonFloatStrconvFmtPrec64(f float64) (fmt byte, prec int8) {
  1115. fmt = 'f'
  1116. prec = -1
  1117. var abs = math.Abs(f)
  1118. if abs == 0 || abs == 1 {
  1119. prec = 1
  1120. } else if abs < 1e-6 || abs >= 1e21 {
  1121. fmt = 'e'
  1122. } else if noFrac64(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1123. prec = 1
  1124. }
  1125. return
  1126. }
  1127. func jsonFloatStrconvFmtPrec32(f float32) (fmt byte, prec int8) {
  1128. fmt = 'f'
  1129. prec = -1
  1130. var abs = abs32(f)
  1131. if abs == 0 || abs == 1 {
  1132. prec = 1
  1133. } else if abs < 1e-6 || abs >= 1e21 {
  1134. fmt = 'e'
  1135. } else if noFrac32(abs) { // _, frac := math.Modf(abs); frac == 0 {
  1136. prec = 1
  1137. }
  1138. return
  1139. }
  1140. var _ decDriverContainerTracker = (*jsonDecDriver)(nil)
  1141. var _ encDriverContainerTracker = (*jsonEncDriver)(nil)
  1142. var _ decDriver = (*jsonDecDriver)(nil)
  1143. var _ encDriver = (*jsonEncDriver)(nil)
  1144. // ----------------
  1145. /*
  1146. type jsonEncDriverTypical jsonEncDriver
  1147. func (e *jsonEncDriverTypical) WriteArrayStart(length int) {
  1148. e.e.encWr.writen1('[')
  1149. }
  1150. func (e *jsonEncDriverTypical) WriteArrayElem() {
  1151. if e.e.c != containerArrayStart {
  1152. e.e.encWr.writen1(',')
  1153. }
  1154. }
  1155. func (e *jsonEncDriverTypical) WriteArrayEnd() {
  1156. e.e.encWr.writen1(']')
  1157. }
  1158. func (e *jsonEncDriverTypical) WriteMapStart(length int) {
  1159. e.e.encWr.writen1('{')
  1160. }
  1161. func (e *jsonEncDriverTypical) WriteMapElemKey() {
  1162. if e.e.c != containerMapStart {
  1163. e.e.encWr.writen1(',')
  1164. }
  1165. }
  1166. func (e *jsonEncDriverTypical) WriteMapElemValue() {
  1167. e.e.encWr.writen1(':')
  1168. }
  1169. func (e *jsonEncDriverTypical) WriteMapEnd() {
  1170. e.e.encWr.writen1('}')
  1171. }
  1172. func (e *jsonEncDriverTypical) EncodeBool(b bool) {
  1173. if b {
  1174. // e.e.encWr.writeb(jsonLiteralTrue)
  1175. e.e.encWr.writen([rwNLen]byte{'t', 'r', 'u', 'e'}, 4)
  1176. } else {
  1177. // e.e.encWr.writeb(jsonLiteralFalse)
  1178. e.e.encWr.writen([rwNLen]byte{'f', 'a', 'l', 's', 'e'}, 5)
  1179. }
  1180. }
  1181. func (e *jsonEncDriverTypical) EncodeInt(v int64) {
  1182. e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
  1183. }
  1184. func (e *jsonEncDriverTypical) EncodeUint(v uint64) {
  1185. e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
  1186. }
  1187. func (e *jsonEncDriverTypical) EncodeFloat64(f float64) {
  1188. fmt, prec := jsonFloatStrconvFmtPrec64(f)
  1189. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), 64))
  1190. // e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, jsonFloatStrconvFmtPrec64(f), 64))
  1191. }
  1192. func (e *jsonEncDriverTypical) EncodeFloat32(f float32) {
  1193. fmt, prec := jsonFloatStrconvFmtPrec32(f)
  1194. e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], float64(f), fmt, int(prec), 32))
  1195. }
  1196. // func (e *jsonEncDriverTypical) encodeFloat(f float64, bitsize uint8) {
  1197. // fmt, prec := jsonFloatStrconvFmtPrec(f, bitsize == 32)
  1198. // e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, prec, int(bitsize)))
  1199. // }
  1200. // func (e *jsonEncDriverTypical) atEndOfEncode() {
  1201. // if e.tw {
  1202. // e.e.encWr.writen1(' ')
  1203. // }
  1204. // }
  1205. */
  1206. /*
  1207. func (d *jsonDecDriver) appendStringAsBytes() (bs []byte) {
  1208. if d.buf != nil {
  1209. d.buf = d.buf[:0]
  1210. }
  1211. d.tok = 0
  1212. // append on each byte seen can be expensive, so we just
  1213. // keep track of where we last read a contiguous set of
  1214. // non-special bytes (using cursor variable),
  1215. // and when we see a special byte
  1216. // e.g. end-of-slice, " or \,
  1217. // we will append the full range into the v slice before proceeding
  1218. var cs = d.d.decRd.readUntil('"', true)
  1219. var c uint8
  1220. var i, cursor uint
  1221. for {
  1222. if i >= uint(len(cs)) {
  1223. d.buf = append(d.buf, cs[cursor:]...)
  1224. cs = d.d.decRd.readUntil('"', true)
  1225. i, cursor = 0, 0
  1226. continue // this continue helps elide the cs[i] below
  1227. }
  1228. c = cs[i]
  1229. if c == '"' {
  1230. break
  1231. }
  1232. if c != '\\' {
  1233. i++
  1234. continue
  1235. }
  1236. d.buf = append(d.buf, cs[cursor:i]...)
  1237. i++
  1238. if i >= uint(len(cs)) {
  1239. d.d.errorf("need at least 1 more bytes for \\ escape sequence")
  1240. return // bounds-check elimination
  1241. }
  1242. c = cs[i]
  1243. switch c {
  1244. case '"', '\\', '/', '\'':
  1245. d.buf = append(d.buf, c)
  1246. case 'b':
  1247. d.buf = append(d.buf, '\b')
  1248. case 'f':
  1249. d.buf = append(d.buf, '\f')
  1250. case 'n':
  1251. d.buf = append(d.buf, '\n')
  1252. case 'r':
  1253. d.buf = append(d.buf, '\r')
  1254. case 't':
  1255. d.buf = append(d.buf, '\t')
  1256. case 'u':
  1257. i = d.appendStringAsBytesSlashU(cs, i)
  1258. default:
  1259. d.d.errorf("unsupported escaped value: %c", c)
  1260. }
  1261. i++
  1262. cursor = i
  1263. }
  1264. if len(cs) > 0 {
  1265. if len(d.buf) > 0 && cursor < uint(len(cs)) {
  1266. d.buf = append(d.buf, cs[cursor:i]...)
  1267. } else {
  1268. // if bytes, just return the cs got from readUntil.
  1269. // do not do it for io, especially bufio, as the buffer is needed for other things
  1270. cs = cs[:i]
  1271. if d.d.bytes {
  1272. return cs
  1273. }
  1274. d.buf = d.d.blist.check(d.buf, len(cs))
  1275. copy(d.buf, cs)
  1276. }
  1277. }
  1278. return d.buf
  1279. }
  1280. func (d *jsonDecDriver) appendStringAsBytesSlashU(cs []byte, i uint) uint {
  1281. var r rune
  1282. var rr uint32
  1283. var j uint
  1284. var c byte
  1285. if uint(len(cs)) < i+4 {
  1286. d.d.errorf("need at least 4 more bytes for unicode sequence")
  1287. return 0 // bounds-check elimination
  1288. }
  1289. for _, c = range cs[i+1 : i+5] { // bounds-check-elimination
  1290. // best to use explicit if-else
  1291. // - not a table, etc which involve memory loads, array lookup with bounds checks, etc
  1292. if c >= '0' && c <= '9' {
  1293. rr = rr*16 + uint32(c-jsonU4Chk2)
  1294. } else if c >= 'a' && c <= 'f' {
  1295. rr = rr*16 + uint32(c-jsonU4Chk1)
  1296. } else if c >= 'A' && c <= 'F' {
  1297. rr = rr*16 + uint32(c-jsonU4Chk0)
  1298. } else {
  1299. r = unicode.ReplacementChar
  1300. i += 4
  1301. goto encode_rune
  1302. }
  1303. }
  1304. r = rune(rr)
  1305. i += 4
  1306. if utf16.IsSurrogate(r) {
  1307. if len(cs) >= int(i+6) {
  1308. var cx = cs[i+1:][:6:6] // [:6] affords bounds-check-elimination
  1309. //var cx [6]byte
  1310. //copy(cx[:], cs[i+1:])
  1311. if cx[0] == '\\' && cx[1] == 'u' {
  1312. i += 2
  1313. var rr1 uint32
  1314. for j = 2; j < 6; j++ {
  1315. c = cx[j]
  1316. if c >= '0' && c <= '9' {
  1317. rr = rr*16 + uint32(c-jsonU4Chk2)
  1318. } else if c >= 'a' && c <= 'f' {
  1319. rr = rr*16 + uint32(c-jsonU4Chk1)
  1320. } else if c >= 'A' && c <= 'F' {
  1321. rr = rr*16 + uint32(c-jsonU4Chk0)
  1322. } else {
  1323. r = unicode.ReplacementChar
  1324. i += 4
  1325. goto encode_rune
  1326. }
  1327. }
  1328. r = utf16.DecodeRune(r, rune(rr1))
  1329. i += 4
  1330. goto encode_rune
  1331. }
  1332. }
  1333. r = unicode.ReplacementChar
  1334. }
  1335. encode_rune:
  1336. w2 := utf8.EncodeRune(d.bstr[:], r)
  1337. d.buf = append(d.buf, d.bstr[:w2]...)
  1338. return i
  1339. }
  1340. */
  1341. /*
  1342. // jsonFloatStrconvFmtPrec ...
  1343. //
  1344. // ensure that every float has an 'e' or '.' in it,/ for easy differentiation from integers.
  1345. // this is better/faster than checking if encoded value has [e.] and appending if needed.
  1346. // func jsonFloatStrconvFmtPrec(f float64, bits32 bool) (fmt byte, prec int) {
  1347. // fmt = 'f'
  1348. // prec = -1
  1349. // var abs = math.Abs(f)
  1350. // if abs == 0 || abs == 1 {
  1351. // prec = 1
  1352. // } else if !bits32 && (abs < 1e-6 || abs >= 1e21) ||
  1353. // bits32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
  1354. // fmt = 'e'
  1355. // } else if _, frac := math.Modf(abs); frac == 0 {
  1356. // // ensure that floats have a .0 at the end, for easy identification as floats
  1357. // prec = 1
  1358. // }
  1359. // return
  1360. // }
  1361. */