msgpack.go 19 KB

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