msgpack.go 22 KB

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