binc.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. // Copyright (c) 2012-2015 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. type bincEncDriver struct {
  49. e *Encoder
  50. w encWriter
  51. m map[string]uint16 // symbols
  52. b [scratchByteArrayLen]byte
  53. s uint16 // symbols sequencer
  54. // encNoSeparator
  55. encDriverNoopContainerWriter
  56. noBuiltInTypes
  57. }
  58. // func (e *bincEncDriver) IsBuiltinType(rt uintptr) bool {
  59. // return rt == timeTypId
  60. // }
  61. func (e *bincEncDriver) EncodeNil() {
  62. e.w.writen1(bincVdSpecial<<4 | bincSpNil)
  63. }
  64. // func (e *bincEncDriver) EncodeBuiltin(rt uintptr, v interface{}) {
  65. // if rt == timeTypId {
  66. // e.EncodeTime(v.(time.Time))
  67. // return
  68. // }
  69. // e.e.errorf("binc error encoding builtin: expect time.Time, received %T", v)
  70. // }
  71. func (e *bincEncDriver) EncodeTime(t time.Time) {
  72. bs := encodeTime(t)
  73. e.w.writen1(bincVdTimestamp<<4 | uint8(len(bs)))
  74. e.w.writeb(bs)
  75. }
  76. func (e *bincEncDriver) EncodeBool(b bool) {
  77. if b {
  78. e.w.writen1(bincVdSpecial<<4 | bincSpTrue)
  79. } else {
  80. e.w.writen1(bincVdSpecial<<4 | bincSpFalse)
  81. }
  82. }
  83. func (e *bincEncDriver) EncodeFloat32(f float32) {
  84. if f == 0 {
  85. e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
  86. return
  87. }
  88. e.w.writen1(bincVdFloat<<4 | bincFlBin32)
  89. bigenHelper{e.b[:4], e.w}.writeUint32(math.Float32bits(f))
  90. }
  91. func (e *bincEncDriver) EncodeFloat64(f float64) {
  92. if f == 0 {
  93. e.w.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
  94. return
  95. }
  96. bigen.PutUint64(e.b[:8], math.Float64bits(f))
  97. if bincDoPrune {
  98. i := 7
  99. for ; i >= 0 && (e.b[i] == 0); i-- {
  100. }
  101. i++
  102. if i <= 6 {
  103. e.w.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64)
  104. e.w.writen1(byte(i))
  105. e.w.writeb(e.b[:i])
  106. return
  107. }
  108. }
  109. e.w.writen1(bincVdFloat<<4 | bincFlBin64)
  110. e.w.writeb(e.b[:8])
  111. }
  112. func (e *bincEncDriver) encIntegerPrune(bd byte, pos bool, v uint64, lim uint8) {
  113. if lim == 4 {
  114. bigen.PutUint32(e.b[:lim], uint32(v))
  115. } else {
  116. bigen.PutUint64(e.b[:lim], v)
  117. }
  118. if bincDoPrune {
  119. i := pruneSignExt(e.b[:lim], pos)
  120. e.w.writen1(bd | lim - 1 - byte(i))
  121. e.w.writeb(e.b[i:lim])
  122. } else {
  123. e.w.writen1(bd | lim - 1)
  124. e.w.writeb(e.b[:lim])
  125. }
  126. }
  127. func (e *bincEncDriver) EncodeInt(v int64) {
  128. const nbd byte = bincVdNegInt << 4
  129. if v >= 0 {
  130. e.encUint(bincVdPosInt<<4, true, uint64(v))
  131. } else if v == -1 {
  132. e.w.writen1(bincVdSpecial<<4 | bincSpNegOne)
  133. } else {
  134. e.encUint(bincVdNegInt<<4, false, uint64(-v))
  135. }
  136. }
  137. func (e *bincEncDriver) EncodeUint(v uint64) {
  138. e.encUint(bincVdPosInt<<4, true, v)
  139. }
  140. func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) {
  141. if v == 0 {
  142. e.w.writen1(bincVdSpecial<<4 | bincSpZero)
  143. } else if pos && v >= 1 && v <= 16 {
  144. e.w.writen1(bincVdSmallInt<<4 | byte(v-1))
  145. } else if v <= math.MaxUint8 {
  146. e.w.writen2(bd|0x0, byte(v))
  147. } else if v <= math.MaxUint16 {
  148. e.w.writen1(bd | 0x01)
  149. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v))
  150. } else if v <= math.MaxUint32 {
  151. e.encIntegerPrune(bd, pos, v, 4)
  152. } else {
  153. e.encIntegerPrune(bd, pos, v, 8)
  154. }
  155. }
  156. func (e *bincEncDriver) EncodeExt(rv interface{}, xtag uint64, ext Ext, _ *Encoder) {
  157. bs := ext.WriteExt(rv)
  158. if bs == nil {
  159. e.EncodeNil()
  160. return
  161. }
  162. e.encodeExtPreamble(uint8(xtag), len(bs))
  163. e.w.writeb(bs)
  164. }
  165. func (e *bincEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  166. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  167. e.w.writeb(re.Data)
  168. }
  169. func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
  170. e.encLen(bincVdCustomExt<<4, uint64(length))
  171. e.w.writen1(xtag)
  172. }
  173. func (e *bincEncDriver) WriteArrayStart(length int) {
  174. e.encLen(bincVdArray<<4, uint64(length))
  175. }
  176. func (e *bincEncDriver) WriteMapStart(length int) {
  177. e.encLen(bincVdMap<<4, uint64(length))
  178. }
  179. func (e *bincEncDriver) EncodeString(c charEncoding, v string) {
  180. l := uint64(len(v))
  181. e.encBytesLen(c, l)
  182. if l > 0 {
  183. e.w.writestr(v)
  184. }
  185. }
  186. func (e *bincEncDriver) EncodeSymbol(v string) {
  187. // if WriteSymbolsNoRefs {
  188. // e.encodeString(cUTF8, v)
  189. // return
  190. // }
  191. //symbols only offer benefit when string length > 1.
  192. //This is because strings with length 1 take only 2 bytes to store
  193. //(bd with embedded length, and single byte for string val).
  194. l := len(v)
  195. if l == 0 {
  196. e.encBytesLen(cUTF8, 0)
  197. return
  198. } else if l == 1 {
  199. e.encBytesLen(cUTF8, 1)
  200. e.w.writen1(v[0])
  201. return
  202. }
  203. if e.m == nil {
  204. e.m = make(map[string]uint16, 16)
  205. }
  206. ui, ok := e.m[v]
  207. if ok {
  208. if ui <= math.MaxUint8 {
  209. e.w.writen2(bincVdSymbol<<4, byte(ui))
  210. } else {
  211. e.w.writen1(bincVdSymbol<<4 | 0x8)
  212. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  213. }
  214. } else {
  215. e.s++
  216. ui = e.s
  217. //ui = uint16(atomic.AddUint32(&e.s, 1))
  218. e.m[v] = ui
  219. var lenprec uint8
  220. if l <= math.MaxUint8 {
  221. // lenprec = 0
  222. } else if l <= math.MaxUint16 {
  223. lenprec = 1
  224. } else if int64(l) <= math.MaxUint32 {
  225. lenprec = 2
  226. } else {
  227. lenprec = 3
  228. }
  229. if ui <= math.MaxUint8 {
  230. e.w.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
  231. } else {
  232. e.w.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
  233. bigenHelper{e.b[:2], e.w}.writeUint16(ui)
  234. }
  235. if lenprec == 0 {
  236. e.w.writen1(byte(l))
  237. } else if lenprec == 1 {
  238. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(l))
  239. } else if lenprec == 2 {
  240. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(l))
  241. } else {
  242. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(l))
  243. }
  244. e.w.writestr(v)
  245. }
  246. }
  247. func (e *bincEncDriver) EncodeStringBytes(c charEncoding, v []byte) {
  248. if v == nil {
  249. e.EncodeNil()
  250. return
  251. }
  252. l := uint64(len(v))
  253. e.encBytesLen(c, l)
  254. if l > 0 {
  255. e.w.writeb(v)
  256. }
  257. }
  258. func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
  259. //TODO: support bincUnicodeOther (for now, just use string or bytearray)
  260. if c == cRAW {
  261. e.encLen(bincVdByteArray<<4, length)
  262. } else {
  263. e.encLen(bincVdString<<4, length)
  264. }
  265. }
  266. func (e *bincEncDriver) encLen(bd byte, l uint64) {
  267. if l < 12 {
  268. e.w.writen1(bd | uint8(l+4))
  269. } else {
  270. e.encLenNumber(bd, l)
  271. }
  272. }
  273. func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
  274. if v <= math.MaxUint8 {
  275. e.w.writen2(bd, byte(v))
  276. } else if v <= math.MaxUint16 {
  277. e.w.writen1(bd | 0x01)
  278. bigenHelper{e.b[:2], e.w}.writeUint16(uint16(v))
  279. } else if v <= math.MaxUint32 {
  280. e.w.writen1(bd | 0x02)
  281. bigenHelper{e.b[:4], e.w}.writeUint32(uint32(v))
  282. } else {
  283. e.w.writen1(bd | 0x03)
  284. bigenHelper{e.b[:8], e.w}.writeUint64(uint64(v))
  285. }
  286. }
  287. //------------------------------------
  288. type bincDecSymbol struct {
  289. s string
  290. b []byte
  291. i uint16
  292. }
  293. type bincDecDriver struct {
  294. d *Decoder
  295. h *BincHandle
  296. r decReader
  297. br bool // bytes reader
  298. bdRead bool
  299. bd byte
  300. vd byte
  301. vs byte
  302. // noStreamingCodec
  303. // decNoSeparator
  304. b [scratchByteArrayLen]byte
  305. // linear searching on this slice is ok,
  306. // because we typically expect < 32 symbols in each stream.
  307. s []bincDecSymbol
  308. decDriverNoopContainerReader
  309. noBuiltInTypes
  310. }
  311. func (d *bincDecDriver) readNextBd() {
  312. d.bd = d.r.readn1()
  313. d.vd = d.bd >> 4
  314. d.vs = d.bd & 0x0f
  315. d.bdRead = true
  316. }
  317. func (d *bincDecDriver) uncacheRead() {
  318. if d.bdRead {
  319. d.r.unreadn1()
  320. d.bdRead = false
  321. }
  322. }
  323. func (d *bincDecDriver) ContainerType() (vt valueType) {
  324. if !d.bdRead {
  325. d.readNextBd()
  326. }
  327. if d.vd == bincVdSpecial && d.vs == bincSpNil {
  328. return valueTypeNil
  329. } else if d.vd == bincVdByteArray {
  330. return valueTypeBytes
  331. } else if d.vd == bincVdString {
  332. return valueTypeString
  333. } else if d.vd == bincVdArray {
  334. return valueTypeArray
  335. } else if d.vd == bincVdMap {
  336. return valueTypeMap
  337. }
  338. // else {
  339. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  340. // }
  341. return valueTypeUnset
  342. }
  343. func (d *bincDecDriver) TryDecodeAsNil() bool {
  344. if !d.bdRead {
  345. d.readNextBd()
  346. }
  347. if d.bd == bincVdSpecial<<4|bincSpNil {
  348. d.bdRead = false
  349. return true
  350. }
  351. return false
  352. }
  353. // func (d *bincDecDriver) IsBuiltinType(rt uintptr) bool {
  354. // return rt == timeTypId
  355. // }
  356. func (d *bincDecDriver) DecodeTime() (tt time.Time) {
  357. if !d.bdRead {
  358. d.readNextBd()
  359. }
  360. if d.vd != bincVdTimestamp {
  361. d.d.errorf("Invalid d.vd. Expecting 0x%x. Received: 0x%x", bincVdTimestamp, d.vd)
  362. return
  363. }
  364. tt, err := decodeTime(d.r.readx(int(d.vs)))
  365. if err != nil {
  366. panic(err)
  367. }
  368. d.bdRead = false
  369. return
  370. }
  371. // func (d *bincDecDriver) DecodeBuiltin(rt uintptr, v interface{}) {
  372. // if rt == timeTypId {
  373. // var vt = v.(*time.Time)
  374. // *vt = d.DecodeTime()
  375. // return
  376. // }
  377. // d.d.errorf("binc error decoding builtin: expect *time.Time, received %T", v)
  378. // }
  379. func (d *bincDecDriver) decFloatPre(vs, defaultLen byte) {
  380. if vs&0x8 == 0 {
  381. d.r.readb(d.b[0:defaultLen])
  382. } else {
  383. l := d.r.readn1()
  384. if l > 8 {
  385. d.d.errorf("At most 8 bytes used to represent float. Received: %v bytes", l)
  386. return
  387. }
  388. for i := l; i < 8; i++ {
  389. d.b[i] = 0
  390. }
  391. d.r.readb(d.b[0:l])
  392. }
  393. }
  394. func (d *bincDecDriver) decFloat() (f float64) {
  395. //if true { f = math.Float64frombits(bigen.Uint64(d.r.readx(8))); break; }
  396. if x := d.vs & 0x7; x == bincFlBin32 {
  397. d.decFloatPre(d.vs, 4)
  398. f = float64(math.Float32frombits(bigen.Uint32(d.b[0:4])))
  399. } else if x == bincFlBin64 {
  400. d.decFloatPre(d.vs, 8)
  401. f = math.Float64frombits(bigen.Uint64(d.b[0:8]))
  402. } else {
  403. d.d.errorf("only float32 and float64 are supported. d.vd: 0x%x, d.vs: 0x%x", d.vd, d.vs)
  404. return
  405. }
  406. return
  407. }
  408. func (d *bincDecDriver) decUint() (v uint64) {
  409. // need to inline the code (interface conversion and type assertion expensive)
  410. switch d.vs {
  411. case 0:
  412. v = uint64(d.r.readn1())
  413. case 1:
  414. d.r.readb(d.b[6:8])
  415. v = uint64(bigen.Uint16(d.b[6:8]))
  416. case 2:
  417. d.b[4] = 0
  418. d.r.readb(d.b[5:8])
  419. v = uint64(bigen.Uint32(d.b[4:8]))
  420. case 3:
  421. d.r.readb(d.b[4:8])
  422. v = uint64(bigen.Uint32(d.b[4:8]))
  423. case 4, 5, 6:
  424. lim := int(7 - d.vs)
  425. d.r.readb(d.b[lim:8])
  426. for i := 0; i < lim; i++ {
  427. d.b[i] = 0
  428. }
  429. v = uint64(bigen.Uint64(d.b[:8]))
  430. case 7:
  431. d.r.readb(d.b[:8])
  432. v = uint64(bigen.Uint64(d.b[:8]))
  433. default:
  434. d.d.errorf("unsigned integers with greater than 64 bits of precision not supported")
  435. return
  436. }
  437. return
  438. }
  439. func (d *bincDecDriver) decCheckInteger() (ui uint64, neg bool) {
  440. if !d.bdRead {
  441. d.readNextBd()
  442. }
  443. vd, vs := d.vd, d.vs
  444. if vd == bincVdPosInt {
  445. ui = d.decUint()
  446. } else if vd == bincVdNegInt {
  447. ui = d.decUint()
  448. neg = true
  449. } else if vd == bincVdSmallInt {
  450. ui = uint64(d.vs) + 1
  451. } else if vd == bincVdSpecial {
  452. if vs == bincSpZero {
  453. //i = 0
  454. } else if vs == bincSpNegOne {
  455. neg = true
  456. ui = 1
  457. } else {
  458. d.d.errorf("numeric decode fails for special value: d.vs: 0x%x", d.vs)
  459. return
  460. }
  461. } else {
  462. d.d.errorf("number can only be decoded from uint or int values. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
  463. return
  464. }
  465. return
  466. }
  467. func (d *bincDecDriver) DecodeInt(bitsize uint8) (i int64) {
  468. ui, neg := d.decCheckInteger()
  469. i, overflow := chkOvf.SignedInt(ui)
  470. if overflow {
  471. d.d.errorf("simple: overflow converting %v to signed integer", ui)
  472. return
  473. }
  474. if neg {
  475. i = -i
  476. }
  477. if chkOvf.Int(i, bitsize) {
  478. d.d.errorf("binc: overflow integer: %v for num bits: %v", i, bitsize)
  479. return
  480. }
  481. d.bdRead = false
  482. return
  483. }
  484. func (d *bincDecDriver) DecodeUint(bitsize uint8) (ui uint64) {
  485. ui, neg := d.decCheckInteger()
  486. if neg {
  487. d.d.errorf("Assigning negative signed value to unsigned type")
  488. return
  489. }
  490. if chkOvf.Uint(ui, bitsize) {
  491. d.d.errorf("binc: overflow integer: %v", ui)
  492. return
  493. }
  494. d.bdRead = false
  495. return
  496. }
  497. func (d *bincDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  498. if !d.bdRead {
  499. d.readNextBd()
  500. }
  501. vd, vs := d.vd, d.vs
  502. if vd == bincVdSpecial {
  503. d.bdRead = false
  504. if vs == bincSpNan {
  505. return math.NaN()
  506. } else if vs == bincSpPosInf {
  507. return math.Inf(1)
  508. } else if vs == bincSpZeroFloat || vs == bincSpZero {
  509. return
  510. } else if vs == bincSpNegInf {
  511. return math.Inf(-1)
  512. } else {
  513. d.d.errorf("Invalid d.vs decoding float where d.vd=bincVdSpecial: %v", d.vs)
  514. return
  515. }
  516. } else if vd == bincVdFloat {
  517. f = d.decFloat()
  518. } else {
  519. f = float64(d.DecodeInt(64))
  520. }
  521. if chkOverflow32 && chkOvf.Float32(f) {
  522. d.d.errorf("binc: float32 overflow: %v", f)
  523. return
  524. }
  525. d.bdRead = false
  526. return
  527. }
  528. // bool can be decoded from bool only (single byte).
  529. func (d *bincDecDriver) DecodeBool() (b bool) {
  530. if !d.bdRead {
  531. d.readNextBd()
  532. }
  533. if bd := d.bd; bd == (bincVdSpecial | bincSpFalse) {
  534. // b = false
  535. } else if bd == (bincVdSpecial | bincSpTrue) {
  536. b = true
  537. } else {
  538. d.d.errorf("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  539. return
  540. }
  541. d.bdRead = false
  542. return
  543. }
  544. func (d *bincDecDriver) ReadMapStart() (length int) {
  545. if !d.bdRead {
  546. d.readNextBd()
  547. }
  548. if d.vd != bincVdMap {
  549. d.d.errorf("Invalid d.vd for map. Expecting 0x%x. Got: 0x%x", bincVdMap, d.vd)
  550. return
  551. }
  552. length = d.decLen()
  553. d.bdRead = false
  554. return
  555. }
  556. func (d *bincDecDriver) ReadArrayStart() (length int) {
  557. if !d.bdRead {
  558. d.readNextBd()
  559. }
  560. if d.vd != bincVdArray {
  561. d.d.errorf("Invalid d.vd for array. Expecting 0x%x. Got: 0x%x", bincVdArray, d.vd)
  562. return
  563. }
  564. length = d.decLen()
  565. d.bdRead = false
  566. return
  567. }
  568. func (d *bincDecDriver) decLen() int {
  569. if d.vs > 3 {
  570. return int(d.vs - 4)
  571. }
  572. return int(d.decLenNumber())
  573. }
  574. func (d *bincDecDriver) decLenNumber() (v uint64) {
  575. if x := d.vs; x == 0 {
  576. v = uint64(d.r.readn1())
  577. } else if x == 1 {
  578. d.r.readb(d.b[6:8])
  579. v = uint64(bigen.Uint16(d.b[6:8]))
  580. } else if x == 2 {
  581. d.r.readb(d.b[4:8])
  582. v = uint64(bigen.Uint32(d.b[4:8]))
  583. } else {
  584. d.r.readb(d.b[:8])
  585. v = bigen.Uint64(d.b[:8])
  586. }
  587. return
  588. }
  589. func (d *bincDecDriver) decStringAndBytes(bs []byte, withString, zerocopy bool) (bs2 []byte, s string) {
  590. if !d.bdRead {
  591. d.readNextBd()
  592. }
  593. if d.bd == bincVdSpecial<<4|bincSpNil {
  594. d.bdRead = false
  595. return
  596. }
  597. var slen = -1
  598. // var ok bool
  599. switch d.vd {
  600. case bincVdString, bincVdByteArray:
  601. slen = d.decLen()
  602. if zerocopy {
  603. if d.br {
  604. bs2 = d.r.readx(slen)
  605. } else if len(bs) == 0 {
  606. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, d.b[:])
  607. } else {
  608. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  609. }
  610. } else {
  611. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, bs)
  612. }
  613. if withString {
  614. s = string(bs2)
  615. }
  616. case bincVdSymbol:
  617. // zerocopy doesn't apply for symbols,
  618. // as the values must be stored in a table for later use.
  619. //
  620. //from vs: extract numSymbolBytes, containsStringVal, strLenPrecision,
  621. //extract symbol
  622. //if containsStringVal, read it and put in map
  623. //else look in map for string value
  624. var symbol uint16
  625. vs := d.vs
  626. if vs&0x8 == 0 {
  627. symbol = uint16(d.r.readn1())
  628. } else {
  629. symbol = uint16(bigen.Uint16(d.r.readx(2)))
  630. }
  631. if d.s == nil {
  632. d.s = make([]bincDecSymbol, 0, 16)
  633. }
  634. if vs&0x4 == 0 {
  635. for i := range d.s {
  636. j := &d.s[i]
  637. if j.i == symbol {
  638. bs2 = j.b
  639. if withString {
  640. if j.s == "" && bs2 != nil {
  641. j.s = string(bs2)
  642. }
  643. s = j.s
  644. }
  645. break
  646. }
  647. }
  648. } else {
  649. switch vs & 0x3 {
  650. case 0:
  651. slen = int(d.r.readn1())
  652. case 1:
  653. slen = int(bigen.Uint16(d.r.readx(2)))
  654. case 2:
  655. slen = int(bigen.Uint32(d.r.readx(4)))
  656. case 3:
  657. slen = int(bigen.Uint64(d.r.readx(8)))
  658. }
  659. // since using symbols, do not store any part of
  660. // the parameter bs in the map, as it might be a shared buffer.
  661. // bs2 = decByteSlice(d.r, slen, bs)
  662. bs2 = decByteSlice(d.r, slen, d.d.h.MaxInitLen, nil)
  663. if withString {
  664. s = string(bs2)
  665. }
  666. d.s = append(d.s, bincDecSymbol{i: symbol, s: s, b: bs2})
  667. }
  668. default:
  669. d.d.errorf("Invalid d.vd. Expecting string:0x%x, bytearray:0x%x or symbol: 0x%x. Got: 0x%x",
  670. bincVdString, bincVdByteArray, bincVdSymbol, d.vd)
  671. return
  672. }
  673. d.bdRead = false
  674. return
  675. }
  676. func (d *bincDecDriver) DecodeString() (s string) {
  677. // DecodeBytes does not accommodate symbols, whose impl stores string version in map.
  678. // Use decStringAndBytes directly.
  679. // return string(d.DecodeBytes(d.b[:], true, true))
  680. _, s = d.decStringAndBytes(d.b[:], true, true)
  681. return
  682. }
  683. func (d *bincDecDriver) DecodeStringAsBytes() (s []byte) {
  684. s, _ = d.decStringAndBytes(d.b[:], false, true)
  685. return
  686. }
  687. func (d *bincDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  688. if !d.bdRead {
  689. d.readNextBd()
  690. }
  691. if d.bd == bincVdSpecial<<4|bincSpNil {
  692. d.bdRead = false
  693. return nil
  694. }
  695. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  696. if d.vd == bincVdArray {
  697. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  698. return
  699. }
  700. var clen int
  701. if d.vd == bincVdString || d.vd == bincVdByteArray {
  702. clen = d.decLen()
  703. } else {
  704. d.d.errorf("Invalid d.vd for bytes. Expecting string:0x%x or bytearray:0x%x. Got: 0x%x",
  705. bincVdString, bincVdByteArray, d.vd)
  706. return
  707. }
  708. d.bdRead = false
  709. if zerocopy {
  710. if d.br {
  711. return d.r.readx(clen)
  712. } else if len(bs) == 0 {
  713. bs = d.b[:]
  714. }
  715. }
  716. return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs)
  717. }
  718. func (d *bincDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  719. if xtag > 0xff {
  720. d.d.errorf("decodeExt: tag must be <= 0xff; got: %v", xtag)
  721. return
  722. }
  723. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  724. realxtag = uint64(realxtag1)
  725. if ext == nil {
  726. re := rv.(*RawExt)
  727. re.Tag = realxtag
  728. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  729. } else {
  730. ext.ReadExt(rv, xbs)
  731. }
  732. return
  733. }
  734. func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  735. if !d.bdRead {
  736. d.readNextBd()
  737. }
  738. if d.vd == bincVdCustomExt {
  739. l := d.decLen()
  740. xtag = d.r.readn1()
  741. if verifyTag && xtag != tag {
  742. d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  743. return
  744. }
  745. xbs = d.r.readx(l)
  746. } else if d.vd == bincVdByteArray {
  747. xbs = d.DecodeBytes(nil, true)
  748. } else {
  749. d.d.errorf("Invalid d.vd for extensions (Expecting extensions or byte array). Got: 0x%x", d.vd)
  750. return
  751. }
  752. d.bdRead = false
  753. return
  754. }
  755. func (d *bincDecDriver) DecodeNaked() {
  756. if !d.bdRead {
  757. d.readNextBd()
  758. }
  759. n := d.d.n
  760. var decodeFurther bool
  761. switch d.vd {
  762. case bincVdSpecial:
  763. switch d.vs {
  764. case bincSpNil:
  765. n.v = valueTypeNil
  766. case bincSpFalse:
  767. n.v = valueTypeBool
  768. n.b = false
  769. case bincSpTrue:
  770. n.v = valueTypeBool
  771. n.b = true
  772. case bincSpNan:
  773. n.v = valueTypeFloat
  774. n.f = math.NaN()
  775. case bincSpPosInf:
  776. n.v = valueTypeFloat
  777. n.f = math.Inf(1)
  778. case bincSpNegInf:
  779. n.v = valueTypeFloat
  780. n.f = math.Inf(-1)
  781. case bincSpZeroFloat:
  782. n.v = valueTypeFloat
  783. n.f = float64(0)
  784. case bincSpZero:
  785. n.v = valueTypeUint
  786. n.u = uint64(0) // int8(0)
  787. case bincSpNegOne:
  788. n.v = valueTypeInt
  789. n.i = int64(-1) // int8(-1)
  790. default:
  791. d.d.errorf("decodeNaked: Unrecognized special value 0x%x", d.vs)
  792. }
  793. case bincVdSmallInt:
  794. n.v = valueTypeUint
  795. n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
  796. case bincVdPosInt:
  797. n.v = valueTypeUint
  798. n.u = d.decUint()
  799. case bincVdNegInt:
  800. n.v = valueTypeInt
  801. n.i = -(int64(d.decUint()))
  802. case bincVdFloat:
  803. n.v = valueTypeFloat
  804. n.f = d.decFloat()
  805. case bincVdSymbol:
  806. n.v = valueTypeSymbol
  807. n.s = d.DecodeString()
  808. case bincVdString:
  809. n.v = valueTypeString
  810. n.s = d.DecodeString()
  811. case bincVdByteArray:
  812. n.v = valueTypeBytes
  813. n.l = d.DecodeBytes(nil, false)
  814. case bincVdTimestamp:
  815. n.v = valueTypeTime
  816. tt, err := decodeTime(d.r.readx(int(d.vs)))
  817. if err != nil {
  818. panic(err)
  819. }
  820. n.t = tt
  821. case bincVdCustomExt:
  822. n.v = valueTypeExt
  823. l := d.decLen()
  824. n.u = uint64(d.r.readn1())
  825. n.l = d.r.readx(l)
  826. case bincVdArray:
  827. n.v = valueTypeArray
  828. decodeFurther = true
  829. case bincVdMap:
  830. n.v = valueTypeMap
  831. decodeFurther = true
  832. default:
  833. d.d.errorf("decodeNaked: Unrecognized d.vd: 0x%x", d.vd)
  834. }
  835. if !decodeFurther {
  836. d.bdRead = false
  837. }
  838. if n.v == valueTypeUint && d.h.SignedInteger {
  839. n.v = valueTypeInt
  840. n.i = int64(n.u)
  841. }
  842. return
  843. }
  844. //------------------------------------
  845. //BincHandle is a Handle for the Binc Schema-Free Encoding Format
  846. //defined at https://github.com/ugorji/binc .
  847. //
  848. //BincHandle currently supports all Binc features with the following EXCEPTIONS:
  849. // - only integers up to 64 bits of precision are supported.
  850. // big integers are unsupported.
  851. // - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
  852. // extended precision and decimal IEEE 754 floats are unsupported.
  853. // - Only UTF-8 strings supported.
  854. // Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
  855. //
  856. //Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
  857. type BincHandle struct {
  858. BasicHandle
  859. binaryEncodingType
  860. noElemSeparators
  861. }
  862. // SetBytesExt sets an extension
  863. func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  864. return h.SetExt(rt, tag, &setExtWrapper{b: ext})
  865. }
  866. func (h *BincHandle) newEncDriver(e *Encoder) encDriver {
  867. return &bincEncDriver{e: e, w: e.w}
  868. }
  869. func (h *BincHandle) newDecDriver(d *Decoder) decDriver {
  870. return &bincDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  871. }
  872. // // IsBuiltinType returns true for time.Time, else false.
  873. // // only time.Time is builtin.
  874. // func (h *BincHandle) IsBuiltinType(rt uintptr) bool {
  875. // return rt == timeTypId
  876. // }
  877. func (e *bincEncDriver) reset() {
  878. e.w = e.e.w
  879. e.s = 0
  880. e.m = nil
  881. }
  882. func (d *bincDecDriver) reset() {
  883. d.r, d.br = d.d.r, d.d.bytes
  884. d.s = nil
  885. d.bd, d.bdRead, d.vd, d.vs = 0, false, 0, 0
  886. }
  887. var _ decDriver = (*bincDecDriver)(nil)
  888. var _ encDriver = (*bincEncDriver)(nil)