msgpack.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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) encodeSymbol(v string) {
  203. e.encodeString(c_UTF8, v)
  204. }
  205. func (e *msgpackEncoder) encodeStringBytes(c charEncoding, bs []byte) {
  206. //ignore charEncoding.
  207. e.writeContainerLen(msgpackContainerRawBytes, len(bs))
  208. if len(bs) > 0 {
  209. e.w.writeb(bs)
  210. }
  211. }
  212. func (e *msgpackEncoder) writeContainerLen(ct msgpackContainerType, l int) {
  213. switch {
  214. case l < int(ct.cutoff):
  215. e.w.writen1(ct.b0 | byte(l))
  216. case l < 65536:
  217. e.w.writen1(ct.b1)
  218. e.w.writeUint16(uint16(l))
  219. default:
  220. e.w.writen1(ct.b2)
  221. e.w.writeUint32(uint32(l))
  222. }
  223. }
  224. //---------------------------------------------
  225. func (d *msgpackDecoder) decodeBuiltinType(rt reflect.Type, rv reflect.Value) bool {
  226. return false
  227. }
  228. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  229. // or a containerType, or a specific type denoting nil or extension.
  230. // It is called when a nil interface{} is passed, leaving it up to the Decoder
  231. // to introspect the stream and decide how best to decode.
  232. // It deciphers the value by looking at the stream first.
  233. func (d *msgpackDecoder) decodeNaked(h decodeHandleI) (rv reflect.Value, ctx decodeNakedContext) {
  234. d.initReadNext()
  235. bd := d.bd
  236. var v interface{}
  237. switch bd {
  238. case mpNil:
  239. ctx = dncNil
  240. d.bdRead = false
  241. case mpFalse:
  242. v = false
  243. case mpTrue:
  244. v = true
  245. case mpFloat:
  246. v = float64(math.Float32frombits(d.r.readUint32()))
  247. case mpDouble:
  248. v = math.Float64frombits(d.r.readUint64())
  249. case mpUint8:
  250. v = uint64(d.r.readn1())
  251. case mpUint16:
  252. v = uint64(d.r.readUint16())
  253. case mpUint32:
  254. v = uint64(d.r.readUint32())
  255. case mpUint64:
  256. v = uint64(d.r.readUint64())
  257. case mpInt8:
  258. v = int64(int8(d.r.readn1()))
  259. case mpInt16:
  260. v = int64(int16(d.r.readUint16()))
  261. case mpInt32:
  262. v = int64(int32(d.r.readUint32()))
  263. case mpInt64:
  264. v = int64(int64(d.r.readUint64()))
  265. default:
  266. switch {
  267. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  268. // positive fixnum (always signed)
  269. v = int64(int8(bd))
  270. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  271. // negative fixnum
  272. v = int64(int8(bd))
  273. case bd == mpRaw16, bd == mpRaw32, bd >= mpFixRawMin && bd <= mpFixRawMax:
  274. ctx = dncContainer
  275. // v = containerRawBytes
  276. opts := h.(*MsgpackHandle)
  277. if opts.rawToStringOverride || opts.RawToString {
  278. var rvm string
  279. rv = reflect.ValueOf(&rvm).Elem()
  280. } else {
  281. rv = reflect.New(byteSliceTyp).Elem() // Use New, not Zero, so it's settable
  282. }
  283. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  284. ctx = dncContainer
  285. // v = containerList
  286. opts := h.(*MsgpackHandle)
  287. if opts.SliceType == nil {
  288. rv = reflect.New(intfSliceTyp).Elem()
  289. } else {
  290. rv = reflect.New(opts.SliceType).Elem()
  291. }
  292. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  293. ctx = dncContainer
  294. // v = containerMap
  295. opts := h.(*MsgpackHandle)
  296. if opts.MapType == nil {
  297. rv = reflect.MakeMap(mapIntfIntfTyp)
  298. } else {
  299. rv = reflect.MakeMap(opts.MapType)
  300. }
  301. case bd >= mpXv4Fixext0 && bd <= mpXv4Fixext5, bd >= mpXv4Ext8m && bd <= mpXv4Ext32:
  302. //ctx = dncExt
  303. xtag := d.r.readn1()
  304. opts := h.(*MsgpackHandle)
  305. rt, bfn := opts.getDecodeExtForTag(xtag)
  306. if rt == nil {
  307. decErr("Unable to find type mapped to extension tag: %v", xtag)
  308. }
  309. if rt.Kind() == reflect.Ptr {
  310. rv = reflect.New(rt.Elem())
  311. } else {
  312. rv = reflect.New(rt).Elem()
  313. }
  314. if fnerr := bfn(rv, d.r.readn(d.readExtLen())); fnerr != nil {
  315. panic(fnerr)
  316. }
  317. default:
  318. decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  319. }
  320. }
  321. if ctx == dncHandled {
  322. d.bdRead = false
  323. if v != nil {
  324. rv = reflect.ValueOf(v)
  325. }
  326. }
  327. return
  328. }
  329. // int can be decoded from msgpack type: intXXX or uintXXX
  330. func (d *msgpackDecoder) decodeInt(bitsize uint8) (i int64) {
  331. switch d.bd {
  332. case mpUint8:
  333. i = int64(uint64(d.r.readn1()))
  334. case mpUint16:
  335. i = int64(uint64(d.r.readUint16()))
  336. case mpUint32:
  337. i = int64(uint64(d.r.readUint32()))
  338. case mpUint64:
  339. i = int64(d.r.readUint64())
  340. case mpInt8:
  341. i = int64(int8(d.r.readn1()))
  342. case mpInt16:
  343. i = int64(int16(d.r.readUint16()))
  344. case mpInt32:
  345. i = int64(int32(d.r.readUint32()))
  346. case mpInt64:
  347. i = int64(d.r.readUint64())
  348. default:
  349. switch {
  350. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  351. i = int64(int8(d.bd))
  352. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  353. i = int64(int8(d.bd))
  354. default:
  355. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  356. }
  357. }
  358. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  359. if bitsize > 0 {
  360. if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
  361. decErr("Overflow int value: %v", i)
  362. }
  363. }
  364. d.bdRead = false
  365. return
  366. }
  367. // uint can be decoded from msgpack type: intXXX or uintXXX
  368. func (d *msgpackDecoder) decodeUint(bitsize uint8) (ui uint64) {
  369. switch d.bd {
  370. case mpUint8:
  371. ui = uint64(d.r.readn1())
  372. case mpUint16:
  373. ui = uint64(d.r.readUint16())
  374. case mpUint32:
  375. ui = uint64(d.r.readUint32())
  376. case mpUint64:
  377. ui = d.r.readUint64()
  378. case mpInt8:
  379. if i := int64(int8(d.r.readn1())); i >= 0 {
  380. ui = uint64(i)
  381. } else {
  382. decErr("Assigning negative signed value: %v, to unsigned type", i)
  383. }
  384. case mpInt16:
  385. if i := int64(int16(d.r.readUint16())); i >= 0 {
  386. ui = uint64(i)
  387. } else {
  388. decErr("Assigning negative signed value: %v, to unsigned type", i)
  389. }
  390. case mpInt32:
  391. if i := int64(int32(d.r.readUint32())); i >= 0 {
  392. ui = uint64(i)
  393. } else {
  394. decErr("Assigning negative signed value: %v, to unsigned type", i)
  395. }
  396. case mpInt64:
  397. if i := int64(d.r.readUint64()); i >= 0 {
  398. ui = uint64(i)
  399. } else {
  400. decErr("Assigning negative signed value: %v, to unsigned type", i)
  401. }
  402. default:
  403. switch {
  404. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  405. ui = uint64(d.bd)
  406. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  407. decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd))
  408. default:
  409. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  410. }
  411. }
  412. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  413. if bitsize > 0 {
  414. if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
  415. decErr("Overflow uint value: %v", ui)
  416. }
  417. }
  418. d.bdRead = false
  419. return
  420. }
  421. // float can either be decoded from msgpack type: float, double or intX
  422. func (d *msgpackDecoder) decodeFloat(chkOverflow32 bool) (f float64) {
  423. switch d.bd {
  424. case mpFloat:
  425. f = float64(math.Float32frombits(d.r.readUint32()))
  426. case mpDouble:
  427. f = math.Float64frombits(d.r.readUint64())
  428. default:
  429. f = float64(d.decodeInt(0))
  430. }
  431. // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
  432. if chkOverflow32 {
  433. f2 := f
  434. if f2 < 0 {
  435. f2 = -f
  436. }
  437. if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
  438. decErr("Overflow float32 value: %v", f2)
  439. }
  440. }
  441. d.bdRead = false
  442. return
  443. }
  444. // bool can be decoded from bool, fixnum 0 or 1.
  445. func (d *msgpackDecoder) decodeBool() (b bool) {
  446. switch d.bd {
  447. case mpFalse, 0:
  448. // b = false
  449. case mpTrue, 1:
  450. b = true
  451. default:
  452. decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  453. }
  454. d.bdRead = false
  455. return
  456. }
  457. func (d *msgpackDecoder) decodeString() (s string) {
  458. clen := d.readContainerLen(msgpackContainerRawBytes)
  459. if clen > 0 {
  460. s = string(d.r.readn(clen))
  461. }
  462. d.bdRead = false
  463. return
  464. }
  465. // Callers must check if changed=true (to decide whether to replace the one they have)
  466. func (d *msgpackDecoder) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
  467. clen := d.readContainerLen(msgpackContainerRawBytes)
  468. // if clen < 0 {
  469. // changed = true
  470. // panic("length cannot be zero. this cannot be nil.")
  471. // }
  472. if clen > 0 {
  473. // if no contents in stream, don't update the passed byteslice
  474. if len(bs) != clen {
  475. // Return changed=true if length of passed slice is different from length of bytes in the stream.
  476. if len(bs) > clen {
  477. bs = bs[:clen]
  478. } else {
  479. bs = make([]byte, clen)
  480. }
  481. bsOut = bs
  482. changed = true
  483. }
  484. d.r.readb(bs)
  485. }
  486. d.bdRead = false
  487. return
  488. }
  489. // Every top-level decode funcs (i.e. decodeValue, decode) must call this first.
  490. func (d *msgpackDecoder) initReadNext() {
  491. if d.bdRead {
  492. return
  493. }
  494. d.bd = d.r.readn1()
  495. d.bdRead = true
  496. }
  497. func (d *msgpackDecoder) currentIsNil() bool {
  498. if d.bd == mpNil {
  499. d.bdRead = false
  500. return true
  501. }
  502. return false
  503. }
  504. func (d *msgpackDecoder) readContainerLen(ct msgpackContainerType) (clen int) {
  505. switch {
  506. case d.bd == mpNil:
  507. clen = -1 // to represent nil
  508. case d.bd == ct.b1:
  509. clen = int(d.r.readUint16())
  510. case d.bd == ct.b2:
  511. clen = int(d.r.readUint32())
  512. case (ct.b0 & d.bd) == ct.b0:
  513. clen = int(ct.b0 ^ d.bd)
  514. default:
  515. decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, d.bd, d.bd)
  516. }
  517. d.bdRead = false
  518. return
  519. }
  520. func (d *msgpackDecoder) readMapLen() int {
  521. return d.readContainerLen(msgpackContainerMap)
  522. }
  523. func (d *msgpackDecoder) readArrayLen() int {
  524. return d.readContainerLen(msgpackContainerList)
  525. }
  526. func (d *msgpackDecoder) readExtLen() (clen int) {
  527. switch d.bd {
  528. case mpNil:
  529. clen = -1 // to represent nil
  530. case mpXv4Fixext5:
  531. clen = int(d.r.readn1())
  532. case mpXv4Ext16:
  533. clen = int(d.r.readUint16())
  534. case mpXv4Ext32:
  535. clen = int(d.r.readUint32())
  536. default:
  537. switch {
  538. case d.bd >= mpXv4Fixext0 && d.bd <= mpXv4Fixext4:
  539. clen = int(d.bd & 0x0f)
  540. case d.bd >= mpXv4Ext8m && d.bd <= mpXv4Ext8:
  541. clen = int(d.bd & 0x03)
  542. default:
  543. decErr("decoding ext bytes: found unexpected byte: %x", d.bd)
  544. }
  545. }
  546. return
  547. }
  548. func (d *msgpackDecoder) decodeExt(tag byte) (xbs []byte) {
  549. // if (d.bd >= mpXv4Fixext0 && d.bd <= mpXv4Fixext5) || (d.bd >= mpXv4Ext8m && d.bd <= mpXv4Ext32) {
  550. xbd := d.bd
  551. switch {
  552. case xbd >= mpXv4Fixext0 && xbd <= mpXv4Fixext5, xbd >= mpXv4Ext8m && xbd <= mpXv4Ext32:
  553. if xtag := d.r.readn1(); xtag != tag {
  554. decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  555. }
  556. xbs = d.r.readn(d.readExtLen())
  557. case xbd == mpRaw16, xbd == mpRaw32, xbd >= mpFixRawMin && xbd <= mpFixRawMax:
  558. xbs, _ = d.decodeBytes(nil)
  559. default:
  560. decErr("Wrong byte descriptor (Expecting extensions or raw bytes). Got: 0x%x", xbd)
  561. }
  562. d.bdRead = false
  563. return
  564. }
  565. //--------------------------------------------------
  566. func (msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) (rpc.ServerCodec) {
  567. return &msgpackSpecRpcCodec{ newRPCCodec(conn, h) }
  568. }
  569. func (msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) (rpc.ClientCodec) {
  570. return &msgpackSpecRpcCodec{ newRPCCodec(conn, h) }
  571. }
  572. // /////////////// Spec RPC Codec ///////////////////
  573. func (c msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  574. return c.writeCustomBody(0, r.Seq, r.ServiceMethod, body)
  575. }
  576. func (c msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  577. return c.writeCustomBody(1, r.Seq, r.Error, body)
  578. }
  579. func (c msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  580. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  581. }
  582. func (c msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  583. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  584. }
  585. func (c msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  586. // We read the response header by hand
  587. // so that the body can be decoded on its own from the stream at a later time.
  588. bs := make([]byte, 1)
  589. n, err := c.rwc.Read(bs)
  590. if err != nil {
  591. return
  592. }
  593. if n != 1 {
  594. err = fmt.Errorf("Couldn't read array descriptor: No bytes read")
  595. return
  596. }
  597. const fia byte = 0x94 //four item array descriptor value
  598. if bs[0] != fia {
  599. err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs[0])
  600. return
  601. }
  602. var b byte
  603. if err = c.read(&b, msgid, methodOrError); err != nil {
  604. return
  605. }
  606. if b != expectTypeByte {
  607. err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
  608. return
  609. }
  610. return
  611. }
  612. func (c msgpackSpecRpcCodec) writeCustomBody(typeByte byte, msgid uint64, methodOrError string, body interface{}) (err error) {
  613. var moe interface{} = methodOrError
  614. // response needs nil error (not ""), and only one of error or body can be nil
  615. if typeByte == 1 {
  616. if methodOrError == "" {
  617. moe = nil
  618. }
  619. if moe != nil && body != nil {
  620. body = nil
  621. }
  622. }
  623. r2 := []interface{}{ typeByte, uint32(msgid), moe, body }
  624. return c.enc.Encode(r2)
  625. }
  626. //--------------------------------------------------
  627. // EncodeBinaryExt returns the underlying bytes of this value AS-IS.
  628. // Configure this to support the Binary Extension using tag 0.
  629. func (_ *MsgpackHandle) BinaryEncodeExt(rv reflect.Value) ([]byte, error) {
  630. if rv.IsNil() {
  631. return nil, nil
  632. }
  633. return rv.Bytes(), nil
  634. }
  635. // DecodeBinaryExt sets passed byte array AS-IS into the reflect Value.
  636. // Configure this to support the Binary Extension using tag 0.
  637. func (_ *MsgpackHandle) BinaryDecodeExt(rv reflect.Value, bs []byte) (err error) {
  638. rv.SetBytes(bs)
  639. return
  640. }
  641. // EncodeBinaryExt returns the underlying bytes of this value AS-IS.
  642. // Configure this to support the Binary Extension using tag 0.
  643. func (_ *MsgpackHandle) TimeEncodeExt(rv reflect.Value) (bs []byte, err error) {
  644. bs = encodeTime(rv.Interface().(time.Time))
  645. return
  646. }
  647. func (_ *MsgpackHandle) TimeDecodeExt(rv reflect.Value, bs []byte) (err error) {
  648. tt, err := decodeTime(bs)
  649. if err == nil {
  650. rv.Set(reflect.ValueOf(tt))
  651. }
  652. return
  653. }
  654. func (_ *MsgpackHandle) newEncoder(w encWriter) encoder {
  655. return &msgpackEncoder{w: w}
  656. }
  657. func (_ *MsgpackHandle) newDecoder(r decReader) decoder {
  658. return &msgpackDecoder{r: r}
  659. }
  660. func (o *MsgpackHandle) writeExt() bool {
  661. return o.WriteExt
  662. }