msgpack.go 20 KB

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