binc.go 28 KB

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