msgpack.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. // Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license found in the LICENSE file.
  3. package codec
  4. import (
  5. "fmt"
  6. "io"
  7. "math"
  8. "net/rpc"
  9. "reflect"
  10. "time"
  11. )
  12. const (
  13. mpPosFixNumMin byte = 0x00
  14. mpPosFixNumMax = 0x7f
  15. mpFixMapMin = 0x80
  16. mpFixMapMax = 0x8f
  17. mpFixArrayMin = 0x90
  18. mpFixArrayMax = 0x9f
  19. mpFixStrMin = 0xa0
  20. mpFixStrMax = 0xbf
  21. mpNil = 0xc0
  22. _ = 0xc1
  23. mpFalse = 0xc2
  24. mpTrue = 0xc3
  25. mpFloat = 0xca
  26. mpDouble = 0xcb
  27. mpUint8 = 0xcc
  28. mpUint16 = 0xcd
  29. mpUint32 = 0xce
  30. mpUint64 = 0xcf
  31. mpInt8 = 0xd0
  32. mpInt16 = 0xd1
  33. mpInt32 = 0xd2
  34. mpInt64 = 0xd3
  35. // extensions below
  36. mpBin8 = 0xc4
  37. mpBin16 = 0xc5
  38. mpBin32 = 0xc6
  39. mpExt8 = 0xc7
  40. mpExt16 = 0xc8
  41. mpExt32 = 0xc9
  42. mpFixExt1 = 0xd4
  43. mpFixExt2 = 0xd5
  44. mpFixExt4 = 0xd6
  45. mpFixExt8 = 0xd7
  46. mpFixExt16 = 0xd8
  47. mpStr8 = 0xd9 // new
  48. mpStr16 = 0xda
  49. mpStr32 = 0xdb
  50. mpArray16 = 0xdc
  51. mpArray32 = 0xdd
  52. mpMap16 = 0xde
  53. mpMap32 = 0xdf
  54. mpNegFixNumMin = 0xe0
  55. mpNegFixNumMax = 0xff
  56. )
  57. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  58. // the msgpack spec at http://wiki.msgpack.org/display/MSGPACK/RPC+specification
  59. var MsgpackSpecRpc msgpackSpecRpc
  60. // MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
  61. // that the backend RPC service takes multiple arguments, which have been arranged
  62. // in sequence in the slice.
  63. //
  64. // The Codec then passes it AS-IS to the rpc service (without wrapping it in an
  65. // array of 1 element).
  66. type MsgpackSpecRpcMultiArgs []interface{}
  67. // A MsgpackContainer type specifies the different types of msgpackContainers.
  68. type msgpackContainerType struct {
  69. fixCutoff int
  70. bFixMin, b8, b16, b32 byte
  71. hasFixMin, has8, has8Always bool
  72. }
  73. var (
  74. msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false}
  75. msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true}
  76. msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false}
  77. msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false}
  78. )
  79. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  80. // as defined in the msgpack spec at http://wiki.msgpack.org/display/MSGPACK/RPC+specification
  81. type msgpackSpecRpc struct{}
  82. type msgpackSpecRpcCodec struct {
  83. rpcCodec
  84. }
  85. //MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
  86. type MsgpackHandle struct {
  87. // RawToString controls how raw bytes are decoded into a nil interface{}.
  88. RawToString bool
  89. // WriteExt flag supports encoding configured extensions with extension tags.
  90. // It also controls whether other elements of the new spec are encoded (ie Str8).
  91. //
  92. // With WriteExt=false, configured extensions are serialized as raw bytes
  93. // and Str8 is not encoded.
  94. //
  95. // A stream can still be decoded into a typed value, provided an appropriate value
  96. // is provided, but the type cannot be inferred from the stream. If no appropriate
  97. // type is provided (e.g. decoding into a nil interface{}), you get back
  98. // a []byte or string based on the setting of RawToString.
  99. WriteExt bool
  100. extHandle
  101. EncodeOptions
  102. DecodeOptions
  103. }
  104. type msgpackEncDriver struct {
  105. w encWriter
  106. h *MsgpackHandle
  107. }
  108. type msgpackDecDriver struct {
  109. r decReader
  110. h *MsgpackHandle
  111. bd byte
  112. bdRead bool
  113. bdType decodeEncodedType
  114. }
  115. func (e *msgpackEncDriver) isBuiltinType(rt uintptr) bool {
  116. //no builtin types. All encodings are based on kinds. Types supported as extensions.
  117. return false
  118. }
  119. func (e *msgpackEncDriver) encodeBuiltinType(rt uintptr, rv reflect.Value) {}
  120. func (e *msgpackEncDriver) encodeNil() {
  121. e.w.writen1(mpNil)
  122. }
  123. func (e *msgpackEncDriver) encodeInt(i int64) {
  124. switch {
  125. case i >= -32 && i <= math.MaxInt8:
  126. e.w.writen1(byte(i))
  127. case i < -32 && i >= math.MinInt8:
  128. e.w.writen2(mpInt8, byte(i))
  129. case i >= math.MinInt16 && i <= math.MaxInt16:
  130. e.w.writen1(mpInt16)
  131. e.w.writeUint16(uint16(i))
  132. case i >= math.MinInt32 && i <= math.MaxInt32:
  133. e.w.writen1(mpInt32)
  134. e.w.writeUint32(uint32(i))
  135. case i >= math.MinInt64 && i <= math.MaxInt64:
  136. e.w.writen1(mpInt64)
  137. e.w.writeUint64(uint64(i))
  138. default:
  139. encErr("encInt64: Unreachable block")
  140. }
  141. }
  142. func (e *msgpackEncDriver) encodeUint(i uint64) {
  143. // uints are not fixnums. fixnums are always signed.
  144. // case i <= math.MaxInt8:
  145. // e.w.writen1(byte(i))
  146. switch {
  147. case i <= math.MaxUint8:
  148. e.w.writen2(mpUint8, byte(i))
  149. case i <= math.MaxUint16:
  150. e.w.writen1(mpUint16)
  151. e.w.writeUint16(uint16(i))
  152. case i <= math.MaxUint32:
  153. e.w.writen1(mpUint32)
  154. e.w.writeUint32(uint32(i))
  155. default:
  156. e.w.writen1(mpUint64)
  157. e.w.writeUint64(uint64(i))
  158. }
  159. }
  160. func (e *msgpackEncDriver) encodeBool(b bool) {
  161. if b {
  162. e.w.writen1(mpTrue)
  163. } else {
  164. e.w.writen1(mpFalse)
  165. }
  166. }
  167. func (e *msgpackEncDriver) encodeFloat32(f float32) {
  168. e.w.writen1(mpFloat)
  169. e.w.writeUint32(math.Float32bits(f))
  170. }
  171. func (e *msgpackEncDriver) encodeFloat64(f float64) {
  172. e.w.writen1(mpDouble)
  173. e.w.writeUint64(math.Float64bits(f))
  174. }
  175. func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
  176. switch {
  177. case l == 1:
  178. e.w.writen2(mpFixExt1, xtag)
  179. case l == 2:
  180. e.w.writen2(mpFixExt2, xtag)
  181. case l == 4:
  182. e.w.writen2(mpFixExt4, xtag)
  183. case l == 8:
  184. e.w.writen2(mpFixExt8, xtag)
  185. case l == 16:
  186. e.w.writen2(mpFixExt16, xtag)
  187. case l < 256:
  188. e.w.writen2(mpExt8, byte(l))
  189. e.w.writen1(xtag)
  190. case l < 65536:
  191. e.w.writen1(mpExt16)
  192. e.w.writeUint16(uint16(l))
  193. e.w.writen1(xtag)
  194. default:
  195. e.w.writen1(mpExt32)
  196. e.w.writeUint32(uint32(l))
  197. e.w.writen1(xtag)
  198. }
  199. }
  200. func (e *msgpackEncDriver) encodeArrayPreamble(length int) {
  201. e.writeContainerLen(msgpackContainerList, length)
  202. }
  203. func (e *msgpackEncDriver) encodeMapPreamble(length int) {
  204. e.writeContainerLen(msgpackContainerMap, length)
  205. }
  206. func (e *msgpackEncDriver) encodeString(c charEncoding, s string) {
  207. if c == c_RAW && e.h.WriteExt {
  208. e.writeContainerLen(msgpackContainerBin, len(s))
  209. } else {
  210. e.writeContainerLen(msgpackContainerStr, len(s))
  211. }
  212. if len(s) > 0 {
  213. e.w.writestr(s)
  214. }
  215. }
  216. func (e *msgpackEncDriver) encodeSymbol(v string) {
  217. e.encodeString(c_UTF8, v)
  218. }
  219. func (e *msgpackEncDriver) encodeStringBytes(c charEncoding, bs []byte) {
  220. if c == c_RAW && e.h.WriteExt {
  221. e.writeContainerLen(msgpackContainerBin, len(bs))
  222. } else {
  223. e.writeContainerLen(msgpackContainerStr, len(bs))
  224. }
  225. if len(bs) > 0 {
  226. e.w.writeb(bs)
  227. }
  228. }
  229. func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
  230. switch {
  231. case ct.hasFixMin && l < ct.fixCutoff:
  232. e.w.writen1(ct.bFixMin | byte(l))
  233. case ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt):
  234. e.w.writen2(ct.b8, uint8(l))
  235. case l < 65536:
  236. e.w.writen1(ct.b16)
  237. e.w.writeUint16(uint16(l))
  238. default:
  239. e.w.writen1(ct.b32)
  240. e.w.writeUint32(uint32(l))
  241. }
  242. }
  243. //---------------------------------------------
  244. func (d *msgpackDecDriver) isBuiltinType(rt uintptr) bool {
  245. //no builtin types. All encodings are based on kinds. Types supported as extensions.
  246. return false
  247. }
  248. func (d *msgpackDecDriver) decodeBuiltinType(rt uintptr, rv reflect.Value) {}
  249. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  250. // or a containerType, or a specific type denoting nil or extension.
  251. // It is called when a nil interface{} is passed, leaving it up to the DecDriver
  252. // to introspect the stream and decide how best to decode.
  253. // It deciphers the value by looking at the stream first.
  254. func (d *msgpackDecDriver) decodeNaked() (rv reflect.Value, ctx decodeNakedContext) {
  255. d.initReadNext()
  256. bd := d.bd
  257. var v interface{}
  258. switch bd {
  259. case mpNil:
  260. ctx = dncNil
  261. d.bdRead = false
  262. case mpFalse:
  263. v = false
  264. case mpTrue:
  265. v = true
  266. case mpFloat:
  267. v = float64(math.Float32frombits(d.r.readUint32()))
  268. case mpDouble:
  269. v = math.Float64frombits(d.r.readUint64())
  270. case mpUint8:
  271. v = uint64(d.r.readn1())
  272. case mpUint16:
  273. v = uint64(d.r.readUint16())
  274. case mpUint32:
  275. v = uint64(d.r.readUint32())
  276. case mpUint64:
  277. v = uint64(d.r.readUint64())
  278. case mpInt8:
  279. v = int64(int8(d.r.readn1()))
  280. case mpInt16:
  281. v = int64(int16(d.r.readUint16()))
  282. case mpInt32:
  283. v = int64(int32(d.r.readUint32()))
  284. case mpInt64:
  285. v = int64(int64(d.r.readUint64()))
  286. default:
  287. switch {
  288. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  289. // positive fixnum (always signed)
  290. v = int64(int8(bd))
  291. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  292. // negative fixnum
  293. v = int64(int8(bd))
  294. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  295. ctx = dncContainer
  296. // v = containerRaw
  297. if d.h.RawToString {
  298. var rvm string
  299. rv = reflect.ValueOf(&rvm).Elem()
  300. } else {
  301. rvm := []byte{}
  302. rv = reflect.ValueOf(&rvm).Elem()
  303. //rv = reflect.New(byteSliceTyp).Elem() // Use New, not Zero, so it's settable
  304. }
  305. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  306. ctx = dncContainer
  307. rvm := []byte{}
  308. rv = reflect.ValueOf(&rvm).Elem()
  309. // rv = reflect.New(byteSliceTyp).Elem()
  310. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  311. ctx = dncContainer
  312. // v = containerList
  313. if d.h.SliceType == nil {
  314. rv = reflect.New(intfSliceTyp).Elem()
  315. } else {
  316. rv = reflect.New(d.h.SliceType).Elem()
  317. }
  318. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  319. ctx = dncContainer
  320. // v = containerMap
  321. if d.h.MapType == nil {
  322. rv = reflect.MakeMap(mapIntfIntfTyp)
  323. } else {
  324. rv = reflect.MakeMap(d.h.MapType)
  325. }
  326. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  327. //ctx = dncExt
  328. clen := d.readExtLen()
  329. xtag := d.r.readn1()
  330. var bfn func(reflect.Value, []byte) error
  331. rv, bfn = d.h.getDecodeExtForTag(xtag)
  332. if bfn == nil {
  333. decErr("Unable to find type mapped to extension tag: %v", xtag)
  334. }
  335. if fnerr := bfn(rv, d.r.readn(clen)); fnerr != nil {
  336. panic(fnerr)
  337. }
  338. default:
  339. decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  340. }
  341. }
  342. if ctx == dncHandled {
  343. d.bdRead = false
  344. if v != nil {
  345. rv = reflect.ValueOf(v)
  346. }
  347. }
  348. return
  349. }
  350. // int can be decoded from msgpack type: intXXX or uintXXX
  351. func (d *msgpackDecDriver) decodeInt(bitsize uint8) (i int64) {
  352. switch d.bd {
  353. case mpUint8:
  354. i = int64(uint64(d.r.readn1()))
  355. case mpUint16:
  356. i = int64(uint64(d.r.readUint16()))
  357. case mpUint32:
  358. i = int64(uint64(d.r.readUint32()))
  359. case mpUint64:
  360. i = int64(d.r.readUint64())
  361. case mpInt8:
  362. i = int64(int8(d.r.readn1()))
  363. case mpInt16:
  364. i = int64(int16(d.r.readUint16()))
  365. case mpInt32:
  366. i = int64(int32(d.r.readUint32()))
  367. case mpInt64:
  368. i = int64(d.r.readUint64())
  369. default:
  370. switch {
  371. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  372. i = int64(int8(d.bd))
  373. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  374. i = int64(int8(d.bd))
  375. default:
  376. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  377. }
  378. }
  379. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  380. if bitsize > 0 {
  381. if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
  382. decErr("Overflow int value: %v", i)
  383. }
  384. }
  385. d.bdRead = false
  386. return
  387. }
  388. // uint can be decoded from msgpack type: intXXX or uintXXX
  389. func (d *msgpackDecDriver) decodeUint(bitsize uint8) (ui uint64) {
  390. switch d.bd {
  391. case mpUint8:
  392. ui = uint64(d.r.readn1())
  393. case mpUint16:
  394. ui = uint64(d.r.readUint16())
  395. case mpUint32:
  396. ui = uint64(d.r.readUint32())
  397. case mpUint64:
  398. ui = d.r.readUint64()
  399. case mpInt8:
  400. if i := int64(int8(d.r.readn1())); i >= 0 {
  401. ui = uint64(i)
  402. } else {
  403. decErr("Assigning negative signed value: %v, to unsigned type", i)
  404. }
  405. case mpInt16:
  406. if i := int64(int16(d.r.readUint16())); i >= 0 {
  407. ui = uint64(i)
  408. } else {
  409. decErr("Assigning negative signed value: %v, to unsigned type", i)
  410. }
  411. case mpInt32:
  412. if i := int64(int32(d.r.readUint32())); i >= 0 {
  413. ui = uint64(i)
  414. } else {
  415. decErr("Assigning negative signed value: %v, to unsigned type", i)
  416. }
  417. case mpInt64:
  418. if i := int64(d.r.readUint64()); i >= 0 {
  419. ui = uint64(i)
  420. } else {
  421. decErr("Assigning negative signed value: %v, to unsigned type", i)
  422. }
  423. default:
  424. switch {
  425. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  426. ui = uint64(d.bd)
  427. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  428. decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd))
  429. default:
  430. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  431. }
  432. }
  433. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  434. if bitsize > 0 {
  435. if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
  436. decErr("Overflow uint value: %v", ui)
  437. }
  438. }
  439. d.bdRead = false
  440. return
  441. }
  442. // float can either be decoded from msgpack type: float, double or intX
  443. func (d *msgpackDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
  444. switch d.bd {
  445. case mpFloat:
  446. f = float64(math.Float32frombits(d.r.readUint32()))
  447. case mpDouble:
  448. f = math.Float64frombits(d.r.readUint64())
  449. default:
  450. f = float64(d.decodeInt(0))
  451. }
  452. // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
  453. if chkOverflow32 {
  454. f2 := f
  455. if f2 < 0 {
  456. f2 = -f
  457. }
  458. if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
  459. decErr("Overflow float32 value: %v", f2)
  460. }
  461. }
  462. d.bdRead = false
  463. return
  464. }
  465. // bool can be decoded from bool, fixnum 0 or 1.
  466. func (d *msgpackDecDriver) decodeBool() (b bool) {
  467. switch d.bd {
  468. case mpFalse, 0:
  469. // b = false
  470. case mpTrue, 1:
  471. b = true
  472. default:
  473. decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  474. }
  475. d.bdRead = false
  476. return
  477. }
  478. func (d *msgpackDecDriver) decodeString() (s string) {
  479. clen := d.readContainerLen(msgpackContainerStr)
  480. if clen > 0 {
  481. s = string(d.r.readn(clen))
  482. }
  483. d.bdRead = false
  484. return
  485. }
  486. // Callers must check if changed=true (to decide whether to replace the one they have)
  487. func (d *msgpackDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
  488. // bytes can be decoded from msgpackContainerStr or msgpackContainerBin
  489. var clen int
  490. switch d.bd {
  491. case mpBin8, mpBin16, mpBin32:
  492. clen = d.readContainerLen(msgpackContainerBin)
  493. default:
  494. clen = d.readContainerLen(msgpackContainerStr)
  495. }
  496. // if clen < 0 {
  497. // changed = true
  498. // panic("length cannot be zero. this cannot be nil.")
  499. // }
  500. if clen > 0 {
  501. // if no contents in stream, don't update the passed byteslice
  502. if len(bs) != clen {
  503. // Return changed=true if length of passed slice diff from length of bytes in stream
  504. if len(bs) > clen {
  505. bs = bs[:clen]
  506. } else {
  507. bs = make([]byte, clen)
  508. }
  509. bsOut = bs
  510. changed = true
  511. }
  512. d.r.readb(bs)
  513. }
  514. d.bdRead = false
  515. return
  516. }
  517. // Every top-level decode funcs (i.e. decodeValue, decode) must call this first.
  518. func (d *msgpackDecDriver) initReadNext() {
  519. if d.bdRead {
  520. return
  521. }
  522. d.bd = d.r.readn1()
  523. d.bdRead = true
  524. d.bdType = detUnset
  525. }
  526. func (d *msgpackDecDriver) currentEncodedType() decodeEncodedType {
  527. if d.bdType == detUnset {
  528. bd := d.bd
  529. switch bd {
  530. case mpNil:
  531. d.bdType = detNil
  532. case mpFalse, mpTrue:
  533. d.bdType = detBool
  534. case mpFloat, mpDouble:
  535. d.bdType = detFloat
  536. case mpUint8, mpUint16, mpUint32, mpUint64:
  537. d.bdType = detUint
  538. case mpInt8, mpInt16, mpInt32, mpInt64:
  539. d.bdType = detInt
  540. default:
  541. switch {
  542. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  543. d.bdType = detInt
  544. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  545. d.bdType = detInt
  546. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  547. if d.h.RawToString {
  548. d.bdType = detString
  549. } else {
  550. d.bdType = detBytes
  551. }
  552. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  553. d.bdType = detBytes
  554. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  555. d.bdType = detArray
  556. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  557. d.bdType = detMap
  558. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  559. d.bdType = detExt
  560. default:
  561. decErr("currentEncodedType: Undeciphered descriptor: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  562. }
  563. }
  564. }
  565. return d.bdType
  566. }
  567. func (d *msgpackDecDriver) tryDecodeAsNil() bool {
  568. if d.bd == mpNil {
  569. d.bdRead = false
  570. return true
  571. }
  572. return false
  573. }
  574. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  575. bd := d.bd
  576. switch {
  577. case bd == mpNil:
  578. clen = -1 // to represent nil
  579. case bd == ct.b8:
  580. clen = int(d.r.readn1())
  581. case bd == ct.b16:
  582. clen = int(d.r.readUint16())
  583. case bd == ct.b32:
  584. clen = int(d.r.readUint32())
  585. case (ct.bFixMin & bd) == ct.bFixMin:
  586. clen = int(ct.bFixMin ^ bd)
  587. default:
  588. decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  589. }
  590. d.bdRead = false
  591. return
  592. }
  593. func (d *msgpackDecDriver) readMapLen() int {
  594. return d.readContainerLen(msgpackContainerMap)
  595. }
  596. func (d *msgpackDecDriver) readArrayLen() int {
  597. return d.readContainerLen(msgpackContainerList)
  598. }
  599. func (d *msgpackDecDriver) readExtLen() (clen int) {
  600. switch d.bd {
  601. case mpNil:
  602. clen = -1 // to represent nil
  603. case mpFixExt1:
  604. clen = 1
  605. case mpFixExt2:
  606. clen = 2
  607. case mpFixExt4:
  608. clen = 4
  609. case mpFixExt8:
  610. clen = 8
  611. case mpFixExt16:
  612. clen = 16
  613. case mpExt8:
  614. clen = int(d.r.readn1())
  615. case mpExt16:
  616. clen = int(d.r.readUint16())
  617. case mpExt32:
  618. clen = int(d.r.readUint32())
  619. default:
  620. decErr("decoding ext bytes: found unexpected byte: %x", d.bd)
  621. }
  622. return
  623. }
  624. func (d *msgpackDecDriver) decodeExt(tag byte) (xbs []byte) {
  625. xbd := d.bd
  626. switch {
  627. case xbd == mpBin8, xbd == mpBin16, xbd == mpBin32:
  628. xbs, _ = d.decodeBytes(nil)
  629. case xbd == mpStr8, xbd == mpStr16, xbd == mpStr32,
  630. xbd >= mpFixStrMin && xbd <= mpFixStrMax:
  631. xbs = []byte(d.decodeString())
  632. default:
  633. clen := d.readExtLen()
  634. if xtag := d.r.readn1(); xtag != tag {
  635. decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  636. }
  637. xbs = d.r.readn(clen)
  638. }
  639. d.bdRead = false
  640. return
  641. }
  642. //--------------------------------------------------
  643. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  644. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  645. }
  646. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  647. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  648. }
  649. // /////////////// Spec RPC Codec ///////////////////
  650. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  651. // WriteRequest can write to both a Go service, and other services that do
  652. // not abide by the 1 argument rule of a Go service.
  653. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  654. var bodyArr []interface{}
  655. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  656. bodyArr = ([]interface{})(m)
  657. } else {
  658. bodyArr = []interface{}{body}
  659. }
  660. r2 := []interface{}{ 0, uint32(r.Seq), r.ServiceMethod, bodyArr }
  661. return c.write(r2, nil, false, true)
  662. }
  663. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  664. var moe interface{}
  665. if r.Error != "" {
  666. moe = r.Error
  667. }
  668. if moe != nil && body != nil {
  669. body = nil
  670. }
  671. r2 := []interface{}{ 1, uint32(r.Seq), moe, body }
  672. return c.write(r2, nil, false, true)
  673. }
  674. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  675. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  676. }
  677. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  678. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  679. }
  680. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  681. if body == nil { // read and discard
  682. return c.read(nil)
  683. }
  684. bodyArr := []interface{}{body}
  685. return c.read(&bodyArr)
  686. }
  687. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  688. // We read the response header by hand
  689. // so that the body can be decoded on its own from the stream at a later time.
  690. bs := make([]byte, 1)
  691. n, err := c.rwc.Read(bs)
  692. if err != nil {
  693. return
  694. }
  695. if n != 1 {
  696. err = fmt.Errorf("Couldn't read array descriptor: No bytes read")
  697. return
  698. }
  699. const fia byte = 0x94 //four item array descriptor value
  700. if bs[0] != fia {
  701. err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs[0])
  702. return
  703. }
  704. var b byte
  705. if err = c.read(&b); err != nil {
  706. return
  707. }
  708. if b != expectTypeByte {
  709. err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
  710. return
  711. }
  712. if err = c.read(msgid); err != nil {
  713. return
  714. }
  715. if err = c.read(methodOrError); err != nil {
  716. return
  717. }
  718. return
  719. }
  720. //--------------------------------------------------
  721. // TimeEncodeExt encodes a time.Time as a byte slice.
  722. // Configure this to support the Time Extension, e.g. using tag 1.
  723. func (_ *MsgpackHandle) TimeEncodeExt(rv reflect.Value) (bs []byte, err error) {
  724. rvi := rv.Interface()
  725. switch iv := rvi.(type) {
  726. case time.Time:
  727. bs = encodeTime(iv)
  728. default:
  729. err = fmt.Errorf("codec/msgpack: TimeEncodeExt expects a time.Time. Received %T", rvi)
  730. }
  731. return
  732. }
  733. // TimeDecodeExt decodes a time.Time from the byte slice parameter, and sets it into the reflect value.
  734. // Configure this to support the Time Extension, e.g. using tag 1.
  735. func (_ *MsgpackHandle) TimeDecodeExt(rv reflect.Value, bs []byte) (err error) {
  736. tt, err := decodeTime(bs)
  737. if err == nil {
  738. rv.Set(reflect.ValueOf(tt))
  739. }
  740. return
  741. }
  742. func (h *MsgpackHandle) newEncDriver(w encWriter) encDriver {
  743. return &msgpackEncDriver{w: w, h: h}
  744. }
  745. func (h *MsgpackHandle) newDecDriver(r decReader) decDriver {
  746. return &msgpackDecDriver{r: r, h: h}
  747. }
  748. func (h *MsgpackHandle) writeExt() bool {
  749. return h.WriteExt
  750. }