msgpack.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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. /*
  4. MSGPACK
  5. Msgpack-c implementation powers the c, c++, python, ruby, etc libraries.
  6. We need to maintain compatibility with it and how it encodes integer values
  7. without caring about the type.
  8. For compatibility with behaviour of msgpack-c reference implementation:
  9. - Go intX (>0) and uintX
  10. IS ENCODED AS
  11. msgpack +ve fixnum, unsigned
  12. - Go intX (<0)
  13. IS ENCODED AS
  14. msgpack -ve fixnum, signed
  15. */
  16. package codec
  17. import (
  18. "fmt"
  19. "io"
  20. "math"
  21. "net/rpc"
  22. "reflect"
  23. "time"
  24. )
  25. const (
  26. mpPosFixNumMin byte = 0x00
  27. mpPosFixNumMax byte = 0x7f
  28. mpFixMapMin byte = 0x80
  29. mpFixMapMax byte = 0x8f
  30. mpFixArrayMin byte = 0x90
  31. mpFixArrayMax byte = 0x9f
  32. mpFixStrMin byte = 0xa0
  33. mpFixStrMax byte = 0xbf
  34. mpNil byte = 0xc0
  35. _ byte = 0xc1
  36. mpFalse byte = 0xc2
  37. mpTrue byte = 0xc3
  38. mpFloat byte = 0xca
  39. mpDouble byte = 0xcb
  40. mpUint8 byte = 0xcc
  41. mpUint16 byte = 0xcd
  42. mpUint32 byte = 0xce
  43. mpUint64 byte = 0xcf
  44. mpInt8 byte = 0xd0
  45. mpInt16 byte = 0xd1
  46. mpInt32 byte = 0xd2
  47. mpInt64 byte = 0xd3
  48. // extensions below
  49. mpBin8 byte = 0xc4
  50. mpBin16 byte = 0xc5
  51. mpBin32 byte = 0xc6
  52. mpExt8 byte = 0xc7
  53. mpExt16 byte = 0xc8
  54. mpExt32 byte = 0xc9
  55. mpFixExt1 byte = 0xd4
  56. mpFixExt2 byte = 0xd5
  57. mpFixExt4 byte = 0xd6
  58. mpFixExt8 byte = 0xd7
  59. mpFixExt16 byte = 0xd8
  60. mpStr8 byte = 0xd9 // new
  61. mpStr16 byte = 0xda
  62. mpStr32 byte = 0xdb
  63. mpArray16 byte = 0xdc
  64. mpArray32 byte = 0xdd
  65. mpMap16 byte = 0xde
  66. mpMap32 byte = 0xdf
  67. mpNegFixNumMin byte = 0xe0
  68. mpNegFixNumMax byte = 0xff
  69. )
  70. var mpTimeExtTag int8 = -1
  71. var mpTimeExtTagU = uint8(mpTimeExtTag)
  72. // var mpdesc = map[byte]string{
  73. // mpPosFixNumMin: "PosFixNumMin",
  74. // mpPosFixNumMax: "PosFixNumMax",
  75. // mpFixMapMin: "FixMapMin",
  76. // mpFixMapMax: "FixMapMax",
  77. // mpFixArrayMin: "FixArrayMin",
  78. // mpFixArrayMax: "FixArrayMax",
  79. // mpFixStrMin: "FixStrMin",
  80. // mpFixStrMax: "FixStrMax",
  81. // mpNil: "Nil",
  82. // mpFalse: "False",
  83. // mpTrue: "True",
  84. // mpFloat: "Float",
  85. // mpDouble: "Double",
  86. // mpUint8: "Uint8",
  87. // mpUint16: "Uint16",
  88. // mpUint32: "Uint32",
  89. // mpUint64: "Uint64",
  90. // mpInt8: "Int8",
  91. // mpInt16: "Int16",
  92. // mpInt32: "Int32",
  93. // mpInt64: "Int64",
  94. // mpBin8: "Bin8",
  95. // mpBin16: "Bin16",
  96. // mpBin32: "Bin32",
  97. // mpExt8: "Ext8",
  98. // mpExt16: "Ext16",
  99. // mpExt32: "Ext32",
  100. // mpFixExt1: "FixExt1",
  101. // mpFixExt2: "FixExt2",
  102. // mpFixExt4: "FixExt4",
  103. // mpFixExt8: "FixExt8",
  104. // mpFixExt16: "FixExt16",
  105. // mpStr8: "Str8",
  106. // mpStr16: "Str16",
  107. // mpStr32: "Str32",
  108. // mpArray16: "Array16",
  109. // mpArray32: "Array32",
  110. // mpMap16: "Map16",
  111. // mpMap32: "Map32",
  112. // mpNegFixNumMin: "NegFixNumMin",
  113. // mpNegFixNumMax: "NegFixNumMax",
  114. // }
  115. func mpdesc(bd byte) string {
  116. switch bd {
  117. case mpNil:
  118. return "nil"
  119. case mpFalse:
  120. return "false"
  121. case mpTrue:
  122. return "true"
  123. case mpFloat, mpDouble:
  124. return "float"
  125. case mpUint8, mpUint16, mpUint32, mpUint64:
  126. return "uint"
  127. case mpInt8, mpInt16, mpInt32, mpInt64:
  128. return "int"
  129. default:
  130. switch {
  131. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  132. return "int"
  133. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  134. return "int"
  135. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  136. return "string|bytes"
  137. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  138. return "bytes"
  139. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  140. return "array"
  141. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  142. return "map"
  143. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  144. return "ext"
  145. default:
  146. return "unknown"
  147. }
  148. }
  149. }
  150. // MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
  151. // that the backend RPC service takes multiple arguments, which have been arranged
  152. // in sequence in the slice.
  153. //
  154. // The Codec then passes it AS-IS to the rpc service (without wrapping it in an
  155. // array of 1 element).
  156. type MsgpackSpecRpcMultiArgs []interface{}
  157. // A MsgpackContainer type specifies the different types of msgpackContainers.
  158. type msgpackContainerType struct {
  159. fixCutoff int
  160. bFixMin, b8, b16, b32 byte
  161. hasFixMin, has8, has8Always bool
  162. }
  163. var (
  164. msgpackContainerStr = msgpackContainerType{
  165. 32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false,
  166. }
  167. msgpackContainerBin = msgpackContainerType{
  168. 0, 0, mpBin8, mpBin16, mpBin32, false, true, true,
  169. }
  170. msgpackContainerList = msgpackContainerType{
  171. 16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false,
  172. }
  173. msgpackContainerMap = msgpackContainerType{
  174. 16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false,
  175. }
  176. )
  177. //---------------------------------------------
  178. type msgpackEncDriver struct {
  179. noBuiltInTypes
  180. encDriverNoopContainerWriter
  181. // encNoSeparator
  182. e *Encoder
  183. w *encWriterSwitch
  184. h *MsgpackHandle
  185. x [8]byte
  186. // _ [3]uint64 // padding
  187. }
  188. func (e *msgpackEncDriver) EncodeNil() {
  189. e.w.writen1(mpNil)
  190. }
  191. func (e *msgpackEncDriver) EncodeInt(i int64) {
  192. if e.h.PositiveIntUnsigned && i >= 0 {
  193. e.EncodeUint(uint64(i))
  194. } else if i > math.MaxInt8 {
  195. if i <= math.MaxInt16 {
  196. e.w.writen1(mpInt16)
  197. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  198. } else if i <= math.MaxInt32 {
  199. e.w.writen1(mpInt32)
  200. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  201. } else {
  202. e.w.writen1(mpInt64)
  203. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  204. }
  205. } else if i >= -32 {
  206. if e.h.NoFixedNum {
  207. e.w.writen2(mpInt8, byte(i))
  208. } else {
  209. e.w.writen1(byte(i))
  210. }
  211. } else if i >= math.MinInt8 {
  212. e.w.writen2(mpInt8, byte(i))
  213. } else if i >= math.MinInt16 {
  214. e.w.writen1(mpInt16)
  215. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  216. } else if i >= math.MinInt32 {
  217. e.w.writen1(mpInt32)
  218. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  219. } else {
  220. e.w.writen1(mpInt64)
  221. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  222. }
  223. }
  224. func (e *msgpackEncDriver) EncodeUint(i uint64) {
  225. if i <= math.MaxInt8 {
  226. if e.h.NoFixedNum {
  227. e.w.writen2(mpUint8, byte(i))
  228. } else {
  229. e.w.writen1(byte(i))
  230. }
  231. } else if i <= math.MaxUint8 {
  232. e.w.writen2(mpUint8, byte(i))
  233. } else if i <= math.MaxUint16 {
  234. e.w.writen1(mpUint16)
  235. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  236. } else if i <= math.MaxUint32 {
  237. e.w.writen1(mpUint32)
  238. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  239. } else {
  240. e.w.writen1(mpUint64)
  241. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  242. }
  243. }
  244. func (e *msgpackEncDriver) EncodeBool(b bool) {
  245. if b {
  246. e.w.writen1(mpTrue)
  247. } else {
  248. e.w.writen1(mpFalse)
  249. }
  250. }
  251. func (e *msgpackEncDriver) EncodeFloat32(f float32) {
  252. e.w.writen1(mpFloat)
  253. bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f))
  254. }
  255. func (e *msgpackEncDriver) EncodeFloat64(f float64) {
  256. e.w.writen1(mpDouble)
  257. bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f))
  258. }
  259. func (e *msgpackEncDriver) EncodeTime(t time.Time) {
  260. if t.IsZero() {
  261. e.EncodeNil()
  262. return
  263. }
  264. t = t.UTC()
  265. sec, nsec := t.Unix(), uint64(t.Nanosecond())
  266. var data64 uint64
  267. var l = 4
  268. if sec >= 0 && sec>>34 == 0 {
  269. data64 = (nsec << 34) | uint64(sec)
  270. if data64&0xffffffff00000000 != 0 {
  271. l = 8
  272. }
  273. } else {
  274. l = 12
  275. }
  276. if e.h.WriteExt {
  277. e.encodeExtPreamble(mpTimeExtTagU, l)
  278. } else {
  279. e.writeContainerLen(msgpackContainerStr, l)
  280. }
  281. switch l {
  282. case 4:
  283. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(data64))
  284. case 8:
  285. bigenHelper{e.x[:8], e.w}.writeUint64(data64)
  286. case 12:
  287. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(nsec))
  288. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(sec))
  289. }
  290. }
  291. func (e *msgpackEncDriver) EncodeExt(v interface{}, xtag uint64, ext Ext, _ *Encoder) {
  292. bs := ext.WriteExt(v)
  293. if bs == nil {
  294. e.EncodeNil()
  295. return
  296. }
  297. if e.h.WriteExt {
  298. e.encodeExtPreamble(uint8(xtag), len(bs))
  299. e.w.writeb(bs)
  300. } else {
  301. e.EncodeStringBytesRaw(bs)
  302. }
  303. }
  304. func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  305. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  306. e.w.writeb(re.Data)
  307. }
  308. func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
  309. if l == 1 {
  310. e.w.writen2(mpFixExt1, xtag)
  311. } else if l == 2 {
  312. e.w.writen2(mpFixExt2, xtag)
  313. } else if l == 4 {
  314. e.w.writen2(mpFixExt4, xtag)
  315. } else if l == 8 {
  316. e.w.writen2(mpFixExt8, xtag)
  317. } else if l == 16 {
  318. e.w.writen2(mpFixExt16, xtag)
  319. } else if l < 256 {
  320. e.w.writen2(mpExt8, byte(l))
  321. e.w.writen1(xtag)
  322. } else if l < 65536 {
  323. e.w.writen1(mpExt16)
  324. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  325. e.w.writen1(xtag)
  326. } else {
  327. e.w.writen1(mpExt32)
  328. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  329. e.w.writen1(xtag)
  330. }
  331. }
  332. func (e *msgpackEncDriver) WriteArrayStart(length int) {
  333. e.writeContainerLen(msgpackContainerList, length)
  334. }
  335. func (e *msgpackEncDriver) WriteMapStart(length int) {
  336. e.writeContainerLen(msgpackContainerMap, length)
  337. }
  338. func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) {
  339. slen := len(s)
  340. if c == cRAW && e.h.WriteExt {
  341. e.writeContainerLen(msgpackContainerBin, slen)
  342. } else {
  343. e.writeContainerLen(msgpackContainerStr, slen)
  344. }
  345. if slen > 0 {
  346. e.w.writestr(s)
  347. }
  348. }
  349. func (e *msgpackEncDriver) EncodeStringEnc(c charEncoding, s string) {
  350. slen := len(s)
  351. e.writeContainerLen(msgpackContainerStr, slen)
  352. if slen > 0 {
  353. e.w.writestr(s)
  354. }
  355. }
  356. func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) {
  357. if bs == nil {
  358. e.EncodeNil()
  359. return
  360. }
  361. slen := len(bs)
  362. if c == cRAW && e.h.WriteExt {
  363. e.writeContainerLen(msgpackContainerBin, slen)
  364. } else {
  365. e.writeContainerLen(msgpackContainerStr, slen)
  366. }
  367. if slen > 0 {
  368. e.w.writeb(bs)
  369. }
  370. }
  371. func (e *msgpackEncDriver) EncodeStringBytesRaw(bs []byte) {
  372. if bs == nil {
  373. e.EncodeNil()
  374. return
  375. }
  376. slen := len(bs)
  377. if e.h.WriteExt {
  378. e.writeContainerLen(msgpackContainerBin, slen)
  379. } else {
  380. e.writeContainerLen(msgpackContainerStr, slen)
  381. }
  382. if slen > 0 {
  383. e.w.writeb(bs)
  384. }
  385. }
  386. func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
  387. if ct.hasFixMin && l < ct.fixCutoff {
  388. e.w.writen1(ct.bFixMin | byte(l))
  389. } else if ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt) {
  390. e.w.writen2(ct.b8, uint8(l))
  391. } else if l < 65536 {
  392. e.w.writen1(ct.b16)
  393. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  394. } else {
  395. e.w.writen1(ct.b32)
  396. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  397. }
  398. }
  399. //---------------------------------------------
  400. type msgpackDecDriver struct {
  401. d *Decoder
  402. r *decReaderSwitch
  403. h *MsgpackHandle
  404. // b [scratchByteArrayLen]byte
  405. bd byte
  406. bdRead bool
  407. br bool // bytes reader
  408. noBuiltInTypes
  409. // noStreamingCodec
  410. // decNoSeparator
  411. decDriverNoopContainerReader
  412. // _ [3]uint64 // padding
  413. }
  414. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  415. // or a containerType, or a specific type denoting nil or extension.
  416. // It is called when a nil interface{} is passed, leaving it up to the DecDriver
  417. // to introspect the stream and decide how best to decode.
  418. // It deciphers the value by looking at the stream first.
  419. func (d *msgpackDecDriver) DecodeNaked() {
  420. if !d.bdRead {
  421. d.readNextBd()
  422. }
  423. bd := d.bd
  424. n := d.d.n
  425. var decodeFurther bool
  426. switch bd {
  427. case mpNil:
  428. n.v = valueTypeNil
  429. d.bdRead = false
  430. case mpFalse:
  431. n.v = valueTypeBool
  432. n.b = false
  433. case mpTrue:
  434. n.v = valueTypeBool
  435. n.b = true
  436. case mpFloat:
  437. n.v = valueTypeFloat
  438. n.f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  439. case mpDouble:
  440. n.v = valueTypeFloat
  441. n.f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  442. case mpUint8:
  443. n.v = valueTypeUint
  444. n.u = uint64(d.r.readn1())
  445. case mpUint16:
  446. n.v = valueTypeUint
  447. n.u = uint64(bigen.Uint16(d.r.readx(2)))
  448. case mpUint32:
  449. n.v = valueTypeUint
  450. n.u = uint64(bigen.Uint32(d.r.readx(4)))
  451. case mpUint64:
  452. n.v = valueTypeUint
  453. n.u = uint64(bigen.Uint64(d.r.readx(8)))
  454. case mpInt8:
  455. n.v = valueTypeInt
  456. n.i = int64(int8(d.r.readn1()))
  457. case mpInt16:
  458. n.v = valueTypeInt
  459. n.i = int64(int16(bigen.Uint16(d.r.readx(2))))
  460. case mpInt32:
  461. n.v = valueTypeInt
  462. n.i = int64(int32(bigen.Uint32(d.r.readx(4))))
  463. case mpInt64:
  464. n.v = valueTypeInt
  465. n.i = int64(int64(bigen.Uint64(d.r.readx(8))))
  466. default:
  467. switch {
  468. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  469. // positive fixnum (always signed)
  470. n.v = valueTypeInt
  471. n.i = int64(int8(bd))
  472. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  473. // negative fixnum
  474. n.v = valueTypeInt
  475. n.i = int64(int8(bd))
  476. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  477. if d.h.RawToString {
  478. n.v = valueTypeString
  479. n.s = d.DecodeString()
  480. } else {
  481. n.v = valueTypeBytes
  482. n.l = d.DecodeBytes(nil, false)
  483. }
  484. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  485. n.v = valueTypeBytes
  486. n.l = d.DecodeBytes(nil, false)
  487. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  488. n.v = valueTypeArray
  489. decodeFurther = true
  490. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  491. n.v = valueTypeMap
  492. decodeFurther = true
  493. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  494. n.v = valueTypeExt
  495. clen := d.readExtLen()
  496. n.u = uint64(d.r.readn1())
  497. if n.u == uint64(mpTimeExtTagU) {
  498. n.v = valueTypeTime
  499. n.t = d.decodeTime(clen)
  500. } else if d.br {
  501. n.l = d.r.readx(clen)
  502. } else {
  503. n.l = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:])
  504. }
  505. default:
  506. d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd))
  507. }
  508. }
  509. if !decodeFurther {
  510. d.bdRead = false
  511. }
  512. if n.v == valueTypeUint && d.h.SignedInteger {
  513. n.v = valueTypeInt
  514. n.i = int64(n.u)
  515. }
  516. return
  517. }
  518. // int can be decoded from msgpack type: intXXX or uintXXX
  519. func (d *msgpackDecDriver) DecodeInt64() (i int64) {
  520. if !d.bdRead {
  521. d.readNextBd()
  522. }
  523. switch d.bd {
  524. case mpUint8:
  525. i = int64(uint64(d.r.readn1()))
  526. case mpUint16:
  527. i = int64(uint64(bigen.Uint16(d.r.readx(2))))
  528. case mpUint32:
  529. i = int64(uint64(bigen.Uint32(d.r.readx(4))))
  530. case mpUint64:
  531. i = int64(bigen.Uint64(d.r.readx(8)))
  532. case mpInt8:
  533. i = int64(int8(d.r.readn1()))
  534. case mpInt16:
  535. i = int64(int16(bigen.Uint16(d.r.readx(2))))
  536. case mpInt32:
  537. i = int64(int32(bigen.Uint32(d.r.readx(4))))
  538. case mpInt64:
  539. i = int64(bigen.Uint64(d.r.readx(8)))
  540. default:
  541. switch {
  542. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  543. i = int64(int8(d.bd))
  544. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  545. i = int64(int8(d.bd))
  546. default:
  547. d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  548. return
  549. }
  550. }
  551. d.bdRead = false
  552. return
  553. }
  554. // uint can be decoded from msgpack type: intXXX or uintXXX
  555. func (d *msgpackDecDriver) DecodeUint64() (ui uint64) {
  556. if !d.bdRead {
  557. d.readNextBd()
  558. }
  559. switch d.bd {
  560. case mpUint8:
  561. ui = uint64(d.r.readn1())
  562. case mpUint16:
  563. ui = uint64(bigen.Uint16(d.r.readx(2)))
  564. case mpUint32:
  565. ui = uint64(bigen.Uint32(d.r.readx(4)))
  566. case mpUint64:
  567. ui = bigen.Uint64(d.r.readx(8))
  568. case mpInt8:
  569. if i := int64(int8(d.r.readn1())); i >= 0 {
  570. ui = uint64(i)
  571. } else {
  572. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  573. return
  574. }
  575. case mpInt16:
  576. if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 {
  577. ui = uint64(i)
  578. } else {
  579. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  580. return
  581. }
  582. case mpInt32:
  583. if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 {
  584. ui = uint64(i)
  585. } else {
  586. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  587. return
  588. }
  589. case mpInt64:
  590. if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 {
  591. ui = uint64(i)
  592. } else {
  593. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  594. return
  595. }
  596. default:
  597. switch {
  598. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  599. ui = uint64(d.bd)
  600. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  601. d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd))
  602. return
  603. default:
  604. d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  605. return
  606. }
  607. }
  608. d.bdRead = false
  609. return
  610. }
  611. // float can either be decoded from msgpack type: float, double or intX
  612. func (d *msgpackDecDriver) DecodeFloat64() (f float64) {
  613. if !d.bdRead {
  614. d.readNextBd()
  615. }
  616. if d.bd == mpFloat {
  617. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  618. } else if d.bd == mpDouble {
  619. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  620. } else {
  621. f = float64(d.DecodeInt64())
  622. }
  623. d.bdRead = false
  624. return
  625. }
  626. // bool can be decoded from bool, fixnum 0 or 1.
  627. func (d *msgpackDecDriver) DecodeBool() (b bool) {
  628. if !d.bdRead {
  629. d.readNextBd()
  630. }
  631. if d.bd == mpFalse || d.bd == 0 {
  632. // b = false
  633. } else if d.bd == mpTrue || d.bd == 1 {
  634. b = true
  635. } else {
  636. d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  637. return
  638. }
  639. d.bdRead = false
  640. return
  641. }
  642. func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  643. if !d.bdRead {
  644. d.readNextBd()
  645. }
  646. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  647. bd := d.bd
  648. // DecodeBytes could be from: bin str fixstr fixarray array ...
  649. var clen int
  650. vt := d.ContainerType()
  651. switch vt {
  652. case valueTypeBytes:
  653. // valueTypeBytes may be a mpBin or an mpStr container
  654. if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  655. clen = d.readContainerLen(msgpackContainerBin)
  656. } else {
  657. clen = d.readContainerLen(msgpackContainerStr)
  658. }
  659. case valueTypeString:
  660. clen = d.readContainerLen(msgpackContainerStr)
  661. case valueTypeArray:
  662. if zerocopy && len(bs) == 0 {
  663. bs = d.d.b[:]
  664. }
  665. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  666. return
  667. default:
  668. d.d.errorf("invalid container type: expecting bin|str|array, got: 0x%x", uint8(vt))
  669. return
  670. }
  671. // these are (bin|str)(8|16|32)
  672. d.bdRead = false
  673. // bytes may be nil, so handle it. if nil, clen=-1.
  674. if clen < 0 {
  675. return nil
  676. }
  677. if zerocopy {
  678. if d.br {
  679. return d.r.readx(clen)
  680. } else if len(bs) == 0 {
  681. bs = d.d.b[:]
  682. }
  683. }
  684. return decByteSlice(d.r, clen, d.h.MaxInitLen, bs)
  685. }
  686. func (d *msgpackDecDriver) DecodeString() (s string) {
  687. return string(d.DecodeBytes(d.d.b[:], true))
  688. }
  689. func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) {
  690. return d.DecodeBytes(d.d.b[:], true)
  691. }
  692. func (d *msgpackDecDriver) readNextBd() {
  693. d.bd = d.r.readn1()
  694. d.bdRead = true
  695. }
  696. func (d *msgpackDecDriver) uncacheRead() {
  697. if d.bdRead {
  698. d.r.unreadn1()
  699. d.bdRead = false
  700. }
  701. }
  702. func (d *msgpackDecDriver) ContainerType() (vt valueType) {
  703. if !d.bdRead {
  704. d.readNextBd()
  705. }
  706. bd := d.bd
  707. if bd == mpNil {
  708. return valueTypeNil
  709. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 ||
  710. (!d.h.RawToString &&
  711. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax))) {
  712. return valueTypeBytes
  713. } else if d.h.RawToString &&
  714. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax)) {
  715. return valueTypeString
  716. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  717. return valueTypeArray
  718. } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  719. return valueTypeMap
  720. }
  721. // else {
  722. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  723. // }
  724. return valueTypeUnset
  725. }
  726. func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) {
  727. if !d.bdRead {
  728. d.readNextBd()
  729. }
  730. if d.bd == mpNil {
  731. d.bdRead = false
  732. return true
  733. }
  734. return
  735. }
  736. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  737. bd := d.bd
  738. if bd == mpNil {
  739. clen = -1 // to represent nil
  740. } else if bd == ct.b8 {
  741. clen = int(d.r.readn1())
  742. } else if bd == ct.b16 {
  743. clen = int(bigen.Uint16(d.r.readx(2)))
  744. } else if bd == ct.b32 {
  745. clen = int(bigen.Uint32(d.r.readx(4)))
  746. } else if (ct.bFixMin & bd) == ct.bFixMin {
  747. clen = int(ct.bFixMin ^ bd)
  748. } else {
  749. d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
  750. return
  751. }
  752. d.bdRead = false
  753. return
  754. }
  755. func (d *msgpackDecDriver) ReadMapStart() int {
  756. if !d.bdRead {
  757. d.readNextBd()
  758. }
  759. return d.readContainerLen(msgpackContainerMap)
  760. }
  761. func (d *msgpackDecDriver) ReadArrayStart() int {
  762. if !d.bdRead {
  763. d.readNextBd()
  764. }
  765. return d.readContainerLen(msgpackContainerList)
  766. }
  767. func (d *msgpackDecDriver) readExtLen() (clen int) {
  768. switch d.bd {
  769. case mpNil:
  770. clen = -1 // to represent nil
  771. case mpFixExt1:
  772. clen = 1
  773. case mpFixExt2:
  774. clen = 2
  775. case mpFixExt4:
  776. clen = 4
  777. case mpFixExt8:
  778. clen = 8
  779. case mpFixExt16:
  780. clen = 16
  781. case mpExt8:
  782. clen = int(d.r.readn1())
  783. case mpExt16:
  784. clen = int(bigen.Uint16(d.r.readx(2)))
  785. case mpExt32:
  786. clen = int(bigen.Uint32(d.r.readx(4)))
  787. default:
  788. d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
  789. return
  790. }
  791. return
  792. }
  793. func (d *msgpackDecDriver) DecodeTime() (t time.Time) {
  794. // decode time from string bytes or ext
  795. if !d.bdRead {
  796. d.readNextBd()
  797. }
  798. if d.bd == mpNil {
  799. d.bdRead = false
  800. return
  801. }
  802. var clen int
  803. switch d.ContainerType() {
  804. case valueTypeBytes, valueTypeString:
  805. clen = d.readContainerLen(msgpackContainerStr)
  806. default:
  807. // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1
  808. d.bdRead = false
  809. b2 := d.r.readn1()
  810. if d.bd == mpFixExt4 && b2 == mpTimeExtTagU {
  811. clen = 4
  812. } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU {
  813. clen = 8
  814. } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU {
  815. clen = 12
  816. } else {
  817. d.d.errorf("invalid bytes for decoding time as extension: got 0x%x, 0x%x", d.bd, b2)
  818. return
  819. }
  820. }
  821. return d.decodeTime(clen)
  822. }
  823. func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) {
  824. // bs = d.r.readx(clen)
  825. d.bdRead = false
  826. switch clen {
  827. case 4:
  828. t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC()
  829. case 8:
  830. tv := bigen.Uint64(d.r.readx(8))
  831. t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC()
  832. case 12:
  833. nsec := bigen.Uint32(d.r.readx(4))
  834. sec := bigen.Uint64(d.r.readx(8))
  835. t = time.Unix(int64(sec), int64(nsec)).UTC()
  836. default:
  837. d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen)
  838. return
  839. }
  840. return
  841. }
  842. func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  843. if xtag > 0xff {
  844. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  845. return
  846. }
  847. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  848. realxtag = uint64(realxtag1)
  849. if ext == nil {
  850. re := rv.(*RawExt)
  851. re.Tag = realxtag
  852. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  853. } else {
  854. ext.ReadExt(rv, xbs)
  855. }
  856. return
  857. }
  858. func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  859. if !d.bdRead {
  860. d.readNextBd()
  861. }
  862. xbd := d.bd
  863. if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 {
  864. xbs = d.DecodeBytes(nil, true)
  865. } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 ||
  866. (xbd >= mpFixStrMin && xbd <= mpFixStrMax) {
  867. xbs = d.DecodeStringAsBytes()
  868. } else {
  869. clen := d.readExtLen()
  870. xtag = d.r.readn1()
  871. if verifyTag && xtag != tag {
  872. d.d.errorf("wrong extension tag - got %b, expecting %v", xtag, tag)
  873. return
  874. }
  875. if d.br {
  876. xbs = d.r.readx(clen)
  877. } else {
  878. xbs = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:])
  879. }
  880. }
  881. d.bdRead = false
  882. return
  883. }
  884. //--------------------------------------------------
  885. //MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
  886. type MsgpackHandle struct {
  887. BasicHandle
  888. // RawToString controls how raw bytes are decoded into a nil interface{}.
  889. RawToString bool
  890. // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum.
  891. NoFixedNum bool
  892. // WriteExt flag supports encoding configured extensions with extension tags.
  893. // It also controls whether other elements of the new spec are encoded (ie Str8).
  894. //
  895. // With WriteExt=false, configured extensions are serialized as raw bytes
  896. // and Str8 is not encoded.
  897. //
  898. // A stream can still be decoded into a typed value, provided an appropriate value
  899. // is provided, but the type cannot be inferred from the stream. If no appropriate
  900. // type is provided (e.g. decoding into a nil interface{}), you get back
  901. // a []byte or string based on the setting of RawToString.
  902. WriteExt bool
  903. // PositiveIntUnsigned says to encode positive integers as unsigned.
  904. PositiveIntUnsigned bool
  905. binaryEncodingType
  906. noElemSeparators
  907. // _ [1]uint64 // padding
  908. }
  909. // Name returns the name of the handle: msgpack
  910. func (h *MsgpackHandle) Name() string { return "msgpack" }
  911. // SetBytesExt sets an extension
  912. func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  913. return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
  914. }
  915. func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver {
  916. return &msgpackEncDriver{e: e, w: e.w, h: h}
  917. }
  918. func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver {
  919. return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  920. }
  921. func (e *msgpackEncDriver) reset() {
  922. e.w = e.e.w
  923. }
  924. func (d *msgpackDecDriver) reset() {
  925. d.r, d.br = d.d.r, d.d.bytes
  926. d.bd, d.bdRead = 0, false
  927. }
  928. //--------------------------------------------------
  929. type msgpackSpecRpcCodec struct {
  930. rpcCodec
  931. }
  932. // /////////////// Spec RPC Codec ///////////////////
  933. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  934. // WriteRequest can write to both a Go service, and other services that do
  935. // not abide by the 1 argument rule of a Go service.
  936. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  937. var bodyArr []interface{}
  938. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  939. bodyArr = ([]interface{})(m)
  940. } else {
  941. bodyArr = []interface{}{body}
  942. }
  943. r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
  944. return c.write(r2, nil, false)
  945. }
  946. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  947. var moe interface{}
  948. if r.Error != "" {
  949. moe = r.Error
  950. }
  951. if moe != nil && body != nil {
  952. body = nil
  953. }
  954. r2 := []interface{}{1, uint32(r.Seq), moe, body}
  955. return c.write(r2, nil, false)
  956. }
  957. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  958. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  959. }
  960. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  961. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  962. }
  963. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  964. if body == nil { // read and discard
  965. return c.read(nil)
  966. }
  967. bodyArr := []interface{}{body}
  968. return c.read(&bodyArr)
  969. }
  970. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  971. if cls := c.cls.load(); cls.closed {
  972. return io.EOF
  973. }
  974. // We read the response header by hand
  975. // so that the body can be decoded on its own from the stream at a later time.
  976. const fia byte = 0x94 //four item array descriptor value
  977. // Not sure why the panic of EOF is swallowed above.
  978. // if bs1 := c.dec.r.readn1(); bs1 != fia {
  979. // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
  980. // return
  981. // }
  982. var ba [1]byte
  983. var n int
  984. for {
  985. n, err = c.r.Read(ba[:])
  986. if err != nil {
  987. return
  988. }
  989. if n == 1 {
  990. break
  991. }
  992. }
  993. var b = ba[0]
  994. if b != fia {
  995. err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b))
  996. } else {
  997. err = c.read(&b)
  998. if err == nil {
  999. if b != expectTypeByte {
  1000. err = fmt.Errorf("%s - expecting %v but got %x/%s",
  1001. msgBadDesc, expectTypeByte, b, mpdesc(b))
  1002. } else {
  1003. err = c.read(msgid)
  1004. if err == nil {
  1005. err = c.read(methodOrError)
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return
  1011. }
  1012. //--------------------------------------------------
  1013. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  1014. // as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  1015. type msgpackSpecRpc struct{}
  1016. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  1017. // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
  1018. //
  1019. // See GoRpc documentation, for information on buffering for better performance.
  1020. var MsgpackSpecRpc msgpackSpecRpc
  1021. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  1022. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1023. }
  1024. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  1025. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1026. }
  1027. var _ decDriver = (*msgpackDecDriver)(nil)
  1028. var _ encDriver = (*msgpackEncDriver)(nil)