msgpack.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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{0, 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 == mpBin8, bd == mpBin16, bd == mpBin32:
  296. ctx = dncContainer
  297. rv = reflect.New(byteSliceTyp).Elem()
  298. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  299. ctx = dncContainer
  300. // v = containerList
  301. opts := h.(*MsgpackHandle)
  302. if opts.SliceType == nil {
  303. rv = reflect.New(intfSliceTyp).Elem()
  304. } else {
  305. rv = reflect.New(opts.SliceType).Elem()
  306. }
  307. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  308. ctx = dncContainer
  309. // v = containerMap
  310. opts := h.(*MsgpackHandle)
  311. if opts.MapType == nil {
  312. rv = reflect.MakeMap(mapIntfIntfTyp)
  313. } else {
  314. rv = reflect.MakeMap(opts.MapType)
  315. }
  316. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  317. //ctx = dncExt
  318. clen := d.readExtLen()
  319. xtag := d.r.readn1()
  320. opts := h.(*MsgpackHandle)
  321. var bfn func(reflect.Value, []byte) error
  322. rv, bfn = opts.getDecodeExtForTag(xtag)
  323. if bfn == nil {
  324. decErr("Unable to find type mapped to extension tag: %v", xtag)
  325. }
  326. if fnerr := bfn(rv, d.r.readn(clen)); fnerr != nil {
  327. panic(fnerr)
  328. }
  329. default:
  330. decErr("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  331. }
  332. }
  333. if ctx == dncHandled {
  334. d.bdRead = false
  335. if v != nil {
  336. rv = reflect.ValueOf(v)
  337. }
  338. }
  339. return
  340. }
  341. // int can be decoded from msgpack type: intXXX or uintXXX
  342. func (d *msgpackDecDriver) decodeInt(bitsize uint8) (i int64) {
  343. switch d.bd {
  344. case mpUint8:
  345. i = int64(uint64(d.r.readn1()))
  346. case mpUint16:
  347. i = int64(uint64(d.r.readUint16()))
  348. case mpUint32:
  349. i = int64(uint64(d.r.readUint32()))
  350. case mpUint64:
  351. i = int64(d.r.readUint64())
  352. case mpInt8:
  353. i = int64(int8(d.r.readn1()))
  354. case mpInt16:
  355. i = int64(int16(d.r.readUint16()))
  356. case mpInt32:
  357. i = int64(int32(d.r.readUint32()))
  358. case mpInt64:
  359. i = int64(d.r.readUint64())
  360. default:
  361. switch {
  362. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  363. i = int64(int8(d.bd))
  364. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  365. i = int64(int8(d.bd))
  366. default:
  367. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  368. }
  369. }
  370. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  371. if bitsize > 0 {
  372. if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
  373. decErr("Overflow int value: %v", i)
  374. }
  375. }
  376. d.bdRead = false
  377. return
  378. }
  379. // uint can be decoded from msgpack type: intXXX or uintXXX
  380. func (d *msgpackDecDriver) decodeUint(bitsize uint8) (ui uint64) {
  381. switch d.bd {
  382. case mpUint8:
  383. ui = uint64(d.r.readn1())
  384. case mpUint16:
  385. ui = uint64(d.r.readUint16())
  386. case mpUint32:
  387. ui = uint64(d.r.readUint32())
  388. case mpUint64:
  389. ui = d.r.readUint64()
  390. case mpInt8:
  391. if i := int64(int8(d.r.readn1())); i >= 0 {
  392. ui = uint64(i)
  393. } else {
  394. decErr("Assigning negative signed value: %v, to unsigned type", i)
  395. }
  396. case mpInt16:
  397. if i := int64(int16(d.r.readUint16())); i >= 0 {
  398. ui = uint64(i)
  399. } else {
  400. decErr("Assigning negative signed value: %v, to unsigned type", i)
  401. }
  402. case mpInt32:
  403. if i := int64(int32(d.r.readUint32())); i >= 0 {
  404. ui = uint64(i)
  405. } else {
  406. decErr("Assigning negative signed value: %v, to unsigned type", i)
  407. }
  408. case mpInt64:
  409. if i := int64(d.r.readUint64()); i >= 0 {
  410. ui = uint64(i)
  411. } else {
  412. decErr("Assigning negative signed value: %v, to unsigned type", i)
  413. }
  414. default:
  415. switch {
  416. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  417. ui = uint64(d.bd)
  418. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  419. decErr("Assigning negative signed value: %v, to unsigned type", int(d.bd))
  420. default:
  421. decErr("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  422. }
  423. }
  424. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  425. if bitsize > 0 {
  426. if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
  427. decErr("Overflow uint value: %v", ui)
  428. }
  429. }
  430. d.bdRead = false
  431. return
  432. }
  433. // float can either be decoded from msgpack type: float, double or intX
  434. func (d *msgpackDecDriver) decodeFloat(chkOverflow32 bool) (f float64) {
  435. switch d.bd {
  436. case mpFloat:
  437. f = float64(math.Float32frombits(d.r.readUint32()))
  438. case mpDouble:
  439. f = math.Float64frombits(d.r.readUint64())
  440. default:
  441. f = float64(d.decodeInt(0))
  442. }
  443. // check overflow (logic adapted from std pkg reflect/value.go OverflowFloat()
  444. if chkOverflow32 {
  445. f2 := f
  446. if f2 < 0 {
  447. f2 = -f
  448. }
  449. if math.MaxFloat32 < f2 && f2 <= math.MaxFloat64 {
  450. decErr("Overflow float32 value: %v", f2)
  451. }
  452. }
  453. d.bdRead = false
  454. return
  455. }
  456. // bool can be decoded from bool, fixnum 0 or 1.
  457. func (d *msgpackDecDriver) decodeBool() (b bool) {
  458. switch d.bd {
  459. case mpFalse, 0:
  460. // b = false
  461. case mpTrue, 1:
  462. b = true
  463. default:
  464. decErr("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  465. }
  466. d.bdRead = false
  467. return
  468. }
  469. func (d *msgpackDecDriver) decodeString() (s string) {
  470. clen := d.readContainerLen(msgpackContainerStr)
  471. if clen > 0 {
  472. s = string(d.r.readn(clen))
  473. }
  474. d.bdRead = false
  475. return
  476. }
  477. // Callers must check if changed=true (to decide whether to replace the one they have)
  478. func (d *msgpackDecDriver) decodeBytes(bs []byte) (bsOut []byte, changed bool) {
  479. // bytes can be decoded from msgpackContainerStr or msgpackContainerBin
  480. var clen int
  481. switch d.bd {
  482. case mpBin8, mpBin16, mpBin32:
  483. clen = d.readContainerLen(msgpackContainerBin)
  484. default:
  485. clen = d.readContainerLen(msgpackContainerStr)
  486. }
  487. // if clen < 0 {
  488. // changed = true
  489. // panic("length cannot be zero. this cannot be nil.")
  490. // }
  491. if clen > 0 {
  492. // if no contents in stream, don't update the passed byteslice
  493. if len(bs) != clen {
  494. // Return changed=true if length of passed slice diff from length of bytes in stream
  495. if len(bs) > clen {
  496. bs = bs[:clen]
  497. } else {
  498. bs = make([]byte, clen)
  499. }
  500. bsOut = bs
  501. changed = true
  502. }
  503. d.r.readb(bs)
  504. }
  505. d.bdRead = false
  506. return
  507. }
  508. // Every top-level decode funcs (i.e. decodeValue, decode) must call this first.
  509. func (d *msgpackDecDriver) initReadNext() {
  510. if d.bdRead {
  511. return
  512. }
  513. d.bd = d.r.readn1()
  514. d.bdRead = true
  515. }
  516. func (d *msgpackDecDriver) currentIsNil() bool {
  517. if d.bd == mpNil {
  518. d.bdRead = false
  519. return true
  520. }
  521. return false
  522. }
  523. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  524. bd := d.bd
  525. switch {
  526. case bd == mpNil:
  527. clen = -1 // to represent nil
  528. case bd == ct.b8:
  529. clen = int(d.r.readn1())
  530. case bd == ct.b16:
  531. clen = int(d.r.readUint16())
  532. case bd == ct.b32:
  533. clen = int(d.r.readUint32())
  534. case (ct.bFixMin & bd) == ct.bFixMin:
  535. clen = int(ct.bFixMin ^ bd)
  536. default:
  537. decErr("readContainerLen: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  538. }
  539. d.bdRead = false
  540. return
  541. }
  542. func (d *msgpackDecDriver) readMapLen() int {
  543. return d.readContainerLen(msgpackContainerMap)
  544. }
  545. func (d *msgpackDecDriver) readArrayLen() int {
  546. return d.readContainerLen(msgpackContainerList)
  547. }
  548. func (d *msgpackDecDriver) readExtLen() (clen int) {
  549. switch d.bd {
  550. case mpNil:
  551. clen = -1 // to represent nil
  552. case mpFixExt1:
  553. clen = 1
  554. case mpFixExt2:
  555. clen = 2
  556. case mpFixExt4:
  557. clen = 4
  558. case mpFixExt8:
  559. clen = 8
  560. case mpFixExt16:
  561. clen = 16
  562. case mpExt8:
  563. clen = int(d.r.readn1())
  564. case mpExt16:
  565. clen = int(d.r.readUint16())
  566. case mpExt32:
  567. clen = int(d.r.readUint32())
  568. default:
  569. decErr("decoding ext bytes: found unexpected byte: %x", d.bd)
  570. }
  571. return
  572. }
  573. func (d *msgpackDecDriver) decodeExt(tag byte) (xbs []byte) {
  574. xbd := d.bd
  575. switch {
  576. case xbd == mpBin8, xbd == mpBin16, xbd == mpBin32:
  577. xbs, _ = d.decodeBytes(nil)
  578. case xbd == mpStr8, xbd == mpStr16, xbd == mpStr32,
  579. xbd >= mpFixStrMin && xbd <= mpFixStrMax:
  580. xbs = []byte(d.decodeString())
  581. default:
  582. clen := d.readExtLen()
  583. if xtag := d.r.readn1(); xtag != tag {
  584. decErr("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  585. }
  586. xbs = d.r.readn(clen)
  587. }
  588. d.bdRead = false
  589. return
  590. }
  591. //--------------------------------------------------
  592. func (msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  593. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  594. }
  595. func (msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  596. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  597. }
  598. // /////////////// Spec RPC Codec ///////////////////
  599. func (c msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  600. return c.writeCustomBody(0, r.Seq, r.ServiceMethod, body)
  601. }
  602. func (c msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  603. return c.writeCustomBody(1, r.Seq, r.Error, body)
  604. }
  605. func (c msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  606. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  607. }
  608. func (c msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  609. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  610. }
  611. func (c msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  612. // We read the response header by hand
  613. // so that the body can be decoded on its own from the stream at a later time.
  614. bs := make([]byte, 1)
  615. n, err := c.rwc.Read(bs)
  616. if err != nil {
  617. return
  618. }
  619. if n != 1 {
  620. err = fmt.Errorf("Couldn't read array descriptor: No bytes read")
  621. return
  622. }
  623. const fia byte = 0x94 //four item array descriptor value
  624. if bs[0] != fia {
  625. err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs[0])
  626. return
  627. }
  628. var b byte
  629. if err = c.read(&b); err != nil {
  630. return
  631. }
  632. if b != expectTypeByte {
  633. err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
  634. return
  635. }
  636. if err = c.read(msgid); err != nil {
  637. return
  638. }
  639. if err = c.read(methodOrError); err != nil {
  640. return
  641. }
  642. return
  643. }
  644. func (c msgpackSpecRpcCodec) writeCustomBody(typeByte byte, msgid uint64, methodOrError string, body interface{}) (err error) {
  645. var moe interface{} = methodOrError
  646. // response needs nil error (not ""), and only one of error or body can be nil
  647. if typeByte == 1 {
  648. if methodOrError == "" {
  649. moe = nil
  650. }
  651. if moe != nil && body != nil {
  652. body = nil
  653. }
  654. }
  655. r2 := []interface{}{typeByte, uint32(msgid), moe, body}
  656. return c.write(r2, nil, false, true)
  657. }
  658. //--------------------------------------------------
  659. // BinaryEncodeExt returns the underlying bytes of this value AS-IS.
  660. // Configure this to support the Binary Extension using tag 0.
  661. func (_ *MsgpackHandle) BinaryEncodeExt(rv reflect.Value) ([]byte, error) {
  662. if rv.IsNil() {
  663. return nil, nil
  664. }
  665. return rv.Bytes(), nil
  666. }
  667. // BinaryDecodeExt sets passed byte slice AS-IS into the reflect Value.
  668. // Configure this to support the Binary Extension using tag 0.
  669. func (_ *MsgpackHandle) BinaryDecodeExt(rv reflect.Value, bs []byte) (err error) {
  670. rv.SetBytes(bs)
  671. return
  672. }
  673. // TimeEncodeExt encodes a time.Time as a byte slice.
  674. // Configure this to support the Time Extension, e.g. using tag 1.
  675. func (_ *MsgpackHandle) TimeEncodeExt(rv reflect.Value) (bs []byte, err error) {
  676. bs = encodeTime(rv.Interface().(time.Time))
  677. return
  678. }
  679. // TimeDecodeExt decodes a time.Time from the byte slice parameter, and sets it into the reflect value.
  680. // Configure this to support the Time Extension, e.g. using tag 1.
  681. func (_ *MsgpackHandle) TimeDecodeExt(rv reflect.Value, bs []byte) (err error) {
  682. tt, err := decodeTime(bs)
  683. if err == nil {
  684. rv.Set(reflect.ValueOf(tt))
  685. }
  686. return
  687. }
  688. func (h *MsgpackHandle) newEncDriver(w encWriter) encDriver {
  689. return &msgpackEncDriver{w: w, h: h}
  690. }
  691. func (h *MsgpackHandle) newDecDriver(r decReader) decDriver {
  692. return &msgpackDecDriver{r: r, h: h}
  693. }
  694. func (h *MsgpackHandle) writeExt() bool {
  695. return h.WriteExt
  696. }