binc.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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(v interface{}, xtag uint64, ext Ext) {
  198. var bs []byte
  199. var bufp bytesBufPooler
  200. if ext == SelfExt {
  201. bs = bufp.get(1024)[:0]
  202. e.e.sideEncode(v, &bs)
  203. } else {
  204. bs = ext.WriteExt(v)
  205. }
  206. if bs == nil {
  207. e.EncodeNil()
  208. return
  209. }
  210. e.encodeExtPreamble(uint8(xtag), len(bs))
  211. e.w.writeb(bs)
  212. if ext == SelfExt {
  213. bufp.end()
  214. }
  215. }
  216. func (e *bincEncDriver) EncodeRawExt(re *RawExt) {
  217. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  218. e.w.writeb(re.Data)
  219. }
  220. func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
  221. e.encLen(bincVdCustomExt<<4, uint64(length))
  222. e.w.writen1(xtag)
  223. }
  224. func (e *bincEncDriver) WriteArrayStart(length int) {
  225. e.encLen(bincVdArray<<4, uint64(length))
  226. }
  227. func (e *bincEncDriver) WriteMapStart(length int) {
  228. e.encLen(bincVdMap<<4, uint64(length))
  229. }
  230. func (e *bincEncDriver) EncodeSymbol(v string) {
  231. // if WriteSymbolsNoRefs {
  232. // e.encodeString(cUTF8, v)
  233. // return
  234. // }
  235. //symbols only offer benefit when string length > 1.
  236. //This is because strings with length 1 take only 2 bytes to store
  237. //(bd with embedded length, and single byte for string val).
  238. l := len(v)
  239. if l == 0 {
  240. e.encBytesLen(cUTF8, 0)
  241. return
  242. } else if l == 1 {
  243. e.encBytesLen(cUTF8, 1)
  244. e.w.writen1(v[0])
  245. return
  246. }
  247. if e.m == nil {
  248. e.m = pool.mapStrU16.Get().(map[string]uint16)
  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 *decReaderSwitch
  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 [3 * 8]byte // scratch
  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 = pool.mapU16Bytes.Get().(map[uint16][]byte) // make([]bincDecSymbol, 0, 16)
  674. }
  675. if vs&0x4 == 0 {
  676. bs2 = d.s[symbol]
  677. } else {
  678. switch vs & 0x3 {
  679. case 0:
  680. slen = int(d.r.readn1())
  681. case 1:
  682. slen = int(bigen.Uint16(d.r.readx(2)))
  683. case 2:
  684. slen = int(bigen.Uint32(d.r.readx(4)))
  685. case 3:
  686. slen = int(bigen.Uint64(d.r.readx(8)))
  687. }
  688. // since using symbols, do not store any part of
  689. // the parameter bs in the map, as it might be a shared buffer.
  690. // bs2 = decByteSlice(d.r, slen, bs)
  691. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil)
  692. d.s[symbol] = bs2
  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) DecodeStringAsBytes() (s []byte) {
  703. return d.decStringBytes(d.d.b[:], true)
  704. }
  705. func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  706. if d.advanceNil() {
  707. return
  708. }
  709. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  710. if d.vd == bincVdArray {
  711. if zerocopy && len(bs) == 0 {
  712. bs = d.d.b[:]
  713. }
  714. // bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  715. slen := d.ReadArrayStart()
  716. bs = usableByteSlice(bs, slen)
  717. for i := 0; i < slen; i++ {
  718. bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
  719. }
  720. return bs
  721. }
  722. var clen int
  723. if d.vd == bincVdString || d.vd == bincVdByteArray {
  724. clen = d.decLen()
  725. } else {
  726. d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  727. return
  728. }
  729. d.bdRead = false
  730. if zerocopy {
  731. if d.br {
  732. return d.r.readx(uint(clen))
  733. } else if len(bs) == 0 {
  734. bs = d.d.b[:]
  735. }
  736. }
  737. return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs)
  738. }
  739. func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) {
  740. if xtag > 0xff {
  741. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  742. return
  743. }
  744. if d.advanceNil() {
  745. return
  746. }
  747. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  748. realxtag := uint64(realxtag1)
  749. if ext == nil {
  750. re := rv.(*RawExt)
  751. re.Tag = realxtag
  752. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  753. } else if ext == SelfExt {
  754. d.d.sideDecode(rv, xbs)
  755. } else {
  756. ext.ReadExt(rv, xbs)
  757. }
  758. }
  759. func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  760. if d.vd == bincVdCustomExt {
  761. l := d.decLen()
  762. xtag = d.r.readn1()
  763. if verifyTag && xtag != tag {
  764. d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag)
  765. return
  766. }
  767. if d.br {
  768. xbs = d.r.readx(uint(l))
  769. } else {
  770. xbs = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:])
  771. }
  772. } else if d.vd == bincVdByteArray {
  773. xbs = d.DecodeBytes(nil, true)
  774. } else {
  775. d.d.errorf("ext - expecting extensions or byte array - %s %x-%x/%s",
  776. msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  777. return
  778. }
  779. d.bdRead = false
  780. return
  781. }
  782. func (d *bincDecDriver) DecodeNaked() {
  783. if !d.bdRead {
  784. d.readNextBd()
  785. }
  786. d.fnil = false
  787. n := d.d.naked()
  788. var decodeFurther bool
  789. switch d.vd {
  790. case bincVdSpecial:
  791. switch d.vs {
  792. case bincSpNil:
  793. n.v = valueTypeNil
  794. d.fnil = true
  795. case bincSpFalse:
  796. n.v = valueTypeBool
  797. n.b = false
  798. case bincSpTrue:
  799. n.v = valueTypeBool
  800. n.b = true
  801. case bincSpNan:
  802. n.v = valueTypeFloat
  803. n.f = math.NaN()
  804. case bincSpPosInf:
  805. n.v = valueTypeFloat
  806. n.f = math.Inf(1)
  807. case bincSpNegInf:
  808. n.v = valueTypeFloat
  809. n.f = math.Inf(-1)
  810. case bincSpZeroFloat:
  811. n.v = valueTypeFloat
  812. n.f = float64(0)
  813. case bincSpZero:
  814. n.v = valueTypeUint
  815. n.u = uint64(0) // int8(0)
  816. case bincSpNegOne:
  817. n.v = valueTypeInt
  818. n.i = int64(-1) // int8(-1)
  819. default:
  820. d.d.errorf("cannot infer value - unrecognized special value from descriptor %x-%x/%s",
  821. d.vd, d.vs, bincdesc(d.vd, d.vs))
  822. }
  823. case bincVdSmallInt:
  824. n.v = valueTypeUint
  825. n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
  826. case bincVdPosInt:
  827. n.v = valueTypeUint
  828. n.u = d.decUint()
  829. case bincVdNegInt:
  830. n.v = valueTypeInt
  831. n.i = -(int64(d.decUint()))
  832. case bincVdFloat:
  833. n.v = valueTypeFloat
  834. n.f = d.decFloat()
  835. case bincVdSymbol:
  836. n.v = valueTypeSymbol
  837. n.s = string(d.DecodeStringAsBytes())
  838. case bincVdString:
  839. n.v = valueTypeString
  840. n.s = string(d.DecodeStringAsBytes())
  841. case bincVdByteArray:
  842. decNakedReadRawBytes(d, d.d, n, d.h.RawToString)
  843. case bincVdTimestamp:
  844. n.v = valueTypeTime
  845. tt, err := bincDecodeTime(d.r.readx(uint(d.vs)))
  846. if err != nil {
  847. panic(err)
  848. }
  849. n.t = tt
  850. case bincVdCustomExt:
  851. n.v = valueTypeExt
  852. l := d.decLen()
  853. n.u = uint64(d.r.readn1())
  854. if d.br {
  855. n.l = d.r.readx(uint(l))
  856. } else {
  857. n.l = decByteSlice(d.r, l, d.d.h.MaxInitLen, d.d.b[:])
  858. }
  859. case bincVdArray:
  860. n.v = valueTypeArray
  861. decodeFurther = true
  862. case bincVdMap:
  863. n.v = valueTypeMap
  864. decodeFurther = true
  865. default:
  866. d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
  867. }
  868. if !decodeFurther {
  869. d.bdRead = false
  870. }
  871. if n.v == valueTypeUint && d.h.SignedInteger {
  872. n.v = valueTypeInt
  873. n.i = int64(n.u)
  874. }
  875. }
  876. //------------------------------------
  877. //BincHandle is a Handle for the Binc Schema-Free Encoding Format
  878. //defined at https://github.com/ugorji/binc .
  879. //
  880. //BincHandle currently supports all Binc features with the following EXCEPTIONS:
  881. // - only integers up to 64 bits of precision are supported.
  882. // big integers are unsupported.
  883. // - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
  884. // extended precision and decimal IEEE 754 floats are unsupported.
  885. // - Only UTF-8 strings supported.
  886. // Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
  887. //
  888. //Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
  889. type BincHandle struct {
  890. BasicHandle
  891. binaryEncodingType
  892. noElemSeparators
  893. // AsSymbols defines what should be encoded as symbols.
  894. //
  895. // Encoding as symbols can reduce the encoded size significantly.
  896. //
  897. // However, during decoding, each string to be encoded as a symbol must
  898. // be checked to see if it has been seen before. Consequently, encoding time
  899. // will increase if using symbols, because string comparisons has a clear cost.
  900. //
  901. // Values:
  902. // - 0: default: library uses best judgement
  903. // - 1: use symbols
  904. // - 2: do not use symbols
  905. AsSymbols uint8
  906. // AsSymbols: may later on introduce more options ...
  907. // - m: map keys
  908. // - s: struct fields
  909. // - n: none
  910. // - a: all: same as m, s, ...
  911. _ [7]uint64 // padding (cache-aligned)
  912. }
  913. // Name returns the name of the handle: binc
  914. func (h *BincHandle) Name() string { return "binc" }
  915. // SetBytesExt sets an extension
  916. func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  917. return h.SetExt(rt, tag, makeExt(ext))
  918. }
  919. func (h *BincHandle) newEncDriver(e *Encoder) encDriver {
  920. return &bincEncDriver{e: e, h: h, w: e.w()}
  921. }
  922. func (h *BincHandle) newDecDriver(d *Decoder) decDriver {
  923. return &bincDecDriver{d: d, h: h, r: d.r(), br: d.bytes}
  924. }
  925. func (e *bincEncDriver) reset() {
  926. e.w = e.e.w()
  927. e.s = 0
  928. e.m = nil
  929. }
  930. func (e *bincEncDriver) atEndOfEncode() {
  931. if e.m != nil {
  932. for k := range e.m {
  933. delete(e.m, k)
  934. }
  935. pool.mapStrU16.Put(e.m)
  936. e.m = nil
  937. }
  938. }
  939. func (d *bincDecDriver) reset() {
  940. d.r, d.br = d.d.r(), d.d.bytes
  941. d.s = nil
  942. d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0
  943. d.fnil = false
  944. }
  945. func (d *bincDecDriver) atEndOfDecode() {
  946. if d.s != nil {
  947. for k := range d.s {
  948. delete(d.s, k)
  949. }
  950. pool.mapU16Bytes.Put(d.s)
  951. d.s = nil
  952. }
  953. }
  954. // var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
  955. // EncodeTime encodes a time.Time as a []byte, including
  956. // information on the instant in time and UTC offset.
  957. //
  958. // Format Description
  959. //
  960. // A timestamp is composed of 3 components:
  961. //
  962. // - secs: signed integer representing seconds since unix epoch
  963. // - nsces: unsigned integer representing fractional seconds as a
  964. // nanosecond offset within secs, in the range 0 <= nsecs < 1e9
  965. // - tz: signed integer representing timezone offset in minutes east of UTC,
  966. // and a dst (daylight savings time) flag
  967. //
  968. // When encoding a timestamp, the first byte is the descriptor, which
  969. // defines which components are encoded and how many bytes are used to
  970. // encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
  971. // is not encoded in the byte array explicitly*.
  972. //
  973. // Descriptor 8 bits are of the form `A B C DDD EE`:
  974. // A: Is secs component encoded? 1 = true
  975. // B: Is nsecs component encoded? 1 = true
  976. // C: Is tz component encoded? 1 = true
  977. // DDD: Number of extra bytes for secs (range 0-7).
  978. // If A = 1, secs encoded in DDD+1 bytes.
  979. // If A = 0, secs is not encoded, and is assumed to be 0.
  980. // If A = 1, then we need at least 1 byte to encode secs.
  981. // DDD says the number of extra bytes beyond that 1.
  982. // E.g. if DDD=0, then secs is represented in 1 byte.
  983. // if DDD=2, then secs is represented in 3 bytes.
  984. // EE: Number of extra bytes for nsecs (range 0-3).
  985. // If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
  986. //
  987. // Following the descriptor bytes, subsequent bytes are:
  988. //
  989. // secs component encoded in `DDD + 1` bytes (if A == 1)
  990. // nsecs component encoded in `EE + 1` bytes (if B == 1)
  991. // tz component encoded in 2 bytes (if C == 1)
  992. //
  993. // secs and nsecs components are integers encoded in a BigEndian
  994. // 2-complement encoding format.
  995. //
  996. // tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
  997. // Least significant bit 0 are described below:
  998. //
  999. // Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
  1000. // Bit 15 = have\_dst: set to 1 if we set the dst flag.
  1001. // Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
  1002. // Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
  1003. //
  1004. func bincEncodeTime(t time.Time) []byte {
  1005. //t := rv.Interface().(time.Time)
  1006. tsecs, tnsecs := t.Unix(), t.Nanosecond()
  1007. var (
  1008. bd byte
  1009. btmp [8]byte
  1010. bs [16]byte
  1011. i int = 1
  1012. )
  1013. l := t.Location()
  1014. if l == time.UTC {
  1015. l = nil
  1016. }
  1017. if tsecs != 0 {
  1018. bd = bd | 0x80
  1019. bigen.PutUint64(btmp[:], uint64(tsecs))
  1020. f := pruneSignExt(btmp[:], tsecs >= 0)
  1021. bd = bd | (byte(7-f) << 2)
  1022. copy(bs[i:], btmp[f:])
  1023. i = i + (8 - f)
  1024. }
  1025. if tnsecs != 0 {
  1026. bd = bd | 0x40
  1027. bigen.PutUint32(btmp[:4], uint32(tnsecs))
  1028. f := pruneSignExt(btmp[:4], true)
  1029. bd = bd | byte(3-f)
  1030. copy(bs[i:], btmp[f:4])
  1031. i = i + (4 - f)
  1032. }
  1033. if l != nil {
  1034. bd = bd | 0x20
  1035. // Note that Go Libs do not give access to dst flag.
  1036. _, zoneOffset := t.Zone()
  1037. //zoneName, zoneOffset := t.Zone()
  1038. zoneOffset /= 60
  1039. z := uint16(zoneOffset)
  1040. bigen.PutUint16(btmp[:2], z)
  1041. // clear dst flags
  1042. bs[i] = btmp[0] & 0x3f
  1043. bs[i+1] = btmp[1]
  1044. i = i + 2
  1045. }
  1046. bs[0] = bd
  1047. return bs[0:i]
  1048. }
  1049. // bincDecodeTime decodes a []byte into a time.Time.
  1050. func bincDecodeTime(bs []byte) (tt time.Time, err error) {
  1051. bd := bs[0]
  1052. var (
  1053. tsec int64
  1054. tnsec uint32
  1055. tz uint16
  1056. i byte = 1
  1057. i2 byte
  1058. n byte
  1059. )
  1060. if bd&(1<<7) != 0 {
  1061. var btmp [8]byte
  1062. n = ((bd >> 2) & 0x7) + 1
  1063. i2 = i + n
  1064. copy(btmp[8-n:], bs[i:i2])
  1065. //if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
  1066. if bs[i]&(1<<7) != 0 {
  1067. copy(btmp[0:8-n], bsAll0xff)
  1068. //for j,k := byte(0), 8-n; j < k; j++ { btmp[j] = 0xff }
  1069. }
  1070. i = i2
  1071. tsec = int64(bigen.Uint64(btmp[:]))
  1072. }
  1073. if bd&(1<<6) != 0 {
  1074. var btmp [4]byte
  1075. n = (bd & 0x3) + 1
  1076. i2 = i + n
  1077. copy(btmp[4-n:], bs[i:i2])
  1078. i = i2
  1079. tnsec = bigen.Uint32(btmp[:])
  1080. }
  1081. if bd&(1<<5) == 0 {
  1082. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1083. return
  1084. }
  1085. // In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
  1086. // However, we need name here, so it can be shown when time is printf.d.
  1087. // Zone name is in form: UTC-08:00.
  1088. // Note that Go Libs do not give access to dst flag, so we ignore dst bits
  1089. i2 = i + 2
  1090. tz = bigen.Uint16(bs[i:i2])
  1091. // i = i2
  1092. // sign extend sign bit into top 2 MSB (which were dst bits):
  1093. if tz&(1<<13) == 0 { // positive
  1094. tz = tz & 0x3fff //clear 2 MSBs: dst bits
  1095. } else { // negative
  1096. tz = tz | 0xc000 //set 2 MSBs: dst bits
  1097. }
  1098. tzint := int16(tz)
  1099. if tzint == 0 {
  1100. tt = time.Unix(tsec, int64(tnsec)).UTC()
  1101. } else {
  1102. // For Go Time, do not use a descriptive timezone.
  1103. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  1104. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  1105. // var zoneName = timeLocUTCName(tzint)
  1106. tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
  1107. }
  1108. return
  1109. }
  1110. var _ decDriver = (*bincDecDriver)(nil)
  1111. var _ encDriver = (*bincEncDriver)(nil)