msgpack.go 19 KB

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