msgpack.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. /*
  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. )
  24. const (
  25. mpPosFixNumMin byte = 0x00
  26. mpPosFixNumMax = 0x7f
  27. mpFixMapMin = 0x80
  28. mpFixMapMax = 0x8f
  29. mpFixArrayMin = 0x90
  30. mpFixArrayMax = 0x9f
  31. mpFixStrMin = 0xa0
  32. mpFixStrMax = 0xbf
  33. mpNil = 0xc0
  34. _ = 0xc1
  35. mpFalse = 0xc2
  36. mpTrue = 0xc3
  37. mpFloat = 0xca
  38. mpDouble = 0xcb
  39. mpUint8 = 0xcc
  40. mpUint16 = 0xcd
  41. mpUint32 = 0xce
  42. mpUint64 = 0xcf
  43. mpInt8 = 0xd0
  44. mpInt16 = 0xd1
  45. mpInt32 = 0xd2
  46. mpInt64 = 0xd3
  47. // extensions below
  48. mpBin8 = 0xc4
  49. mpBin16 = 0xc5
  50. mpBin32 = 0xc6
  51. mpExt8 = 0xc7
  52. mpExt16 = 0xc8
  53. mpExt32 = 0xc9
  54. mpFixExt1 = 0xd4
  55. mpFixExt2 = 0xd5
  56. mpFixExt4 = 0xd6
  57. mpFixExt8 = 0xd7
  58. mpFixExt16 = 0xd8
  59. mpStr8 = 0xd9 // new
  60. mpStr16 = 0xda
  61. mpStr32 = 0xdb
  62. mpArray16 = 0xdc
  63. mpArray32 = 0xdd
  64. mpMap16 = 0xde
  65. mpMap32 = 0xdf
  66. mpNegFixNumMin = 0xe0
  67. mpNegFixNumMax = 0xff
  68. )
  69. // MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
  70. // that the backend RPC service takes multiple arguments, which have been arranged
  71. // in sequence in the slice.
  72. //
  73. // The Codec then passes it AS-IS to the rpc service (without wrapping it in an
  74. // array of 1 element).
  75. type MsgpackSpecRpcMultiArgs []interface{}
  76. // A MsgpackContainer type specifies the different types of msgpackContainers.
  77. type msgpackContainerType struct {
  78. fixCutoff int
  79. bFixMin, b8, b16, b32 byte
  80. hasFixMin, has8, has8Always bool
  81. }
  82. var (
  83. msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false}
  84. msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true}
  85. msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false}
  86. msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false}
  87. )
  88. //---------------------------------------------
  89. type msgpackEncDriver struct {
  90. e *Encoder
  91. w encWriter
  92. h *MsgpackHandle
  93. noBuiltInTypes
  94. encNoSeparator
  95. x [8]byte
  96. }
  97. func (e *msgpackEncDriver) EncodeNil() {
  98. e.w.writen1(mpNil)
  99. }
  100. func (e *msgpackEncDriver) EncodeInt(i int64) {
  101. if i >= 0 {
  102. e.EncodeUint(uint64(i))
  103. } else if i >= -32 {
  104. e.w.writen1(byte(i))
  105. } else if i >= math.MinInt8 {
  106. e.w.writen2(mpInt8, byte(i))
  107. } else if i >= math.MinInt16 {
  108. e.w.writen1(mpInt16)
  109. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  110. } else if i >= math.MinInt32 {
  111. e.w.writen1(mpInt32)
  112. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  113. } else {
  114. e.w.writen1(mpInt64)
  115. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  116. }
  117. }
  118. func (e *msgpackEncDriver) EncodeUint(i uint64) {
  119. if i <= math.MaxInt8 {
  120. e.w.writen1(byte(i))
  121. } else if i <= math.MaxUint8 {
  122. e.w.writen2(mpUint8, byte(i))
  123. } else if i <= math.MaxUint16 {
  124. e.w.writen1(mpUint16)
  125. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  126. } else if i <= math.MaxUint32 {
  127. e.w.writen1(mpUint32)
  128. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  129. } else {
  130. e.w.writen1(mpUint64)
  131. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  132. }
  133. }
  134. func (e *msgpackEncDriver) EncodeBool(b bool) {
  135. if b {
  136. e.w.writen1(mpTrue)
  137. } else {
  138. e.w.writen1(mpFalse)
  139. }
  140. }
  141. func (e *msgpackEncDriver) EncodeFloat32(f float32) {
  142. e.w.writen1(mpFloat)
  143. bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f))
  144. }
  145. func (e *msgpackEncDriver) EncodeFloat64(f float64) {
  146. e.w.writen1(mpDouble)
  147. bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f))
  148. }
  149. func (e *msgpackEncDriver) EncodeExt(v interface{}, xtag uint64, ext Ext, _ *Encoder) {
  150. bs := ext.WriteExt(v)
  151. if bs == nil {
  152. e.EncodeNil()
  153. return
  154. }
  155. if e.h.WriteExt {
  156. e.encodeExtPreamble(uint8(xtag), len(bs))
  157. e.w.writeb(bs)
  158. } else {
  159. e.EncodeStringBytes(c_RAW, bs)
  160. }
  161. }
  162. func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  163. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  164. e.w.writeb(re.Data)
  165. }
  166. func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
  167. if l == 1 {
  168. e.w.writen2(mpFixExt1, xtag)
  169. } else if l == 2 {
  170. e.w.writen2(mpFixExt2, xtag)
  171. } else if l == 4 {
  172. e.w.writen2(mpFixExt4, xtag)
  173. } else if l == 8 {
  174. e.w.writen2(mpFixExt8, xtag)
  175. } else if l == 16 {
  176. e.w.writen2(mpFixExt16, xtag)
  177. } else if l < 256 {
  178. e.w.writen2(mpExt8, byte(l))
  179. e.w.writen1(xtag)
  180. } else if l < 65536 {
  181. e.w.writen1(mpExt16)
  182. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  183. e.w.writen1(xtag)
  184. } else {
  185. e.w.writen1(mpExt32)
  186. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  187. e.w.writen1(xtag)
  188. }
  189. }
  190. func (e *msgpackEncDriver) EncodeArrayStart(length int) {
  191. e.writeContainerLen(msgpackContainerList, length)
  192. }
  193. func (e *msgpackEncDriver) EncodeMapStart(length int) {
  194. e.writeContainerLen(msgpackContainerMap, length)
  195. }
  196. func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) {
  197. if c == c_RAW && e.h.WriteExt {
  198. e.writeContainerLen(msgpackContainerBin, len(s))
  199. } else {
  200. e.writeContainerLen(msgpackContainerStr, len(s))
  201. }
  202. if len(s) > 0 {
  203. e.w.writestr(s)
  204. }
  205. }
  206. func (e *msgpackEncDriver) EncodeSymbol(v string) {
  207. e.EncodeString(c_UTF8, v)
  208. }
  209. func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) {
  210. if c == c_RAW && e.h.WriteExt {
  211. e.writeContainerLen(msgpackContainerBin, len(bs))
  212. } else {
  213. e.writeContainerLen(msgpackContainerStr, len(bs))
  214. }
  215. if len(bs) > 0 {
  216. e.w.writeb(bs)
  217. }
  218. }
  219. func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
  220. if ct.hasFixMin && l < ct.fixCutoff {
  221. e.w.writen1(ct.bFixMin | byte(l))
  222. } else if ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt) {
  223. e.w.writen2(ct.b8, uint8(l))
  224. } else if l < 65536 {
  225. e.w.writen1(ct.b16)
  226. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  227. } else {
  228. e.w.writen1(ct.b32)
  229. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  230. }
  231. }
  232. //---------------------------------------------
  233. type msgpackDecDriver struct {
  234. d *Decoder
  235. r decReader // *Decoder decReader decReaderT
  236. h *MsgpackHandle
  237. b [scratchByteArrayLen]byte
  238. bd byte
  239. bdRead bool
  240. br bool // bytes reader
  241. bdType valueType
  242. noBuiltInTypes
  243. noStreamingCodec
  244. decNoSeparator
  245. }
  246. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  247. // or a containerType, or a specific type denoting nil or extension.
  248. // It is called when a nil interface{} is passed, leaving it up to the DecDriver
  249. // to introspect the stream and decide how best to decode.
  250. // It deciphers the value by looking at the stream first.
  251. func (d *msgpackDecDriver) DecodeNaked() (v interface{}, vt valueType, decodeFurther bool) {
  252. if !d.bdRead {
  253. d.readNextBd()
  254. }
  255. bd := d.bd
  256. switch bd {
  257. case mpNil:
  258. vt = valueTypeNil
  259. d.bdRead = false
  260. case mpFalse:
  261. vt = valueTypeBool
  262. v = false
  263. case mpTrue:
  264. vt = valueTypeBool
  265. v = true
  266. case mpFloat:
  267. vt = valueTypeFloat
  268. v = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  269. case mpDouble:
  270. vt = valueTypeFloat
  271. v = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  272. case mpUint8:
  273. vt = valueTypeUint
  274. v = uint64(d.r.readn1())
  275. case mpUint16:
  276. vt = valueTypeUint
  277. v = uint64(bigen.Uint16(d.r.readx(2)))
  278. case mpUint32:
  279. vt = valueTypeUint
  280. v = uint64(bigen.Uint32(d.r.readx(4)))
  281. case mpUint64:
  282. vt = valueTypeUint
  283. v = uint64(bigen.Uint64(d.r.readx(8)))
  284. case mpInt8:
  285. vt = valueTypeInt
  286. v = int64(int8(d.r.readn1()))
  287. case mpInt16:
  288. vt = valueTypeInt
  289. v = int64(int16(bigen.Uint16(d.r.readx(2))))
  290. case mpInt32:
  291. vt = valueTypeInt
  292. v = int64(int32(bigen.Uint32(d.r.readx(4))))
  293. case mpInt64:
  294. vt = valueTypeInt
  295. v = int64(int64(bigen.Uint64(d.r.readx(8))))
  296. default:
  297. switch {
  298. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  299. // positive fixnum (always signed)
  300. vt = valueTypeInt
  301. v = int64(int8(bd))
  302. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  303. // negative fixnum
  304. vt = valueTypeInt
  305. v = int64(int8(bd))
  306. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  307. if d.h.RawToString {
  308. var rvm string
  309. vt = valueTypeString
  310. v = &rvm
  311. } else {
  312. var rvm = zeroByteSlice
  313. vt = valueTypeBytes
  314. v = &rvm
  315. }
  316. decodeFurther = true
  317. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  318. var rvm = zeroByteSlice
  319. vt = valueTypeBytes
  320. v = &rvm
  321. decodeFurther = true
  322. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  323. vt = valueTypeArray
  324. decodeFurther = true
  325. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  326. vt = valueTypeMap
  327. decodeFurther = true
  328. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  329. clen := d.readExtLen()
  330. var re RawExt
  331. re.Tag = uint64(d.r.readn1())
  332. re.Data = d.r.readx(clen)
  333. v = &re
  334. vt = valueTypeExt
  335. default:
  336. d.d.errorf("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  337. return
  338. }
  339. }
  340. if !decodeFurther {
  341. d.bdRead = false
  342. }
  343. if vt == valueTypeUint && d.h.SignedInteger {
  344. d.bdType = valueTypeInt
  345. v = int64(v.(uint64))
  346. }
  347. return
  348. }
  349. // int can be decoded from msgpack type: intXXX or uintXXX
  350. func (d *msgpackDecDriver) DecodeInt(bitsize uint8) (i int64) {
  351. if !d.bdRead {
  352. d.readNextBd()
  353. }
  354. switch d.bd {
  355. case mpUint8:
  356. i = int64(uint64(d.r.readn1()))
  357. case mpUint16:
  358. i = int64(uint64(bigen.Uint16(d.r.readx(2))))
  359. case mpUint32:
  360. i = int64(uint64(bigen.Uint32(d.r.readx(4))))
  361. case mpUint64:
  362. i = int64(bigen.Uint64(d.r.readx(8)))
  363. case mpInt8:
  364. i = int64(int8(d.r.readn1()))
  365. case mpInt16:
  366. i = int64(int16(bigen.Uint16(d.r.readx(2))))
  367. case mpInt32:
  368. i = int64(int32(bigen.Uint32(d.r.readx(4))))
  369. case mpInt64:
  370. i = int64(bigen.Uint64(d.r.readx(8)))
  371. default:
  372. switch {
  373. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  374. i = int64(int8(d.bd))
  375. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  376. i = int64(int8(d.bd))
  377. default:
  378. d.d.errorf("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  379. return
  380. }
  381. }
  382. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  383. if bitsize > 0 {
  384. if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
  385. d.d.errorf("Overflow int value: %v", i)
  386. return
  387. }
  388. }
  389. d.bdRead = false
  390. return
  391. }
  392. // uint can be decoded from msgpack type: intXXX or uintXXX
  393. func (d *msgpackDecDriver) DecodeUint(bitsize uint8) (ui uint64) {
  394. if !d.bdRead {
  395. d.readNextBd()
  396. }
  397. switch d.bd {
  398. case mpUint8:
  399. ui = uint64(d.r.readn1())
  400. case mpUint16:
  401. ui = uint64(bigen.Uint16(d.r.readx(2)))
  402. case mpUint32:
  403. ui = uint64(bigen.Uint32(d.r.readx(4)))
  404. case mpUint64:
  405. ui = bigen.Uint64(d.r.readx(8))
  406. case mpInt8:
  407. if i := int64(int8(d.r.readn1())); i >= 0 {
  408. ui = uint64(i)
  409. } else {
  410. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  411. return
  412. }
  413. case mpInt16:
  414. if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 {
  415. ui = uint64(i)
  416. } else {
  417. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  418. return
  419. }
  420. case mpInt32:
  421. if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 {
  422. ui = uint64(i)
  423. } else {
  424. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  425. return
  426. }
  427. case mpInt64:
  428. if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 {
  429. ui = uint64(i)
  430. } else {
  431. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  432. return
  433. }
  434. default:
  435. switch {
  436. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  437. ui = uint64(d.bd)
  438. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  439. d.d.errorf("Assigning negative signed value: %v, to unsigned type", int(d.bd))
  440. return
  441. default:
  442. d.d.errorf("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  443. return
  444. }
  445. }
  446. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  447. if bitsize > 0 {
  448. if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
  449. d.d.errorf("Overflow uint value: %v", ui)
  450. return
  451. }
  452. }
  453. d.bdRead = false
  454. return
  455. }
  456. // float can either be decoded from msgpack type: float, double or intX
  457. func (d *msgpackDecDriver) DecodeFloat(chkOverflow32 bool) (f float64) {
  458. if !d.bdRead {
  459. d.readNextBd()
  460. }
  461. if d.bd == mpFloat {
  462. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  463. } else if d.bd == mpDouble {
  464. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  465. } else {
  466. f = float64(d.DecodeInt(0))
  467. }
  468. if chkOverflow32 && chkOvf.Float32(f) {
  469. d.d.errorf("msgpack: float32 overflow: %v", f)
  470. return
  471. }
  472. d.bdRead = false
  473. return
  474. }
  475. // bool can be decoded from bool, fixnum 0 or 1.
  476. func (d *msgpackDecDriver) DecodeBool() (b bool) {
  477. if !d.bdRead {
  478. d.readNextBd()
  479. }
  480. if d.bd == mpFalse || d.bd == 0 {
  481. // b = false
  482. } else if d.bd == mpTrue || d.bd == 1 {
  483. b = true
  484. } else {
  485. d.d.errorf("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  486. return
  487. }
  488. d.bdRead = false
  489. return
  490. }
  491. func (d *msgpackDecDriver) DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte) {
  492. if !d.bdRead {
  493. d.readNextBd()
  494. }
  495. var clen int
  496. // ignore isstring. Expect that the bytes may be found from msgpackContainerStr or msgpackContainerBin
  497. if bd := d.bd; bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  498. clen = d.readContainerLen(msgpackContainerBin)
  499. } else {
  500. clen = d.readContainerLen(msgpackContainerStr)
  501. }
  502. // println("DecodeBytes: clen: ", clen)
  503. d.bdRead = false
  504. // bytes may be nil, so handle it. if nil, clen=-1.
  505. if clen < 0 {
  506. return nil
  507. }
  508. if zerocopy {
  509. if d.br {
  510. return d.r.readx(clen)
  511. } else if len(bs) == 0 {
  512. bs = d.b[:]
  513. }
  514. }
  515. return decByteSlice(d.r, clen, bs)
  516. }
  517. func (d *msgpackDecDriver) DecodeString() (s string) {
  518. return string(d.DecodeBytes(d.b[:], true, true))
  519. }
  520. func (d *msgpackDecDriver) readNextBd() {
  521. d.bd = d.r.readn1()
  522. d.bdRead = true
  523. d.bdType = valueTypeUnset
  524. }
  525. func (d *msgpackDecDriver) IsContainerType(vt valueType) bool {
  526. bd := d.bd
  527. switch vt {
  528. case valueTypeNil:
  529. return bd == mpNil
  530. case valueTypeBytes:
  531. return bd == mpBin8 || bd == mpBin16 || bd == mpBin32 ||
  532. (!d.h.RawToString &&
  533. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax)))
  534. case valueTypeString:
  535. return d.h.RawToString &&
  536. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax))
  537. case valueTypeArray:
  538. return bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax)
  539. case valueTypeMap:
  540. return bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax)
  541. }
  542. d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  543. return false // "unreachable"
  544. }
  545. func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) {
  546. if !d.bdRead {
  547. d.readNextBd()
  548. }
  549. if d.bd == mpNil {
  550. d.bdRead = false
  551. v = true
  552. }
  553. return
  554. }
  555. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  556. bd := d.bd
  557. if bd == mpNil {
  558. clen = -1 // to represent nil
  559. } else if bd == ct.b8 {
  560. clen = int(d.r.readn1())
  561. } else if bd == ct.b16 {
  562. clen = int(bigen.Uint16(d.r.readx(2)))
  563. } else if bd == ct.b32 {
  564. clen = int(bigen.Uint32(d.r.readx(4)))
  565. } else if (ct.bFixMin & bd) == ct.bFixMin {
  566. clen = int(ct.bFixMin ^ bd)
  567. } else {
  568. d.d.errorf("readContainerLen: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
  569. return
  570. }
  571. d.bdRead = false
  572. return
  573. }
  574. func (d *msgpackDecDriver) ReadMapStart() int {
  575. return d.readContainerLen(msgpackContainerMap)
  576. }
  577. func (d *msgpackDecDriver) ReadArrayStart() int {
  578. return d.readContainerLen(msgpackContainerList)
  579. }
  580. func (d *msgpackDecDriver) readExtLen() (clen int) {
  581. switch d.bd {
  582. case mpNil:
  583. clen = -1 // to represent nil
  584. case mpFixExt1:
  585. clen = 1
  586. case mpFixExt2:
  587. clen = 2
  588. case mpFixExt4:
  589. clen = 4
  590. case mpFixExt8:
  591. clen = 8
  592. case mpFixExt16:
  593. clen = 16
  594. case mpExt8:
  595. clen = int(d.r.readn1())
  596. case mpExt16:
  597. clen = int(bigen.Uint16(d.r.readx(2)))
  598. case mpExt32:
  599. clen = int(bigen.Uint32(d.r.readx(4)))
  600. default:
  601. d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
  602. return
  603. }
  604. return
  605. }
  606. func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  607. if xtag > 0xff {
  608. d.d.errorf("decodeExt: tag must be <= 0xff; got: %v", xtag)
  609. return
  610. }
  611. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  612. realxtag = uint64(realxtag1)
  613. if ext == nil {
  614. re := rv.(*RawExt)
  615. re.Tag = realxtag
  616. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  617. } else {
  618. ext.ReadExt(rv, xbs)
  619. }
  620. return
  621. }
  622. func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  623. if !d.bdRead {
  624. d.readNextBd()
  625. }
  626. xbd := d.bd
  627. if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 {
  628. xbs = d.DecodeBytes(nil, false, true)
  629. } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 ||
  630. (xbd >= mpFixStrMin && xbd <= mpFixStrMax) {
  631. xbs = d.DecodeBytes(nil, true, true)
  632. } else {
  633. clen := d.readExtLen()
  634. xtag = d.r.readn1()
  635. if verifyTag && xtag != tag {
  636. d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  637. return
  638. }
  639. xbs = d.r.readx(clen)
  640. }
  641. d.bdRead = false
  642. return
  643. }
  644. //--------------------------------------------------
  645. //MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
  646. type MsgpackHandle struct {
  647. BasicHandle
  648. binaryEncodingType
  649. // RawToString controls how raw bytes are decoded into a nil interface{}.
  650. RawToString bool
  651. // WriteExt flag supports encoding configured extensions with extension tags.
  652. // It also controls whether other elements of the new spec are encoded (ie Str8).
  653. //
  654. // With WriteExt=false, configured extensions are serialized as raw bytes
  655. // and Str8 is not encoded.
  656. //
  657. // A stream can still be decoded into a typed value, provided an appropriate value
  658. // is provided, but the type cannot be inferred from the stream. If no appropriate
  659. // type is provided (e.g. decoding into a nil interface{}), you get back
  660. // a []byte or string based on the setting of RawToString.
  661. WriteExt bool
  662. }
  663. func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver {
  664. return &msgpackEncDriver{e: e, w: e.w, h: h}
  665. }
  666. func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver {
  667. return &msgpackDecDriver{d: d, r: d.r, h: h, br: d.bytes}
  668. }
  669. func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  670. return h.SetExt(rt, tag, &setExtWrapper{b: ext})
  671. }
  672. //--------------------------------------------------
  673. type msgpackSpecRpcCodec struct {
  674. rpcCodec
  675. }
  676. // /////////////// Spec RPC Codec ///////////////////
  677. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  678. // WriteRequest can write to both a Go service, and other services that do
  679. // not abide by the 1 argument rule of a Go service.
  680. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  681. var bodyArr []interface{}
  682. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  683. bodyArr = ([]interface{})(m)
  684. } else {
  685. bodyArr = []interface{}{body}
  686. }
  687. r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
  688. return c.write(r2, nil, false, true)
  689. }
  690. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  691. var moe interface{}
  692. if r.Error != "" {
  693. moe = r.Error
  694. }
  695. if moe != nil && body != nil {
  696. body = nil
  697. }
  698. r2 := []interface{}{1, uint32(r.Seq), moe, body}
  699. return c.write(r2, nil, false, true)
  700. }
  701. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  702. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  703. }
  704. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  705. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  706. }
  707. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  708. if body == nil { // read and discard
  709. return c.read(nil)
  710. }
  711. bodyArr := []interface{}{body}
  712. return c.read(&bodyArr)
  713. }
  714. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  715. if c.isClosed() {
  716. return io.EOF
  717. }
  718. // We read the response header by hand
  719. // so that the body can be decoded on its own from the stream at a later time.
  720. const fia byte = 0x94 //four item array descriptor value
  721. // Not sure why the panic of EOF is swallowed above.
  722. // if bs1 := c.dec.r.readn1(); bs1 != fia {
  723. // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
  724. // return
  725. // }
  726. var b byte
  727. b, err = c.br.ReadByte()
  728. if err != nil {
  729. return
  730. }
  731. if b != fia {
  732. err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, b)
  733. return
  734. }
  735. if err = c.read(&b); err != nil {
  736. return
  737. }
  738. if b != expectTypeByte {
  739. err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
  740. return
  741. }
  742. if err = c.read(msgid); err != nil {
  743. return
  744. }
  745. if err = c.read(methodOrError); err != nil {
  746. return
  747. }
  748. return
  749. }
  750. //--------------------------------------------------
  751. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  752. // as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  753. type msgpackSpecRpc struct{}
  754. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  755. // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
  756. // Its methods (ServerCodec and ClientCodec) return values that implement RpcCodecBuffered.
  757. var MsgpackSpecRpc msgpackSpecRpc
  758. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  759. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  760. }
  761. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  762. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  763. }
  764. var _ decDriver = (*msgpackDecDriver)(nil)
  765. var _ encDriver = (*msgpackEncDriver)(nil)