msgpack.go 29 KB

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