binc.go 29 KB

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