binc.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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. import (
  5. "math"
  6. "reflect"
  7. "time"
  8. )
  9. const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning.
  10. // vd as low 4 bits (there are 16 slots)
  11. const (
  12. bincVdSpecial byte = iota
  13. bincVdPosInt
  14. bincVdNegInt
  15. bincVdFloat
  16. bincVdString
  17. bincVdByteArray
  18. bincVdArray
  19. bincVdMap
  20. bincVdTimestamp
  21. bincVdSmallInt
  22. bincVdUnicodeOther
  23. bincVdSymbol
  24. bincVdDecimal
  25. _ // open slot
  26. _ // open slot
  27. bincVdCustomExt = 0x0f
  28. )
  29. const (
  30. bincSpNil byte = iota
  31. bincSpFalse
  32. bincSpTrue
  33. bincSpNan
  34. bincSpPosInf
  35. bincSpNegInf
  36. bincSpZeroFloat
  37. bincSpZero
  38. bincSpNegOne
  39. )
  40. const (
  41. bincFlBin16 byte = iota
  42. bincFlBin32
  43. _ // bincFlBin32e
  44. bincFlBin64
  45. _ // bincFlBin64e
  46. // others not currently supported
  47. )
  48. func bincdesc(vd, vs byte) string {
  49. switch vd {
  50. case bincVdSpecial:
  51. switch vs {
  52. case bincSpNil:
  53. return "nil"
  54. case bincSpFalse:
  55. return "false"
  56. case bincSpTrue:
  57. return "true"
  58. case bincSpNan, bincSpPosInf, bincSpNegInf, bincSpZeroFloat:
  59. return "float"
  60. case bincSpZero:
  61. return "uint"
  62. case bincSpNegOne:
  63. return "int"
  64. default:
  65. return "unknown"
  66. }
  67. case bincVdSmallInt, bincVdPosInt:
  68. return "uint"
  69. case bincVdNegInt:
  70. return "int"
  71. case bincVdFloat:
  72. return "float"
  73. case bincVdSymbol:
  74. return "string"
  75. case bincVdString:
  76. return "string"
  77. case bincVdByteArray:
  78. return "bytes"
  79. case bincVdTimestamp:
  80. return "time"
  81. case bincVdCustomExt:
  82. return "ext"
  83. case bincVdArray:
  84. return "array"
  85. case bincVdMap:
  86. return "map"
  87. default:
  88. return "unknown"
  89. }
  90. }
  91. type bincEncDriver struct {
  92. e *Encoder
  93. h *BincHandle
  94. w *encWriterSwitch
  95. m map[string]uint16 // symbols
  96. b [16]byte // scratch, used for encoding numbers - bigendian style
  97. s uint16 // symbols sequencer
  98. // c containerState
  99. encDriverTrackContainerWriter
  100. noBuiltInTypes
  101. // encNoSeparator
  102. // _ [1]uint64 // padding
  103. }
  104. func (e *bincEncDriver) EncodeNil() {
  105. e.w.writen1(bincVdSpecial<<4 | bincSpNil)
  106. }
  107. func (e *bincEncDriver) EncodeTime(t time.Time) {
  108. if t.IsZero() {
  109. e.EncodeNil()
  110. } else {
  111. bs := bincEncodeTime(t)
  112. e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs)))
  113. e.w.writeb(bs)
  114. }
  115. }
  116. func (e *bincEncDriver) EncodeBool(b bool) {
  117. if b {
  118. e.w.writen1(bincVdSpecial<<4 | bincSpTrue)
  119. } else {
  120. e.w.writen1(bincVdSpecial<<4 | bincSpFalse)
  121. }
  122. }
  123. func (e *bincEncDriver) EncodeFloat32(f float32) {
  124. if f == 0 {
  125. e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
  126. return
  127. }
  128. e.w.writen1(bincVdFloat<<4 | bincFlBin32)
  129. bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f))
  130. }
  131. func (e *bincEncDriver) EncodeFloat64(f float64) {
  132. if f == 0 {
  133. e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
  134. return
  135. }
  136. bigen.PutUint64(e.b[:8], math.Float64bits(f))
  137. if bincDoPrune {
  138. i := 7
  139. for ; i >= 0 && (e.b[i] == 0); i-- {
  140. }
  141. i++
  142. if i <= 6 {
  143. e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64)
  144. e.w.writen1(byte(i))
  145. e.w.writeb(e.b[:i])
  146. return
  147. }
  148. }
  149. e.w.writen1(bincVdFloat<<4 | bincFlBin64)
  150. e.w.writeb(e.b[:8])
  151. }
  152. func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) {
  153. if lim == 4 {
  154. bigen.PutUint32(e.b[:lim], uint32(v))
  155. } else {
  156. bigen.PutUint64(e.b[:lim], v)
  157. }
  158. if bincDoPrune {
  159. i := pruneSignExt(e.b[:lim], pos)
  160. e.w.writen1(bd | lim - 1 - byte(i))
  161. e.w.writeb(e.b[i:lim])
  162. } else {
  163. e.w.writen1(bd | lim - 1)
  164. e.w.writeb(e.b[:lim])
  165. }
  166. }
  167. func (e *bincEncDriver) EncodeInt(v int64) {
  168. // const nbd byte = bincVdNegInt << 4
  169. if v >= 0 {
  170. e.encUint(bincVdPosInt<<4, true, uint64(v))
  171. } else if v == -1 {
  172. e.w.writen1(bincVdSpecial<<4 | bincSpNegOne)
  173. } else {
  174. e.encUint(bincVdNegInt<<4, false, uint64(-v))
  175. }
  176. }
  177. func (e *bincEncDriver) EncodeUint(v uint64) {
  178. e.encUint(bincVdPosInt<<4, true, v)
  179. }
  180. func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) {
  181. if v == 0 {
  182. e.w.writen1(bincVdSpecial<<4 | bincSpZero)
  183. } else if pos && v >= 1 && v <= 16 {
  184. e.w.writen1(bincVdSmallInt<<4 | byte(v-1))
  185. } else if v <= math.MaxUint8 {
  186. e.w.writen2(bd|0x0, byte(v))
  187. } else if v <= math.MaxUint16 {
  188. e.w.writen1(bd | 0x01)
  189. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v))
  190. } else if v <= math.MaxUint32 {
  191. e.encIntegerPrune(bd, pos, v, 4)
  192. } else {
  193. e.encIntegerPrune(bd, pos, v, 8)
  194. }
  195. }
  196. func (e *bincEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) {
  197. bs := ext.WriteExt(rv)
  198. if bs == nil {
  199. e.EncodeNil()
  200. return
  201. }
  202. e.encodeExtPreamble(uint8(xtag), len(bs))
  203. e.w.writeb(bs)
  204. }
  205. func (e *bincEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  206. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  207. e.w.writeb(re.Data)
  208. }
  209. func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
  210. e.encLen(bincVdCustomExt<<4, uint64(length))
  211. e.w.writen1(xtag)
  212. }
  213. func (e *bincEncDriver) WriteArrayStart(length int) {
  214. e.encLen(bincVdArray<<4, uint64(length))
  215. e.c = containerArrayStart
  216. }
  217. func (e *bincEncDriver) WriteMapStart(length int) {
  218. e.encLen(bincVdMap<<4, uint64(length))
  219. e.c = containerMapStart
  220. }
  221. func (e *bincEncDriver) EncodeSymbol(v string) {
  222. // if WriteSymbolsNoRefs {
  223. // e.encodeString(cUTF8, v)
  224. // return
  225. // }
  226. //symbols only offer benefit when string length > 1.
  227. //This is because strings with length 1 take only 2 bytes to store
  228. //(bd with embedded length, and single byte for string val).
  229. l := len(v)
  230. if l == 0 {
  231. e.encBytesLen(cUTF8, 0)
  232. return
  233. } else if l == 1 {
  234. e.encBytesLen(cUTF8, 1)
  235. e.w.writen1(v[0])
  236. return
  237. }
  238. if e.m == nil {
  239. e.m = make(map[string]uint16, 16)
  240. }
  241. ui, ok := e.m[v]
  242. if ok {
  243. if ui <= math.MaxUint8 {
  244. e.w.writen2(bincVdSymbol<<4, byte(ui))
  245. } else {
  246. e.w.writen1(bincVdSymbol<<4 | 0x8)
  247. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  248. }
  249. } else {
  250. e.s++
  251. ui = e.s
  252. //ui = uint16(atomic.AddUint32(&e.s, 1))
  253. e.m[v] = ui
  254. var lenprec uint8
  255. if l <= math.MaxUint8 {
  256. // lenprec = 0
  257. } else if l <= math.MaxUint16 {
  258. lenprec = 1
  259. } else if int64(l) <= math.MaxUint32 {
  260. lenprec = 2
  261. } else {
  262. lenprec = 3
  263. }
  264. if ui <= math.MaxUint8 {
  265. e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
  266. } else {
  267. e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
  268. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  269. }
  270. if lenprec == 0 {
  271. e.w.writen1(byte(l))
  272. } else if lenprec == 1 {
  273. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l))
  274. } else if lenprec == 2 {
  275. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l))
  276. } else {
  277. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l))
  278. }
  279. e.w.writestr(v)
  280. }
  281. }
  282. func (e *bincEncDriver) EncodeStringEnc(c charEncoding, v string) {
  283. if e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 0 || e.h.AsSymbols == 1) {
  284. e.EncodeSymbol(v)
  285. return
  286. }
  287. l := uint64(len(v))
  288. e.encLen(bincVdString<<4, l) // e.encBytesLen(c, l)
  289. if l > 0 {
  290. e.w.writestr(v)
  291. }
  292. }
  293. func (e *bincEncDriver) EncodeStringBytesRaw(v []byte) {
  294. if v == nil {
  295. e.EncodeNil()
  296. return
  297. }
  298. l := uint64(len(v))
  299. e.encLen(bincVdByteArray<<4, l) // e.encBytesLen(c, l)
  300. if l > 0 {
  301. e.w.writeb(v)
  302. }
  303. }
  304. func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
  305. //TODO: support bincUnicodeOther (for now, just use string or bytearray)
  306. if c == cRAW {
  307. e.encLen(bincVdByteArray<<4, length)
  308. } else {
  309. e.encLen(bincVdString<<4, length)
  310. }
  311. }
  312. func (e *bincEncDriver) encLen(bd byte, l uint64) {
  313. if l < 12 {
  314. e.w.writen1(bd | uint8(l+4))
  315. } else {
  316. e.encLenNumber(bd, l)
  317. }
  318. }
  319. func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
  320. if v <= math.MaxUint8 {
  321. e.w.writen2(bd, byte(v))
  322. } else if v <= math.MaxUint16 {
  323. e.w.writen1(bd | 0x01)
  324. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v))
  325. } else if v <= math.MaxUint32 {
  326. e.w.writen1(bd | 0x02)
  327. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v))
  328. } else {
  329. e.w.writen1(bd | 0x03)
  330. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v))
  331. }
  332. }
  333. //------------------------------------
  334. type bincDecSymbol struct {
  335. s string
  336. b []byte
  337. i uint16
  338. }
  339. type bincDecDriver struct {
  340. decDriverNoopContainerReader
  341. noBuiltInTypes
  342. d *Decoder
  343. h *BincHandle
  344. r *decReaderSwitch
  345. br bool // bytes reader
  346. bdRead bool
  347. bd byte
  348. vd byte
  349. vs byte
  350. // _ [3]byte // padding
  351. // linear searching on this slice is ok,
  352. // because we typically expect < 32 symbols in each stream.
  353. s []bincDecSymbol
  354. // noStreamingCodec
  355. // decNoSeparator
  356. b [(8 + 1) * 8]byte // scratch
  357. }
  358. func (d *bincDecDriver) readNextBd() {
  359. d.bd = d.r.readn1()
  360. d.vd = d.bd >> 4
  361. d.vs = d.bd & 0x0f
  362. d.bdRead = true
  363. }
  364. func (d *bincDecDriver) uncacheRead() {
  365. if d.bdRead {
  366. d.r.unreadn1()
  367. d.bdRead = false
  368. }
  369. }
  370. func (d *bincDecDriver) ContainerType() (vt valueType) {
  371. if !d.bdRead {
  372. d.readNextBd()
  373. }
  374. if d.vd == bincVdSpecial && d.vs == bincSpNil {
  375. return valueTypeNil
  376. } else if d.vd == bincVdByteArray {
  377. return valueTypeBytes
  378. } else if d.vd == bincVdString {
  379. return valueTypeString
  380. } else if d.vd == bincVdArray {
  381. return valueTypeArray
  382. } else if d.vd == bincVdMap {
  383. return valueTypeMap
  384. }
  385. // else {
  386. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  387. // }
  388. return valueTypeUnset
  389. }
  390. func (d *bincDecDriver) TryDecodeAsNil() bool {
  391. if !d.bdRead {
  392. d.readNextBd()
  393. }
  394. if d.bd == bincVdSpecial<<4|bincSpNil {
  395. d.bdRead = false
  396. return true
  397. }
  398. return false
  399. }
  400. func (d *bincDecDriver) DecodeTime() (t time.Time) {
  401. if !d.bdRead {
  402. d.readNextBd()
  403. }
  404. if d.bd == bincVdSpecial<<4|bincSpNil {
  405. d.bdRead = false
  406. return
  407. }
  408. if d.vd != bincVdTimestamp {
  409. d.d.errorf("cannot decode time - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  410. return
  411. }
  412. t, err := bincDecodeTime(d.r.readx(uint(d.vs)))
  413. if err != nil {
  414. panic(err)
  415. }
  416. d.bdRead = false
  417. return
  418. }
  419. func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) {
  420. if vs&0x8 == 0 {
  421. d.r.readb(d.b[0:defaultLen])
  422. } else {
  423. l := d.r.readn1()
  424. if l > 8 {
  425. d.d.errorf("cannot read float - at most 8 bytes used to represent float - received %v bytes", l)
  426. return
  427. }
  428. for i := l; i < 8; i++ {
  429. d.b[i] = 0
  430. }
  431. d.r.readb(d.b[0:l])
  432. }
  433. }
  434. func (d *bincDecDriver) decFloat() (f float64) {
  435. //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; }
  436. if x := d.vs & 0x7; x == bincFlBin32 {
  437. d.decFloatPre(d.vs, 4)
  438. f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4])))
  439. } else if x == bincFlBin64 {
  440. d.decFloatPre(d.vs, 8)
  441. f = math.Float64frombits(bigen.Uint64(d.b[0:8]))
  442. } else {
  443. d.d.errorf("read float - only float32 and float64 are supported - %s %x-%x/%s",
  444. msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  445. return
  446. }
  447. return
  448. }
  449. func (d *bincDecDriver) decUint() (v uint64) {
  450. // need to inline the code (interface conversion and type assertion expensive)
  451. switch d.vs {
  452. case 0:
  453. v = uint64(d.r.readn1())
  454. case 1:
  455. d.r.readb(d.b[6:8])
  456. v = uint64(bigen.Uint16(d.b[6:8]))
  457. case 2:
  458. d.b[4] = 0
  459. d.r.readb(d.b[5:8])
  460. v = uint64(bigen.Uint32(d.b[4:8]))
  461. case 3:
  462. d.r.readb(d.b[4:8])
  463. v = uint64(bigen.Uint32(d.b[4:8]))
  464. case 4, 5, 6:
  465. lim := 7 - d.vs
  466. d.r.readb(d.b[lim:8])
  467. for i := uint8(0); i < lim; i++ {
  468. d.b[i] = 0
  469. }
  470. v = uint64(bigen.Uint64(d.b[:8]))
  471. case 7:
  472. d.r.readb(d.b[:8])
  473. v = uint64(bigen.Uint64(d.b[:8]))
  474. default:
  475. d.d.errorf("unsigned integers with greater than 64 bits of precision not supported")
  476. return
  477. }
  478. return
  479. }
  480. func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) {
  481. if !d.bdRead {
  482. d.readNextBd()
  483. }
  484. vd, vs := d.vd, d.vs
  485. if vd == bincVdPosInt {
  486. ui = d.decUint()
  487. } else if vd == bincVdNegInt {
  488. ui = d.decUint()
  489. neg = true
  490. } else if vd == bincVdSmallInt {
  491. ui = uint64(d.vs) + 1
  492. } else if vd == bincVdSpecial {
  493. if vs == bincSpZero {
  494. //i = 0
  495. } else if vs == bincSpNegOne {
  496. neg = true
  497. ui = 1
  498. } else {
  499. d.d.errorf("integer decode fails - invalid special value from descriptor %x-%x/%s",
  500. d.vd, d.vs, bincdesc(d.vd, d.vs))
  501. return
  502. }
  503. } else {
  504. d.d.errorf("integer can only be decoded from int/uint. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
  505. return
  506. }
  507. return
  508. }
  509. func (d *bincDecDriver) DecodeInt64() (i int64) {
  510. ui, neg := d.decCheckInteger()
  511. i = chkOvf.SignedIntV(ui)
  512. if neg {
  513. i = -i
  514. }
  515. d.bdRead = false
  516. return
  517. }
  518. func (d *bincDecDriver) DecodeUint64() (ui uint64) {
  519. ui, neg := d.decCheckInteger()
  520. if neg {
  521. d.d.errorf("assigning negative signed value to unsigned integer type")
  522. return
  523. }
  524. d.bdRead = false
  525. return
  526. }
  527. func (d *bincDecDriver) DecodeFloat64() (f float64) {
  528. if !d.bdRead {
  529. d.readNextBd()
  530. }
  531. vd, vs := d.vd, d.vs
  532. if vd == bincVdSpecial {
  533. d.bdRead = false
  534. if vs == bincSpNan {
  535. return math.NaN()
  536. } else if vs == bincSpPosInf {
  537. return math.Inf(1)
  538. } else if vs == bincSpZeroFloat || vs == bincSpZero {
  539. return
  540. } else if vs == bincSpNegInf {
  541. return math.Inf(-1)
  542. } else {
  543. d.d.errorf("float - invalid special value from descriptor %x-%x/%s",
  544. d.vd, d.vs, bincdesc(d.vd, d.vs))
  545. return
  546. }
  547. } else if vd == bincVdFloat {
  548. f = d.decFloat()
  549. } else {
  550. f = float64(d.DecodeInt64())
  551. }
  552. d.bdRead = false
  553. return
  554. }
  555. // bool can be decoded from bool only (single byte).
  556. func (d *bincDecDriver) DecodeBool() (b bool) {
  557. if !d.bdRead {
  558. d.readNextBd()
  559. }
  560. if bd := d.bd; bd == (bincVdSpecial | bincSpFalse) {
  561. // b = false
  562. } else if bd == (bincVdSpecial | bincSpTrue) {
  563. b = true
  564. } else {
  565. d.d.errorf("bool - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  566. return
  567. }
  568. d.bdRead = false
  569. return
  570. }
  571. func (d *bincDecDriver) ReadMapStart() (length int) {
  572. if !d.bdRead {
  573. d.readNextBd()
  574. }
  575. if d.vd != bincVdMap {
  576. d.d.errorf("map - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  577. return
  578. }
  579. length = d.decLen()
  580. d.bdRead = false
  581. return
  582. }
  583. func (d *bincDecDriver) ReadArrayStart() (length int) {
  584. if !d.bdRead {
  585. d.readNextBd()
  586. }
  587. if d.vd != bincVdArray {
  588. d.d.errorf("array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  589. return
  590. }
  591. length = d.decLen()
  592. d.bdRead = false
  593. return
  594. }
  595. func (d *bincDecDriver) decLen() int {
  596. if d.vs > 3 {
  597. return int(d.vs - 4)
  598. }
  599. return int(d.decLenNumber())
  600. }
  601. func (d *bincDecDriver) decLenNumber() (v uint64) {
  602. if x := d.vs; x == 0 {
  603. v = uint64(d.r.readn1())
  604. } else if x == 1 {
  605. d.r.readb(d.b[6:8])
  606. v = uint64(bigen.Uint16(d.b[6:8]))
  607. } else if x == 2 {
  608. d.r.readb(d.b[4:8])
  609. v = uint64(bigen.Uint32(d.b[4:8]))
  610. } else {
  611. d.r.readb(d.b[:8])
  612. v = bigen.Uint64(d.b[:8])
  613. }
  614. return
  615. }
  616. func (d *bincDecDriver) decStringAndBytes(bs []byte, withString, zerocopy bool) (
  617. bs2 []byte, s string) {
  618. if !d.bdRead {
  619. d.readNextBd()
  620. }
  621. if d.bd == bincVdSpecial<<4|bincSpNil {
  622. d.bdRead = false
  623. return
  624. }
  625. var slen = -1
  626. // var ok bool
  627. switch d.vd {
  628. case bincVdString, bincVdByteArray:
  629. slen = d.decLen()
  630. if zerocopy {
  631. if d.br {
  632. bs2 = d.r.readx(uint(slen))
  633. } else if len(bs) == 0 {
  634. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.b[:])
  635. } else {
  636. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  637. }
  638. } else {
  639. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  640. }
  641. if withString {
  642. s = string(bs2)
  643. }
  644. case bincVdSymbol:
  645. // zerocopy doesn't apply for symbols,
  646. // as the values must be stored in a table for later use.
  647. //
  648. //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision,
  649. //extract symbol
  650. //if containsStringVal, read it and put in map
  651. //else look in map for string value
  652. var symbol uint16
  653. vs := d.vs
  654. if vs&0x8 == 0 {
  655. symbol = uint16(d.r.readn1())
  656. } else {
  657. symbol = uint16(bigen.Uint16(d.r.readx(2)))
  658. }
  659. if d.s == nil {
  660. d.s = make([]bincDecSymbol, 0, 16)
  661. }
  662. if vs&0x4 == 0 {
  663. for i := range d.s {
  664. j := &d.s[i]
  665. if j.i == symbol {
  666. bs2 = j.b
  667. if withString {
  668. if j.s == "" && bs2 != nil {
  669. j.s = string(bs2)
  670. }
  671. s = j.s
  672. }
  673. break
  674. }
  675. }
  676. } else {
  677. switch vs & 0x3 {
  678. case 0:
  679. slen = int(d.r.readn1())
  680. case 1:
  681. slen = int(bigen.Uint16(d.r.readx(2)))
  682. case 2:
  683. slen = int(bigen.Uint32(d.r.readx(4)))
  684. case 3:
  685. slen = int(bigen.Uint64(d.r.readx(8)))
  686. }
  687. // since using symbols, do not store any part of
  688. // the parameter bs in the map, as it might be a shared buffer.
  689. // bs2 = decByteSlice(d.r, slen, bs)
  690. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil)
  691. if withString {
  692. s = string(bs2)
  693. }
  694. d.s = append(d.s, bincDecSymbol{i: symbol, s: s, b: bs2})
  695. }
  696. default:
  697. d.d.errorf("string/bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  698. return
  699. }
  700. d.bdRead = false
  701. return
  702. }
  703. func (d *bincDecDriver) DecodeString() (s string) {
  704. // DecodeBytes does not accommodate symbols, whose impl stores string version in map.
  705. // Use decStringAndBytes directly.
  706. // return string(d.DecodeBytes(d.b[:], true, true))
  707. _, s = d.decStringAndBytes(d.b[:], true, true)
  708. return
  709. }
  710. func (d *bincDecDriver) DecodeStringAsBytes() (s []byte) {
  711. s, _ = d.decStringAndBytes(d.b[:], false, true)
  712. return
  713. }
  714. func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  715. if !d.bdRead {
  716. d.readNextBd()
  717. }
  718. if d.bd == bincVdSpecial<<4|bincSpNil {
  719. d.bdRead = false
  720. return nil
  721. }
  722. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  723. if d.vd == bincVdArray {
  724. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  725. return
  726. }
  727. var clen int
  728. if d.vd == bincVdString || d.vd == bincVdByteArray {
  729. clen = d.decLen()
  730. } else {
  731. d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  732. return
  733. }
  734. d.bdRead = false
  735. if zerocopy {
  736. if d.br {
  737. return d.r.readx(uint(clen))
  738. } else if len(bs) == 0 {
  739. bs = d.b[:]
  740. }
  741. }
  742. return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs)
  743. }
  744. func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  745. if xtag > 0xff {
  746. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  747. return
  748. }
  749. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  750. realxtag = uint64(realxtag1)
  751. if ext == nil {
  752. re := rv.(*RawExt)
  753. re.Tag = realxtag
  754. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  755. } else {
  756. ext.ReadExt(rv, xbs)
  757. }
  758. return
  759. }
  760. func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  761. if !d.bdRead {
  762. d.readNextBd()
  763. }
  764. if d.vd == bincVdCustomExt {
  765. l := d.decLen()
  766. xtag = d.r.readn1()
  767. if verifyTag && xtag != tag {
  768. d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag)
  769. return
  770. }
  771. if d.br {
  772. xbs = d.r.readx(uint(l))
  773. } else {
  774. xbs = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:])
  775. }
  776. } else if d.vd == bincVdByteArray {
  777. xbs = d.DecodeBytes(nil, true)
  778. } else {
  779. d.d.errorf("ext - expecting extensions or byte array - %s %x-%x/%s",
  780. msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  781. return
  782. }
  783. d.bdRead = false
  784. return
  785. }
  786. func (d *bincDecDriver) DecodeNaked() {
  787. if !d.bdRead {
  788. d.readNextBd()
  789. }
  790. n := d.d.naked()
  791. var decodeFurther bool
  792. switch d.vd {
  793. case bincVdSpecial:
  794. switch d.vs {
  795. case bincSpNil:
  796. n.v = valueTypeNil
  797. case bincSpFalse:
  798. n.v = valueTypeBool
  799. n.b = false
  800. case bincSpTrue:
  801. n.v = valueTypeBool
  802. n.b = true
  803. case bincSpNan:
  804. n.v = valueTypeFloat
  805. n.f = math.NaN()
  806. case bincSpPosInf:
  807. n.v = valueTypeFloat
  808. n.f = math.Inf(1)
  809. case bincSpNegInf:
  810. n.v = valueTypeFloat
  811. n.f = math.Inf(-1)
  812. case bincSpZeroFloat:
  813. n.v = valueTypeFloat
  814. n.f = float64(0)
  815. case bincSpZero:
  816. n.v = valueTypeUint
  817. n.u = uint64(0) // int8(0)
  818. case bincSpNegOne:
  819. n.v = valueTypeInt
  820. n.i = int64(-1) // int8(-1)
  821. default:
  822. d.d.errorf("cannot infer value - unrecognized special value from descriptor %x-%x/%s",
  823. d.vd, d.vs, bincdesc(d.vd, d.vs))
  824. }
  825. case bincVdSmallInt:
  826. n.v = valueTypeUint
  827. n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
  828. case bincVdPosInt:
  829. n.v = valueTypeUint
  830. n.u = d.decUint()
  831. case bincVdNegInt:
  832. n.v = valueTypeInt
  833. n.i = -(int64(d.decUint()))
  834. case bincVdFloat:
  835. n.v = valueTypeFloat
  836. n.f = d.decFloat()
  837. case bincVdSymbol:
  838. n.v = valueTypeSymbol
  839. n.s = d.DecodeString()
  840. case bincVdString:
  841. n.v = valueTypeString
  842. n.s = d.DecodeString()
  843. case bincVdByteArray:
  844. decNakedReadRawBytes(d, d.d, n, d.h.RawToString)
  845. case bincVdTimestamp:
  846. n.v = valueTypeTime
  847. tt, err := bincDecodeTime(d.r.readx(uint(d.vs)))
  848. if err != nil {
  849. panic(err)
  850. }
  851. n.t = tt
  852. case bincVdCustomExt:
  853. n.v = valueTypeExt
  854. l := d.decLen()
  855. n.u = uint64(d.r.readn1())
  856. if d.br {
  857. n.l = d.r.readx(uint(l))
  858. } else {
  859. n.l = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:])
  860. }
  861. case bincVdArray:
  862. n.v = valueTypeArray
  863. decodeFurther = true
  864. case bincVdMap:
  865. n.v = valueTypeMap
  866. decodeFurther = true
  867. default:
  868. d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  869. }
  870. if !decodeFurther {
  871. d.bdRead = false
  872. }
  873. if n.v == valueTypeUint && d.h.SignedInteger {
  874. n.v = valueTypeInt
  875. n.i = int64(n.u)
  876. }
  877. }
  878. //------------------------------------
  879. //BincHandle is a Handle for the Binc Schema-Free Encoding Format
  880. //defined at https://github.com/ugorji/binc .
  881. //
  882. //BincHandle currently supports all Binc features with the following EXCEPTIONS:
  883. // - only integers up to 64 bits of precision are supported.
  884. // big integers are unsupported.
  885. // - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
  886. // extended precision and decimal IEEE 754 floats are unsupported.
  887. // - Only UTF-8 strings supported.
  888. // Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
  889. //
  890. //Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
  891. type BincHandle struct {
  892. BasicHandle
  893. binaryEncodingType
  894. noElemSeparators
  895. // AsSymbols defines what should be encoded as symbols.
  896. //
  897. // Encoding as symbols can reduce the encoded size significantly.
  898. //
  899. // However, during decoding, each string to be encoded as a symbol must
  900. // be checked to see if it has been seen before. Consequently, encoding time
  901. // will increase if using symbols, because string comparisons has a clear cost.
  902. //
  903. // Values:
  904. // - 0: default: library uses best judgement
  905. // - 1: use symbols
  906. // - 2: do not use symbols
  907. AsSymbols uint8
  908. // AsSymbols: may later on introduce more options ...
  909. // - m: map keys
  910. // - s: struct fields
  911. // - n: none
  912. // - a: all: same as m, s, ...
  913. _ [1]uint64 // padding (cache-aligned)
  914. }
  915. // Name returns the name of the handle: binc
  916. func (h *BincHandle) Name() string { return "binc" }
  917. // SetBytesExt sets an extension
  918. func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  919. return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
  920. }
  921. func (h *BincHandle) newEncDriver(e *Encoder) encDriver {
  922. return &bincEncDriver{e: e, h: h, w: e.w}
  923. }
  924. func (h *BincHandle) newDecDriver(d *Decoder) decDriver {
  925. return &bincDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  926. }
  927. func (e *bincEncDriver) reset() {
  928. e.w = e.e.w
  929. e.s = 0
  930. e.c = 0
  931. e.m = nil
  932. }
  933. func (d *bincDecDriver) reset() {
  934. d.r, d.br = d.d.r, d.d.bytes
  935. d.s = nil
  936. d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0
  937. }
  938. // var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  939. // EncodeTime encodes a time.Time as a []byte, including
  940. // information on the instant in time and UTC offset.
  941. //
  942. // Format Description
  943. //
  944. // A timestamp is composed of 3 components:
  945. //
  946. // - secs: signed integer representing seconds since unix epoch
  947. // - nsces: unsigned integer representing fractional seconds as a
  948. // nanosecond offset within secs, in the range 0 <= nsecs < 1e9
  949. // - tz: signed integer representing timezone offset in minutes east of UTC,
  950. // and a dst (daylight savings time) flag
  951. //
  952. // When encoding a timestamp, the first byte is the descriptor, which
  953. // defines which components are encoded and how many bytes are used to
  954. // encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
  955. // is not encoded in the byte array explicitly*.
  956. //
  957. // Descriptor 8 bits are of the form `A B C DDD EE`:
  958. // A: Is secs component encoded? 1 = true
  959. // B: Is nsecs component encoded? 1 = true
  960. // C: Is tz component encoded? 1 = true
  961. // DDD: Number of extra bytes for secs (range 0-7).
  962. // If A = 1, secs encoded in DDD+1 bytes.
  963. // If A = 0, secs is not encoded, and is assumed to be 0.
  964. // If A = 1, then we need at least 1 byte to encode secs.
  965. // DDD says the number of extra bytes beyond that 1.
  966. // E.g. if DDD=0, then secs is represented in 1 byte.
  967. // if DDD=2, then secs is represented in 3 bytes.
  968. // EE: Number of extra bytes for nsecs (range 0-3).
  969. // If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
  970. //
  971. // Following the descriptor bytes, subsequent bytes are:
  972. //
  973. // secs component encoded in `DDD + 1` bytes (if A == 1)
  974. // nsecs component encoded in `EE + 1` bytes (if B == 1)
  975. // tz component encoded in 2 bytes (if C == 1)
  976. //
  977. // secs and nsecs components are integers encoded in a BigEndian
  978. // 2-complement encoding format.
  979. //
  980. // tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
  981. // Least significant bit 0 are described below:
  982. //
  983. // Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
  984. // Bit 15 = have\_dst: set to 1 if we set the dst flag.
  985. // Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
  986. // Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
  987. //
  988. func bincEncodeTime(t time.Time) []byte {
  989. //t := rv.Interface().(time.Time)
  990. tsecs, tnsecs := t.Unix(), t.Nanosecond()
  991. var (
  992. bd byte
  993. btmp [8]byte
  994. bs [16]byte
  995. i int = 1
  996. )
  997. l := t.Location()
  998. if l == time.UTC {
  999. l = nil
  1000. }
  1001. if tsecs != 0 {
  1002. bd = bd | 0x80
  1003. bigen.PutUint64(btmp[:], uint64(tsecs))
  1004. f := pruneSignExt(btmp[:], tsecs >= 0)
  1005. bd = bd | (byte(7-f) << 2)
  1006. copy(bs[i:], btmp[f:])
  1007. i = i + (8 - f)
  1008. }
  1009. if tnsecs != 0 {
  1010. bd = bd | 0x40
  1011. bigen.PutUint32(btmp[:4], uint32(tnsecs))
  1012. f := pruneSignExt(btmp[:4], true)
  1013. bd = bd | byte(3-f)
  1014. copy(bs[i:], btmp[f:4])
  1015. i = i + (4 - f)
  1016. }
  1017. if l != nil {
  1018. bd = bd | 0x20
  1019. // Note that Go Libs do not give access to dst flag.
  1020. _, zoneOffset := t.Zone()
  1021. //zoneName, zoneOffset := t.Zone()
  1022. zoneOffset /= 60
  1023. z := uint16(zoneOffset)
  1024. bigen.PutUint16(btmp[:2], z)
  1025. // clear dst flags
  1026. bs[i] = btmp[0] & 0x3f
  1027. bs[i+1] = btmp[1]
  1028. i = i + 2
  1029. }
  1030. bs[0] = bd
  1031. return bs[0:i]
  1032. }
  1033. // bincDecodeTime decodes a []byte into a time.Time.
  1034. func bincDecodeTime(bs []byte) (tt time.Time, err error) {
  1035. bd := bs[0]
  1036. var (
  1037. tsec int64
  1038. tnsec uint32
  1039. tz uint16
  1040. i byte = 1
  1041. i2 byte
  1042. n byte
  1043. )
  1044. if bd&(1<<7) != 0 {
  1045. var btmp [8]byte
  1046. n = ((bd >> 2) & 0x7) + 1
  1047. i2 = i + n
  1048. copy(btmp[8-n:], bs[i:i2])
  1049. //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
  1050. if bs[i]&(1<<7) != 0 {
  1051. copy(btmp[0:8-n], bsAll0xff)
  1052. //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
  1053. }
  1054. i = i2
  1055. tsec = int64(bigen.Uint64(btmp[:]))
  1056. }
  1057. if bd&(1<<6) != 0 {
  1058. var btmp [4]byte
  1059. n = (bd & 0x3) + 1
  1060. i2 = i + n
  1061. copy(btmp[4-n:], bs[i:i2])
  1062. i = i2
  1063. tnsec = bigen.Uint32(btmp[:])
  1064. }
  1065. if bd&(1<<5) == 0 {
  1066. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1067. return
  1068. }
  1069. // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
  1070. // However, we need name here, so it can be shown when time is printf.d.
  1071. // Zone name is in form: UTC-08:00.
  1072. // Note that Go Libs do not give access to dst flag, so we ignore dst bits
  1073. i2 = i + 2
  1074. tz = bigen.Uint16(bs[i:i2])
  1075. // i = i2
  1076. // sign extend sign bit into top 2 MSB (which were dst bits):
  1077. if tz&(1<<13) == 0 { // positive
  1078. tz = tz & 0x3fff //clear 2 MSBs: dst bits
  1079. } else { // negative
  1080. tz = tz | 0xc000 //set 2 MSBs: dst bits
  1081. }
  1082. tzint := int16(tz)
  1083. if tzint == 0 {
  1084. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1085. } else {
  1086. // For Go Time, do not use a descriptive timezone.
  1087. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  1088. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  1089. // var zoneName = timeLocUTCName(tzint)
  1090. tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
  1091. }
  1092. return
  1093. }
  1094. var _ decDriver = (*bincDecDriver)(nil)
  1095. var _ encDriver = (*bincEncDriver)(nil)