binc.go 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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. "time"
  7. )
  8. const bincDoPrune = true // No longer needed. Needed before as C lib did not support pruning.
  9. // vd as low 4 bits (there are 16 slots)
  10. const (
  11. bincVdSpecial byte = iota
  12. bincVdPosInt
  13. bincVdNegInt
  14. bincVdFloat
  15. bincVdString
  16. bincVdByteArray
  17. bincVdArray
  18. bincVdMap
  19. bincVdTimestamp
  20. bincVdSmallInt
  21. bincVdUnicodeOther
  22. bincVdSymbol
  23. bincVdDecimal
  24. _ // open slot
  25. _ // open slot
  26. bincVdCustomExt = 0x0f
  27. )
  28. const (
  29. bincSpNil byte = iota
  30. bincSpFalse
  31. bincSpTrue
  32. bincSpNan
  33. bincSpPosInf
  34. bincSpNegInf
  35. bincSpZeroFloat
  36. bincSpZero
  37. bincSpNegOne
  38. )
  39. const (
  40. bincFlBin16 byte = iota
  41. bincFlBin32
  42. _ // bincFlBin32e
  43. bincFlBin64
  44. _ // bincFlBin64e
  45. // others not currently supported
  46. )
  47. func bincdesc(vd, vs byte) string {
  48. switch vd {
  49. case bincVdSpecial:
  50. switch vs {
  51. case bincSpNil:
  52. return "nil"
  53. case bincSpFalse:
  54. return "false"
  55. case bincSpTrue:
  56. return "true"
  57. case bincSpNan, bincSpPosInf, bincSpNegInf, bincSpZeroFloat:
  58. return "float"
  59. case bincSpZero:
  60. return "uint"
  61. case bincSpNegOne:
  62. return "int"
  63. default:
  64. return "unknown"
  65. }
  66. case bincVdSmallInt, bincVdPosInt:
  67. return "uint"
  68. case bincVdNegInt:
  69. return "int"
  70. case bincVdFloat:
  71. return "float"
  72. case bincVdSymbol:
  73. return "string"
  74. case bincVdString:
  75. return "string"
  76. case bincVdByteArray:
  77. return "bytes"
  78. case bincVdTimestamp:
  79. return "time"
  80. case bincVdCustomExt:
  81. return "ext"
  82. case bincVdArray:
  83. return "array"
  84. case bincVdMap:
  85. return "map"
  86. default:
  87. return "unknown"
  88. }
  89. }
  90. type bincEncDriver struct {
  91. noBuiltInTypes
  92. encDriverNoopContainerWriter
  93. e *Encoder
  94. h *BincHandle
  95. w *encWr
  96. m map[string]uint16 // symbols
  97. b [8]byte // scratch, used for encoding numbers - bigendian style
  98. s uint16 // symbols sequencer
  99. // c containerState
  100. // encDriverTrackContainerWriter
  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(v interface{}, xtag uint64, ext Ext) {
  197. var bs []byte
  198. // var bufp bytesBufPooler
  199. if ext == SelfExt {
  200. bs = e.e.blist.get(1024)[:0] // bufp.get(1024)[:0]
  201. e.e.sideEncode(v, &bs)
  202. } else {
  203. bs = ext.WriteExt(v)
  204. }
  205. if bs == nil {
  206. e.EncodeNil()
  207. return
  208. }
  209. e.encodeExtPreamble(uint8(xtag), len(bs))
  210. e.w.writeb(bs)
  211. if ext == SelfExt {
  212. e.e.blist.put(bs) // bufp.end()
  213. }
  214. }
  215. func (e *bincEncDriver) EncodeRawExt(re *RawExt) {
  216. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  217. e.w.writeb(re.Data)
  218. }
  219. func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
  220. e.encLen(bincVdCustomExt<<4, uint64(length))
  221. e.w.writen1(xtag)
  222. }
  223. func (e *bincEncDriver) WriteArrayStart(length int) {
  224. e.encLen(bincVdArray<<4, uint64(length))
  225. }
  226. func (e *bincEncDriver) WriteMapStart(length int) {
  227. e.encLen(bincVdMap<<4, uint64(length))
  228. }
  229. func (e *bincEncDriver) EncodeSymbol(v string) {
  230. // if WriteSymbolsNoRefs {
  231. // e.encodeString(cUTF8, v)
  232. // return
  233. // }
  234. //symbols only offer benefit when string length > 1.
  235. //This is because strings with length 1 take only 2 bytes to store
  236. //(bd with embedded length, and single byte for string val).
  237. l := len(v)
  238. if l == 0 {
  239. e.encBytesLen(cUTF8, 0)
  240. return
  241. } else if l == 1 {
  242. e.encBytesLen(cUTF8, 1)
  243. e.w.writen1(v[0])
  244. return
  245. }
  246. if e.m == nil {
  247. // e.m = pool4mapStrU16.Get().(map[string]uint16)
  248. e.m = make(map[string]uint16, 16)
  249. }
  250. ui, ok := e.m[v]
  251. if ok {
  252. if ui <= math.MaxUint8 {
  253. e.w.writen2(bincVdSymbol<<4, byte(ui))
  254. } else {
  255. e.w.writen1(bincVdSymbol<<4 | 0x8)
  256. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  257. }
  258. } else {
  259. e.s++
  260. ui = e.s
  261. //ui = uint16(atomic.AddUint32(&e.s, 1))
  262. e.m[v] = ui
  263. var lenprec uint8
  264. if l <= math.MaxUint8 {
  265. // lenprec = 0
  266. } else if l <= math.MaxUint16 {
  267. lenprec = 1
  268. } else if int64(l) <= math.MaxUint32 {
  269. lenprec = 2
  270. } else {
  271. lenprec = 3
  272. }
  273. if ui <= math.MaxUint8 {
  274. e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
  275. } else {
  276. e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
  277. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  278. }
  279. if lenprec == 0 {
  280. e.w.writen1(byte(l))
  281. } else if lenprec == 1 {
  282. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l))
  283. } else if lenprec == 2 {
  284. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l))
  285. } else {
  286. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l))
  287. }
  288. e.w.writestr(v)
  289. }
  290. }
  291. func (e *bincEncDriver) EncodeStringEnc(c charEncoding, v string) {
  292. if e.e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 0 || e.h.AsSymbols == 1) {
  293. e.EncodeSymbol(v)
  294. return
  295. }
  296. l := uint64(len(v))
  297. e.encLen(bincVdString<<4, l) // e.encBytesLen(c, l)
  298. if l > 0 {
  299. e.w.writestr(v)
  300. }
  301. }
  302. func (e *bincEncDriver) EncodeStringBytesRaw(v []byte) {
  303. if v == nil {
  304. e.EncodeNil()
  305. return
  306. }
  307. l := uint64(len(v))
  308. e.encLen(bincVdByteArray<<4, l) // e.encBytesLen(c, l)
  309. if l > 0 {
  310. e.w.writeb(v)
  311. }
  312. }
  313. func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
  314. //TODO: support bincUnicodeOther (for now, just use string or bytearray)
  315. if c == cRAW {
  316. e.encLen(bincVdByteArray<<4, length)
  317. } else {
  318. e.encLen(bincVdString<<4, length)
  319. }
  320. }
  321. func (e *bincEncDriver) encLen(bd byte, l uint64) {
  322. if l < 12 {
  323. e.w.writen1(bd | uint8(l+4))
  324. } else {
  325. e.encLenNumber(bd, l)
  326. }
  327. }
  328. func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
  329. if v <= math.MaxUint8 {
  330. e.w.writen2(bd, byte(v))
  331. } else if v <= math.MaxUint16 {
  332. e.w.writen1(bd | 0x01)
  333. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v))
  334. } else if v <= math.MaxUint32 {
  335. e.w.writen1(bd | 0x02)
  336. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v))
  337. } else {
  338. e.w.writen1(bd | 0x03)
  339. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v))
  340. }
  341. }
  342. //------------------------------------
  343. // type bincDecSymbol struct {
  344. // s string
  345. // b []byte
  346. // // i uint16
  347. // }
  348. type bincDecDriver struct {
  349. decDriverNoopContainerReader
  350. noBuiltInTypes
  351. d *Decoder
  352. h *BincHandle
  353. r *decRd
  354. br bool // bytes reader
  355. bdRead bool
  356. bd byte
  357. vd byte
  358. vs byte
  359. fnil bool
  360. // _ [3]byte // padding
  361. // linear searching on this slice is ok,
  362. // because we typically expect < 32 symbols in each stream.
  363. s map[uint16][]byte // []bincDecSymbol
  364. // noStreamingCodec
  365. // decNoSeparator
  366. b [8]byte // scratch for decoding numbers - big endian style
  367. }
  368. func (d *bincDecDriver) readNextBd() {
  369. d.bd = d.r.readn1()
  370. d.vd = d.bd >> 4
  371. d.vs = d.bd & 0x0f
  372. d.bdRead = true
  373. }
  374. func (d *bincDecDriver) uncacheRead() {
  375. if d.bdRead {
  376. d.r.unreadn1()
  377. d.bdRead = false
  378. }
  379. }
  380. func (d *bincDecDriver) advanceNil() (null bool) {
  381. d.fnil = false
  382. if !d.bdRead {
  383. d.readNextBd()
  384. }
  385. if d.bd == bincVdSpecial<<4|bincSpNil {
  386. d.bdRead = false
  387. d.fnil = true
  388. null = true
  389. }
  390. return
  391. }
  392. func (d *bincDecDriver) Nil() bool {
  393. return d.fnil
  394. }
  395. func (d *bincDecDriver) TryNil() bool {
  396. return d.advanceNil()
  397. }
  398. func (d *bincDecDriver) ContainerType() (vt valueType) {
  399. if !d.bdRead {
  400. d.readNextBd()
  401. }
  402. d.fnil = false
  403. // if d.vd == bincVdSpecial && d.vs == bincSpNil {
  404. if d.bd == bincVdSpecial<<4|bincSpNil {
  405. d.bdRead = false
  406. d.fnil = true
  407. return valueTypeNil
  408. } else if d.vd == bincVdByteArray {
  409. return valueTypeBytes
  410. } else if d.vd == bincVdString {
  411. return valueTypeString
  412. } else if d.vd == bincVdArray {
  413. return valueTypeArray
  414. } else if d.vd == bincVdMap {
  415. return valueTypeMap
  416. }
  417. // else {
  418. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  419. // }
  420. return valueTypeUnset
  421. }
  422. func (d *bincDecDriver) DecodeTime() (t time.Time) {
  423. if d.advanceNil() {
  424. return
  425. }
  426. if d.vd != bincVdTimestamp {
  427. d.d.errorf("cannot decode time - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  428. return
  429. }
  430. t, err := bincDecodeTime(d.r.readx(uint(d.vs)))
  431. if err != nil {
  432. panic(err)
  433. }
  434. d.bdRead = false
  435. return
  436. }
  437. func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) {
  438. if vs&0x8 == 0 {
  439. d.r.readb(d.b[0:defaultLen])
  440. } else {
  441. l := d.r.readn1()
  442. if l > 8 {
  443. d.d.errorf("cannot read float - at most 8 bytes used to represent float - received %v bytes", l)
  444. return
  445. }
  446. for i := l; i < 8; i++ {
  447. d.b[i] = 0
  448. }
  449. d.r.readb(d.b[0:l])
  450. }
  451. }
  452. func (d *bincDecDriver) decFloat() (f float64) {
  453. //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; }
  454. if x := d.vs & 0x7; x == bincFlBin32 {
  455. d.decFloatPre(d.vs, 4)
  456. f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4])))
  457. } else if x == bincFlBin64 {
  458. d.decFloatPre(d.vs, 8)
  459. f = math.Float64frombits(bigen.Uint64(d.b[0:8]))
  460. } else {
  461. d.d.errorf("read float - only float32 and float64 are supported - %s %x-%x/%s",
  462. msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  463. return
  464. }
  465. return
  466. }
  467. func (d *bincDecDriver) decUint() (v uint64) {
  468. // need to inline the code (interface conversion and type assertion expensive)
  469. switch d.vs {
  470. case 0:
  471. v = uint64(d.r.readn1())
  472. case 1:
  473. d.r.readb(d.b[6:8])
  474. v = uint64(bigen.Uint16(d.b[6:8]))
  475. case 2:
  476. d.b[4] = 0
  477. d.r.readb(d.b[5:8])
  478. v = uint64(bigen.Uint32(d.b[4:8]))
  479. case 3:
  480. d.r.readb(d.b[4:8])
  481. v = uint64(bigen.Uint32(d.b[4:8]))
  482. case 4, 5, 6:
  483. lim := 7 - d.vs
  484. d.r.readb(d.b[lim:8])
  485. for i := uint8(0); i < lim; i++ {
  486. d.b[i] = 0
  487. }
  488. v = uint64(bigen.Uint64(d.b[:8]))
  489. case 7:
  490. d.r.readb(d.b[:8])
  491. v = uint64(bigen.Uint64(d.b[:8]))
  492. default:
  493. d.d.errorf("unsigned integers with greater than 64 bits of precision not supported")
  494. return
  495. }
  496. return
  497. }
  498. func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) {
  499. vd, vs := d.vd, d.vs
  500. if vd == bincVdPosInt {
  501. ui = d.decUint()
  502. } else if vd == bincVdNegInt {
  503. ui = d.decUint()
  504. neg = true
  505. } else if vd == bincVdSmallInt {
  506. ui = uint64(d.vs) + 1
  507. } else if vd == bincVdSpecial {
  508. if vs == bincSpZero {
  509. //i = 0
  510. } else if vs == bincSpNegOne {
  511. neg = true
  512. ui = 1
  513. } else {
  514. d.d.errorf("integer decode fails - invalid special value from descriptor %x-%x/%s",
  515. d.vd, d.vs, bincdesc(d.vd, d.vs))
  516. return
  517. }
  518. } else {
  519. d.d.errorf("integer can only be decoded from int/uint. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
  520. return
  521. }
  522. return
  523. }
  524. func (d *bincDecDriver) DecodeInt64() (i int64) {
  525. if d.advanceNil() {
  526. return
  527. }
  528. ui, neg := d.decCheckInteger()
  529. i = chkOvf.SignedIntV(ui)
  530. if neg {
  531. i = -i
  532. }
  533. d.bdRead = false
  534. return
  535. }
  536. func (d *bincDecDriver) DecodeUint64() (ui uint64) {
  537. if d.advanceNil() {
  538. return
  539. }
  540. ui, neg := d.decCheckInteger()
  541. if neg {
  542. d.d.errorf("assigning negative signed value to unsigned integer type")
  543. return
  544. }
  545. d.bdRead = false
  546. return
  547. }
  548. func (d *bincDecDriver) DecodeFloat64() (f float64) {
  549. if d.advanceNil() {
  550. return
  551. }
  552. vd, vs := d.vd, d.vs
  553. if vd == bincVdSpecial {
  554. d.bdRead = false
  555. if vs == bincSpNan {
  556. return math.NaN()
  557. } else if vs == bincSpPosInf {
  558. return math.Inf(1)
  559. } else if vs == bincSpZeroFloat || vs == bincSpZero {
  560. return
  561. } else if vs == bincSpNegInf {
  562. return math.Inf(-1)
  563. } else {
  564. d.d.errorf("float - invalid special value from descriptor %x-%x/%s",
  565. d.vd, d.vs, bincdesc(d.vd, d.vs))
  566. return
  567. }
  568. } else if vd == bincVdFloat {
  569. f = d.decFloat()
  570. } else {
  571. f = float64(d.DecodeInt64())
  572. }
  573. d.bdRead = false
  574. return
  575. }
  576. // bool can be decoded from bool only (single byte).
  577. func (d *bincDecDriver) DecodeBool() (b bool) {
  578. if d.advanceNil() {
  579. return
  580. }
  581. if d.bd == (bincVdSpecial | bincSpFalse) {
  582. // b = false
  583. } else if d.bd == (bincVdSpecial | bincSpTrue) {
  584. b = true
  585. } else {
  586. d.d.errorf("bool - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  587. return
  588. }
  589. d.bdRead = false
  590. return
  591. }
  592. func (d *bincDecDriver) ReadMapStart() (length int) {
  593. if d.advanceNil() {
  594. return decContainerLenNil
  595. }
  596. if d.vd != bincVdMap {
  597. d.d.errorf("map - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  598. return
  599. }
  600. length = d.decLen()
  601. d.bdRead = false
  602. return
  603. }
  604. func (d *bincDecDriver) ReadArrayStart() (length int) {
  605. if d.advanceNil() {
  606. return decContainerLenNil
  607. }
  608. if d.vd != bincVdArray {
  609. d.d.errorf("array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  610. return
  611. }
  612. length = d.decLen()
  613. d.bdRead = false
  614. return
  615. }
  616. func (d *bincDecDriver) decLen() int {
  617. if d.vs > 3 {
  618. return int(d.vs - 4)
  619. }
  620. return int(d.decLenNumber())
  621. }
  622. func (d *bincDecDriver) decLenNumber() (v uint64) {
  623. if x := d.vs; x == 0 {
  624. v = uint64(d.r.readn1())
  625. } else if x == 1 {
  626. d.r.readb(d.b[6:8])
  627. v = uint64(bigen.Uint16(d.b[6:8]))
  628. } else if x == 2 {
  629. d.r.readb(d.b[4:8])
  630. v = uint64(bigen.Uint32(d.b[4:8]))
  631. } else {
  632. d.r.readb(d.b[:8])
  633. v = bigen.Uint64(d.b[:8])
  634. }
  635. return
  636. }
  637. func (d *bincDecDriver) decStringBytes(bs []byte, zerocopy bool) (bs2 []byte) {
  638. if d.advanceNil() {
  639. return
  640. }
  641. var slen = -1
  642. // var ok bool
  643. switch d.vd {
  644. case bincVdString, bincVdByteArray:
  645. slen = d.decLen()
  646. if zerocopy {
  647. if d.br {
  648. bs2 = d.r.readx(uint(slen))
  649. } else if len(bs) == 0 {
  650. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.d.b[:])
  651. } else {
  652. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  653. }
  654. } else {
  655. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  656. }
  657. case bincVdSymbol:
  658. // zerocopy doesn't apply for symbols,
  659. // as the values must be stored in a table for later use.
  660. //
  661. //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision,
  662. //extract symbol
  663. //if containsStringVal, read it and put in map
  664. //else look in map for string value
  665. var symbol uint16
  666. vs := d.vs
  667. if vs&0x8 == 0 {
  668. symbol = uint16(d.r.readn1())
  669. } else {
  670. symbol = uint16(bigen.Uint16(d.r.readx(2)))
  671. }
  672. if d.s == nil {
  673. // d.s = pool4mapU16Bytes.Get().(map[uint16][]byte) // make([]bincDecSymbol, 0, 16)
  674. d.s = make(map[uint16][]byte, 16)
  675. }
  676. if vs&0x4 == 0 {
  677. bs2 = d.s[symbol]
  678. } else {
  679. switch vs & 0x3 {
  680. case 0:
  681. slen = int(d.r.readn1())
  682. case 1:
  683. slen = int(bigen.Uint16(d.r.readx(2)))
  684. case 2:
  685. slen = int(bigen.Uint32(d.r.readx(4)))
  686. case 3:
  687. slen = int(bigen.Uint64(d.r.readx(8)))
  688. }
  689. // since using symbols, do not store any part of
  690. // the parameter bs in the map, as it might be a shared buffer.
  691. // bs2 = decByteSlice(d.r, slen, bs)
  692. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil)
  693. d.s[symbol] = bs2
  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) DecodeStringAsBytes() (s []byte) {
  704. return d.decStringBytes(d.d.b[:], true)
  705. }
  706. func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  707. if d.advanceNil() {
  708. return
  709. }
  710. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  711. if d.vd == bincVdArray {
  712. if zerocopy && len(bs) == 0 {
  713. bs = d.d.b[:]
  714. }
  715. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  716. slen := d.ReadArrayStart()
  717. bs = usableByteSlice(bs, slen)
  718. for i := 0; i < slen; i++ {
  719. bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
  720. }
  721. return bs
  722. }
  723. var clen int
  724. if d.vd == bincVdString || d.vd == bincVdByteArray {
  725. clen = d.decLen()
  726. } else {
  727. d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  728. return
  729. }
  730. d.bdRead = false
  731. if zerocopy {
  732. if d.br {
  733. return d.r.readx(uint(clen))
  734. } else if len(bs) == 0 {
  735. bs = d.d.b[:]
  736. }
  737. }
  738. return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs)
  739. }
  740. func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) {
  741. if xtag > 0xff {
  742. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  743. return
  744. }
  745. if d.advanceNil() {
  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 if ext == SelfExt {
  755. d.d.sideDecode(rv, xbs)
  756. } else {
  757. ext.ReadExt(rv, xbs)
  758. }
  759. }
  760. func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  761. if d.vd == bincVdCustomExt {
  762. l := d.decLen()
  763. xtag = d.r.readn1()
  764. if verifyTag && xtag != tag {
  765. d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag)
  766. return
  767. }
  768. if d.br {
  769. xbs = d.r.readx(uint(l))
  770. } else {
  771. xbs = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:])
  772. }
  773. } else if d.vd == bincVdByteArray {
  774. xbs = d.DecodeBytes(nil, true)
  775. } else {
  776. d.d.errorf("ext - expecting extensions or byte array - %s %x-%x/%s",
  777. msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  778. return
  779. }
  780. d.bdRead = false
  781. return
  782. }
  783. func (d *bincDecDriver) DecodeNaked() {
  784. if !d.bdRead {
  785. d.readNextBd()
  786. }
  787. d.fnil = false
  788. n := d.d.naked()
  789. var decodeFurther bool
  790. switch d.vd {
  791. case bincVdSpecial:
  792. switch d.vs {
  793. case bincSpNil:
  794. n.v = valueTypeNil
  795. d.fnil = true
  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 = string(d.DecodeStringAsBytes())
  839. case bincVdString:
  840. n.v = valueTypeString
  841. n.s = string(d.DecodeStringAsBytes())
  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. _ [7]uint64 // padding (cache-aligned)
  913. }
  914. // Name returns the name of the handle: binc
  915. func (h *BincHandle) Name() string { return "binc" }
  916. func (h *BincHandle) newEncDriver(e *Encoder) encDriver {
  917. return &bincEncDriver{e: e, h: h, w: e.w()}
  918. }
  919. func (h *BincHandle) newDecDriver(d *Decoder) decDriver {
  920. return &bincDecDriver{d: d, h: h, r: d.r(), br: d.bytes}
  921. }
  922. func (e *bincEncDriver) reset() {
  923. e.w = e.e.w()
  924. e.s = 0
  925. e.m = nil
  926. }
  927. func (e *bincEncDriver) atEndOfEncode() {
  928. if e.m != nil {
  929. for k := range e.m {
  930. delete(e.m, k)
  931. }
  932. // pool4mapStrU16.Put(e.m)
  933. // e.m = nil
  934. }
  935. }
  936. func (d *bincDecDriver) reset() {
  937. d.r, d.br = d.d.r(), d.d.bytes
  938. d.s = nil
  939. d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0
  940. d.fnil = false
  941. }
  942. func (d *bincDecDriver) atEndOfDecode() {
  943. if d.s != nil {
  944. for k := range d.s {
  945. delete(d.s, k)
  946. }
  947. // pool4mapU16Bytes.Put(d.s)
  948. // d.s = nil
  949. }
  950. }
  951. // var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  952. // EncodeTime encodes a time.Time as a []byte, including
  953. // information on the instant in time and UTC offset.
  954. //
  955. // Format Description
  956. //
  957. // A timestamp is composed of 3 components:
  958. //
  959. // - secs: signed integer representing seconds since unix epoch
  960. // - nsces: unsigned integer representing fractional seconds as a
  961. // nanosecond offset within secs, in the range 0 <= nsecs < 1e9
  962. // - tz: signed integer representing timezone offset in minutes east of UTC,
  963. // and a dst (daylight savings time) flag
  964. //
  965. // When encoding a timestamp, the first byte is the descriptor, which
  966. // defines which components are encoded and how many bytes are used to
  967. // encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
  968. // is not encoded in the byte array explicitly*.
  969. //
  970. // Descriptor 8 bits are of the form `A B C DDD EE`:
  971. // A: Is secs component encoded? 1 = true
  972. // B: Is nsecs component encoded? 1 = true
  973. // C: Is tz component encoded? 1 = true
  974. // DDD: Number of extra bytes for secs (range 0-7).
  975. // If A = 1, secs encoded in DDD+1 bytes.
  976. // If A = 0, secs is not encoded, and is assumed to be 0.
  977. // If A = 1, then we need at least 1 byte to encode secs.
  978. // DDD says the number of extra bytes beyond that 1.
  979. // E.g. if DDD=0, then secs is represented in 1 byte.
  980. // if DDD=2, then secs is represented in 3 bytes.
  981. // EE: Number of extra bytes for nsecs (range 0-3).
  982. // If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
  983. //
  984. // Following the descriptor bytes, subsequent bytes are:
  985. //
  986. // secs component encoded in `DDD + 1` bytes (if A == 1)
  987. // nsecs component encoded in `EE + 1` bytes (if B == 1)
  988. // tz component encoded in 2 bytes (if C == 1)
  989. //
  990. // secs and nsecs components are integers encoded in a BigEndian
  991. // 2-complement encoding format.
  992. //
  993. // tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
  994. // Least significant bit 0 are described below:
  995. //
  996. // Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
  997. // Bit 15 = have\_dst: set to 1 if we set the dst flag.
  998. // Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
  999. // Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
  1000. //
  1001. func bincEncodeTime(t time.Time) []byte {
  1002. //t := rv2i(rv).(time.Time)
  1003. tsecs, tnsecs := t.Unix(), t.Nanosecond()
  1004. var (
  1005. bd byte
  1006. btmp [8]byte
  1007. bs [16]byte
  1008. i int = 1
  1009. )
  1010. l := t.Location()
  1011. if l == time.UTC {
  1012. l = nil
  1013. }
  1014. if tsecs != 0 {
  1015. bd = bd | 0x80
  1016. bigen.PutUint64(btmp[:], uint64(tsecs))
  1017. f := pruneSignExt(btmp[:], tsecs >= 0)
  1018. bd = bd | (byte(7-f) << 2)
  1019. copy(bs[i:], btmp[f:])
  1020. i = i + (8 - f)
  1021. }
  1022. if tnsecs != 0 {
  1023. bd = bd | 0x40
  1024. bigen.PutUint32(btmp[:4], uint32(tnsecs))
  1025. f := pruneSignExt(btmp[:4], true)
  1026. bd = bd | byte(3-f)
  1027. copy(bs[i:], btmp[f:4])
  1028. i = i + (4 - f)
  1029. }
  1030. if l != nil {
  1031. bd = bd | 0x20
  1032. // Note that Go Libs do not give access to dst flag.
  1033. _, zoneOffset := t.Zone()
  1034. //zoneName, zoneOffset := t.Zone()
  1035. zoneOffset /= 60
  1036. z := uint16(zoneOffset)
  1037. bigen.PutUint16(btmp[:2], z)
  1038. // clear dst flags
  1039. bs[i] = btmp[0] & 0x3f
  1040. bs[i+1] = btmp[1]
  1041. i = i + 2
  1042. }
  1043. bs[0] = bd
  1044. return bs[0:i]
  1045. }
  1046. // bincDecodeTime decodes a []byte into a time.Time.
  1047. func bincDecodeTime(bs []byte) (tt time.Time, err error) {
  1048. bd := bs[0]
  1049. var (
  1050. tsec int64
  1051. tnsec uint32
  1052. tz uint16
  1053. i byte = 1
  1054. i2 byte
  1055. n byte
  1056. )
  1057. if bd&(1<<7) != 0 {
  1058. var btmp [8]byte
  1059. n = ((bd >> 2) & 0x7) + 1
  1060. i2 = i + n
  1061. copy(btmp[8-n:], bs[i:i2])
  1062. //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
  1063. if bs[i]&(1<<7) != 0 {
  1064. copy(btmp[0:8-n], bsAll0xff)
  1065. //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
  1066. }
  1067. i = i2
  1068. tsec = int64(bigen.Uint64(btmp[:]))
  1069. }
  1070. if bd&(1<<6) != 0 {
  1071. var btmp [4]byte
  1072. n = (bd & 0x3) + 1
  1073. i2 = i + n
  1074. copy(btmp[4-n:], bs[i:i2])
  1075. i = i2
  1076. tnsec = bigen.Uint32(btmp[:])
  1077. }
  1078. if bd&(1<<5) == 0 {
  1079. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1080. return
  1081. }
  1082. // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
  1083. // However, we need name here, so it can be shown when time is printf.d.
  1084. // Zone name is in form: UTC-08:00.
  1085. // Note that Go Libs do not give access to dst flag, so we ignore dst bits
  1086. i2 = i + 2
  1087. tz = bigen.Uint16(bs[i:i2])
  1088. // i = i2
  1089. // sign extend sign bit into top 2 MSB (which were dst bits):
  1090. if tz&(1<<13) == 0 { // positive
  1091. tz = tz & 0x3fff //clear 2 MSBs: dst bits
  1092. } else { // negative
  1093. tz = tz | 0xc000 //set 2 MSBs: dst bits
  1094. }
  1095. tzint := int16(tz)
  1096. if tzint == 0 {
  1097. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1098. } else {
  1099. // For Go Time, do not use a descriptive timezone.
  1100. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  1101. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  1102. // var zoneName = timeLocUTCName(tzint)
  1103. tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
  1104. }
  1105. return
  1106. }
  1107. var _ decDriver = (*bincDecDriver)(nil)
  1108. var _ encDriver = (*bincEncDriver)(nil)