json.go 40 KB

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