msgpack.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. /*
  4. MSGPACK
  5. Msgpack-c implementation powers the c, c++, python, ruby, etc libraries.
  6. We need to maintain compatibility with it and how it encodes integer values
  7. without caring about the type.
  8. For compatibility with behaviour of msgpack-c reference implementation:
  9. - Go intX (>0) and uintX
  10. IS ENCODED AS
  11. msgpack +ve fixnum, unsigned
  12. - Go intX (<0)
  13. IS ENCODED AS
  14. msgpack -ve fixnum, signed
  15. */
  16. package codec
  17. import (
  18. "fmt"
  19. "io"
  20. "math"
  21. "net/rpc"
  22. "reflect"
  23. "time"
  24. )
  25. const (
  26. mpPosFixNumMin byte = 0x00
  27. mpPosFixNumMax = 0x7f
  28. mpFixMapMin = 0x80
  29. mpFixMapMax = 0x8f
  30. mpFixArrayMin = 0x90
  31. mpFixArrayMax = 0x9f
  32. mpFixStrMin = 0xa0
  33. mpFixStrMax = 0xbf
  34. mpNil = 0xc0
  35. _ = 0xc1
  36. mpFalse = 0xc2
  37. mpTrue = 0xc3
  38. mpFloat = 0xca
  39. mpDouble = 0xcb
  40. mpUint8 = 0xcc
  41. mpUint16 = 0xcd
  42. mpUint32 = 0xce
  43. mpUint64 = 0xcf
  44. mpInt8 = 0xd0
  45. mpInt16 = 0xd1
  46. mpInt32 = 0xd2
  47. mpInt64 = 0xd3
  48. // extensions below
  49. mpBin8 = 0xc4
  50. mpBin16 = 0xc5
  51. mpBin32 = 0xc6
  52. mpExt8 = 0xc7
  53. mpExt16 = 0xc8
  54. mpExt32 = 0xc9
  55. mpFixExt1 = 0xd4
  56. mpFixExt2 = 0xd5
  57. mpFixExt4 = 0xd6
  58. mpFixExt8 = 0xd7
  59. mpFixExt16 = 0xd8
  60. mpStr8 = 0xd9 // new
  61. mpStr16 = 0xda
  62. mpStr32 = 0xdb
  63. mpArray16 = 0xdc
  64. mpArray32 = 0xdd
  65. mpMap16 = 0xde
  66. mpMap32 = 0xdf
  67. mpNegFixNumMin = 0xe0
  68. mpNegFixNumMax = 0xff
  69. )
  70. var mpTimeExtTag int8 = -1
  71. var mpTimeExtTagU = uint8(mpTimeExtTag)
  72. // MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
  73. // that the backend RPC service takes multiple arguments, which have been arranged
  74. // in sequence in the slice.
  75. //
  76. // The Codec then passes it AS-IS to the rpc service (without wrapping it in an
  77. // array of 1 element).
  78. type MsgpackSpecRpcMultiArgs []interface{}
  79. // A MsgpackContainer type specifies the different types of msgpackContainers.
  80. type msgpackContainerType struct {
  81. fixCutoff int
  82. bFixMin, b8, b16, b32 byte
  83. hasFixMin, has8, has8Always bool
  84. }
  85. var (
  86. msgpackContainerStr = msgpackContainerType{32, mpFixStrMin, mpStr8, mpStr16, mpStr32, true, true, false}
  87. msgpackContainerBin = msgpackContainerType{0, 0, mpBin8, mpBin16, mpBin32, false, true, true}
  88. msgpackContainerList = msgpackContainerType{16, mpFixArrayMin, 0, mpArray16, mpArray32, true, false, false}
  89. msgpackContainerMap = msgpackContainerType{16, mpFixMapMin, 0, mpMap16, mpMap32, true, false, false}
  90. )
  91. //---------------------------------------------
  92. type msgpackEncDriver struct {
  93. noBuiltInTypes
  94. encDriverNoopContainerWriter
  95. // encNoSeparator
  96. e *Encoder
  97. w encWriter
  98. h *MsgpackHandle
  99. x [8]byte
  100. }
  101. func (e *msgpackEncDriver) EncodeNil() {
  102. e.w.writen1(mpNil)
  103. }
  104. func (e *msgpackEncDriver) EncodeInt(i int64) {
  105. // if i >= 0 {
  106. // e.EncodeUint(uint64(i))
  107. // } else if false &&
  108. if i > math.MaxInt8 {
  109. if i <= math.MaxInt16 {
  110. e.w.writen1(mpInt16)
  111. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  112. } else if i <= math.MaxInt32 {
  113. e.w.writen1(mpInt32)
  114. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  115. } else {
  116. e.w.writen1(mpInt64)
  117. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  118. }
  119. } else if i >= -32 {
  120. if e.h.NoFixedNum {
  121. e.w.writen2(mpInt8, byte(i))
  122. } else {
  123. e.w.writen1(byte(i))
  124. }
  125. } else if i >= math.MinInt8 {
  126. e.w.writen2(mpInt8, byte(i))
  127. } else if i >= math.MinInt16 {
  128. e.w.writen1(mpInt16)
  129. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  130. } else if i >= math.MinInt32 {
  131. e.w.writen1(mpInt32)
  132. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  133. } else {
  134. e.w.writen1(mpInt64)
  135. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  136. }
  137. }
  138. func (e *msgpackEncDriver) EncodeUint(i uint64) {
  139. if i <= math.MaxInt8 {
  140. if e.h.NoFixedNum {
  141. e.w.writen2(mpUint8, byte(i))
  142. } else {
  143. e.w.writen1(byte(i))
  144. }
  145. } else if i <= math.MaxUint8 {
  146. e.w.writen2(mpUint8, byte(i))
  147. } else if i <= math.MaxUint16 {
  148. e.w.writen1(mpUint16)
  149. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(i))
  150. } else if i <= math.MaxUint32 {
  151. e.w.writen1(mpUint32)
  152. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(i))
  153. } else {
  154. e.w.writen1(mpUint64)
  155. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(i))
  156. }
  157. }
  158. func (e *msgpackEncDriver) EncodeBool(b bool) {
  159. if b {
  160. e.w.writen1(mpTrue)
  161. } else {
  162. e.w.writen1(mpFalse)
  163. }
  164. }
  165. func (e *msgpackEncDriver) EncodeFloat32(f float32) {
  166. e.w.writen1(mpFloat)
  167. bigenHelper{e.x[:4], e.w}.writeUint32(math.Float32bits(f))
  168. }
  169. func (e *msgpackEncDriver) EncodeFloat64(f float64) {
  170. e.w.writen1(mpDouble)
  171. bigenHelper{e.x[:8], e.w}.writeUint64(math.Float64bits(f))
  172. }
  173. func (e *msgpackEncDriver) EncodeTime(t time.Time) {
  174. if t.IsZero() {
  175. e.EncodeNil()
  176. return
  177. }
  178. t = t.UTC()
  179. sec, nsec := t.Unix(), uint64(t.Nanosecond())
  180. var data64 uint64
  181. var l = 4
  182. if sec >= 0 && sec>>34 == 0 {
  183. data64 = (nsec << 34) | uint64(sec)
  184. if data64&0xffffffff00000000 != 0 {
  185. l = 8
  186. }
  187. } else {
  188. l = 12
  189. }
  190. if e.h.WriteExt {
  191. e.encodeExtPreamble(mpTimeExtTagU, l)
  192. } else {
  193. e.writeContainerLen(msgpackContainerStr, l)
  194. }
  195. switch l {
  196. case 4:
  197. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(data64))
  198. case 8:
  199. bigenHelper{e.x[:8], e.w}.writeUint64(data64)
  200. case 12:
  201. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(nsec))
  202. bigenHelper{e.x[:8], e.w}.writeUint64(uint64(sec))
  203. }
  204. }
  205. func (e *msgpackEncDriver) EncodeExt(v interface{}, xtag uint64, ext Ext, _ *Encoder) {
  206. bs := ext.WriteExt(v)
  207. if bs == nil {
  208. e.EncodeNil()
  209. return
  210. }
  211. if e.h.WriteExt {
  212. e.encodeExtPreamble(uint8(xtag), len(bs))
  213. e.w.writeb(bs)
  214. } else {
  215. e.EncodeStringBytes(cRAW, bs)
  216. }
  217. }
  218. func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  219. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  220. e.w.writeb(re.Data)
  221. }
  222. func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
  223. if l == 1 {
  224. e.w.writen2(mpFixExt1, xtag)
  225. } else if l == 2 {
  226. e.w.writen2(mpFixExt2, xtag)
  227. } else if l == 4 {
  228. e.w.writen2(mpFixExt4, xtag)
  229. } else if l == 8 {
  230. e.w.writen2(mpFixExt8, xtag)
  231. } else if l == 16 {
  232. e.w.writen2(mpFixExt16, xtag)
  233. } else if l < 256 {
  234. e.w.writen2(mpExt8, byte(l))
  235. e.w.writen1(xtag)
  236. } else if l < 65536 {
  237. e.w.writen1(mpExt16)
  238. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  239. e.w.writen1(xtag)
  240. } else {
  241. e.w.writen1(mpExt32)
  242. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  243. e.w.writen1(xtag)
  244. }
  245. }
  246. func (e *msgpackEncDriver) WriteArrayStart(length int) {
  247. e.writeContainerLen(msgpackContainerList, length)
  248. }
  249. func (e *msgpackEncDriver) WriteMapStart(length int) {
  250. e.writeContainerLen(msgpackContainerMap, length)
  251. }
  252. func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) {
  253. slen := len(s)
  254. if c == cRAW && e.h.WriteExt {
  255. e.writeContainerLen(msgpackContainerBin, slen)
  256. } else {
  257. e.writeContainerLen(msgpackContainerStr, slen)
  258. }
  259. if slen > 0 {
  260. e.w.writestr(s)
  261. }
  262. }
  263. func (e *msgpackEncDriver) EncodeSymbol(v string) {
  264. e.EncodeString(cUTF8, v)
  265. }
  266. func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) {
  267. if bs == nil {
  268. e.EncodeNil()
  269. return
  270. }
  271. slen := len(bs)
  272. if c == cRAW && e.h.WriteExt {
  273. e.writeContainerLen(msgpackContainerBin, slen)
  274. } else {
  275. e.writeContainerLen(msgpackContainerStr, slen)
  276. }
  277. if slen > 0 {
  278. e.w.writeb(bs)
  279. }
  280. }
  281. func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
  282. if ct.hasFixMin && l < ct.fixCutoff {
  283. e.w.writen1(ct.bFixMin | byte(l))
  284. } else if ct.has8 && l < 256 && (ct.has8Always || e.h.WriteExt) {
  285. e.w.writen2(ct.b8, uint8(l))
  286. } else if l < 65536 {
  287. e.w.writen1(ct.b16)
  288. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  289. } else {
  290. e.w.writen1(ct.b32)
  291. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  292. }
  293. }
  294. //---------------------------------------------
  295. type msgpackDecDriver struct {
  296. d *Decoder
  297. r decReader // *Decoder decReader decReaderT
  298. h *MsgpackHandle
  299. b [scratchByteArrayLen]byte
  300. bd byte
  301. bdRead bool
  302. br bool // bytes reader
  303. noBuiltInTypes
  304. // noStreamingCodec
  305. // decNoSeparator
  306. decDriverNoopContainerReader
  307. }
  308. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  309. // or a containerType, or a specific type denoting nil or extension.
  310. // It is called when a nil interface{} is passed, leaving it up to the DecDriver
  311. // to introspect the stream and decide how best to decode.
  312. // It deciphers the value by looking at the stream first.
  313. func (d *msgpackDecDriver) DecodeNaked() {
  314. if !d.bdRead {
  315. d.readNextBd()
  316. }
  317. bd := d.bd
  318. n := d.d.n
  319. var decodeFurther bool
  320. switch bd {
  321. case mpNil:
  322. n.v = valueTypeNil
  323. d.bdRead = false
  324. case mpFalse:
  325. n.v = valueTypeBool
  326. n.b = false
  327. case mpTrue:
  328. n.v = valueTypeBool
  329. n.b = true
  330. case mpFloat:
  331. n.v = valueTypeFloat
  332. n.f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  333. case mpDouble:
  334. n.v = valueTypeFloat
  335. n.f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  336. case mpUint8:
  337. n.v = valueTypeUint
  338. n.u = uint64(d.r.readn1())
  339. case mpUint16:
  340. n.v = valueTypeUint
  341. n.u = uint64(bigen.Uint16(d.r.readx(2)))
  342. case mpUint32:
  343. n.v = valueTypeUint
  344. n.u = uint64(bigen.Uint32(d.r.readx(4)))
  345. case mpUint64:
  346. n.v = valueTypeUint
  347. n.u = uint64(bigen.Uint64(d.r.readx(8)))
  348. case mpInt8:
  349. n.v = valueTypeInt
  350. n.i = int64(int8(d.r.readn1()))
  351. case mpInt16:
  352. n.v = valueTypeInt
  353. n.i = int64(int16(bigen.Uint16(d.r.readx(2))))
  354. case mpInt32:
  355. n.v = valueTypeInt
  356. n.i = int64(int32(bigen.Uint32(d.r.readx(4))))
  357. case mpInt64:
  358. n.v = valueTypeInt
  359. n.i = int64(int64(bigen.Uint64(d.r.readx(8))))
  360. default:
  361. switch {
  362. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  363. // positive fixnum (always signed)
  364. n.v = valueTypeInt
  365. n.i = int64(int8(bd))
  366. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  367. // negative fixnum
  368. n.v = valueTypeInt
  369. n.i = int64(int8(bd))
  370. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  371. if d.h.RawToString {
  372. n.v = valueTypeString
  373. n.s = d.DecodeString()
  374. } else {
  375. n.v = valueTypeBytes
  376. n.l = d.DecodeBytes(nil, false)
  377. }
  378. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  379. n.v = valueTypeBytes
  380. n.l = d.DecodeBytes(nil, false)
  381. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  382. n.v = valueTypeArray
  383. decodeFurther = true
  384. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  385. n.v = valueTypeMap
  386. decodeFurther = true
  387. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  388. n.v = valueTypeExt
  389. clen := d.readExtLen()
  390. n.u = uint64(d.r.readn1())
  391. if n.u == uint64(mpTimeExtTagU) {
  392. n.v = valueTypeTime
  393. n.t = d.decodeTime(clen)
  394. } else {
  395. n.l = d.r.readx(clen)
  396. }
  397. default:
  398. d.d.errorf("Nil-Deciphered DecodeValue: %s: hex: %x, dec: %d", msgBadDesc, bd, bd)
  399. }
  400. }
  401. if !decodeFurther {
  402. d.bdRead = false
  403. }
  404. if n.v == valueTypeUint && d.h.SignedInteger {
  405. n.v = valueTypeInt
  406. n.i = int64(n.u)
  407. }
  408. return
  409. }
  410. // int can be decoded from msgpack type: intXXX or uintXXX
  411. func (d *msgpackDecDriver) DecodeInt(bitsize uint8) (i int64) {
  412. if !d.bdRead {
  413. d.readNextBd()
  414. }
  415. switch d.bd {
  416. case mpUint8:
  417. i = int64(uint64(d.r.readn1()))
  418. case mpUint16:
  419. i = int64(uint64(bigen.Uint16(d.r.readx(2))))
  420. case mpUint32:
  421. i = int64(uint64(bigen.Uint32(d.r.readx(4))))
  422. case mpUint64:
  423. i = int64(bigen.Uint64(d.r.readx(8)))
  424. case mpInt8:
  425. i = int64(int8(d.r.readn1()))
  426. case mpInt16:
  427. i = int64(int16(bigen.Uint16(d.r.readx(2))))
  428. case mpInt32:
  429. i = int64(int32(bigen.Uint32(d.r.readx(4))))
  430. case mpInt64:
  431. i = int64(bigen.Uint64(d.r.readx(8)))
  432. default:
  433. switch {
  434. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  435. i = int64(int8(d.bd))
  436. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  437. i = int64(int8(d.bd))
  438. default:
  439. d.d.errorf("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  440. return
  441. }
  442. }
  443. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  444. if bitsize > 0 {
  445. if trunc := (i << (64 - bitsize)) >> (64 - bitsize); i != trunc {
  446. d.d.errorf("Overflow int value: %v", i)
  447. return
  448. }
  449. }
  450. d.bdRead = false
  451. return
  452. }
  453. // uint can be decoded from msgpack type: intXXX or uintXXX
  454. func (d *msgpackDecDriver) DecodeUint(bitsize uint8) (ui uint64) {
  455. if !d.bdRead {
  456. d.readNextBd()
  457. }
  458. switch d.bd {
  459. case mpUint8:
  460. ui = uint64(d.r.readn1())
  461. case mpUint16:
  462. ui = uint64(bigen.Uint16(d.r.readx(2)))
  463. case mpUint32:
  464. ui = uint64(bigen.Uint32(d.r.readx(4)))
  465. case mpUint64:
  466. ui = bigen.Uint64(d.r.readx(8))
  467. case mpInt8:
  468. if i := int64(int8(d.r.readn1())); i >= 0 {
  469. ui = uint64(i)
  470. } else {
  471. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  472. return
  473. }
  474. case mpInt16:
  475. if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 {
  476. ui = uint64(i)
  477. } else {
  478. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  479. return
  480. }
  481. case mpInt32:
  482. if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 {
  483. ui = uint64(i)
  484. } else {
  485. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  486. return
  487. }
  488. case mpInt64:
  489. if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 {
  490. ui = uint64(i)
  491. } else {
  492. d.d.errorf("Assigning negative signed value: %v, to unsigned type", i)
  493. return
  494. }
  495. default:
  496. switch {
  497. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  498. ui = uint64(d.bd)
  499. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  500. d.d.errorf("Assigning negative signed value: %v, to unsigned type", int(d.bd))
  501. return
  502. default:
  503. d.d.errorf("Unhandled single-byte unsigned integer value: %s: %x", msgBadDesc, d.bd)
  504. return
  505. }
  506. }
  507. // check overflow (logic adapted from std pkg reflect/value.go OverflowUint()
  508. if bitsize > 0 {
  509. if trunc := (ui << (64 - bitsize)) >> (64 - bitsize); ui != trunc {
  510. d.d.errorf("Overflow uint value: %v", ui)
  511. return
  512. }
  513. }
  514. d.bdRead = false
  515. return
  516. }
  517. // float can either be decoded from msgpack type: float, double or intX
  518. func (d *msgpackDecDriver) DecodeFloat64() (f float64) {
  519. if !d.bdRead {
  520. d.readNextBd()
  521. }
  522. if d.bd == mpFloat {
  523. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  524. } else if d.bd == mpDouble {
  525. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  526. } else {
  527. f = float64(d.DecodeInt(0))
  528. }
  529. d.bdRead = false
  530. return
  531. }
  532. // bool can be decoded from bool, fixnum 0 or 1.
  533. func (d *msgpackDecDriver) DecodeBool() (b bool) {
  534. if !d.bdRead {
  535. d.readNextBd()
  536. }
  537. if d.bd == mpFalse || d.bd == 0 {
  538. // b = false
  539. } else if d.bd == mpTrue || d.bd == 1 {
  540. b = true
  541. } else {
  542. d.d.errorf("Invalid single-byte value for bool: %s: %x", msgBadDesc, d.bd)
  543. return
  544. }
  545. d.bdRead = false
  546. return
  547. }
  548. func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  549. if !d.bdRead {
  550. d.readNextBd()
  551. }
  552. // check if an "array" of uint8's (see ContainerType for how to infer if an array)
  553. bd := d.bd
  554. // DecodeBytes could be from: bin str fixstr fixarray array ...
  555. var clen int
  556. vt := d.ContainerType()
  557. switch vt {
  558. case valueTypeBytes:
  559. // valueTypeBytes may be a mpBin or an mpStr container
  560. if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  561. clen = d.readContainerLen(msgpackContainerBin)
  562. } else {
  563. clen = d.readContainerLen(msgpackContainerStr)
  564. }
  565. case valueTypeString:
  566. clen = d.readContainerLen(msgpackContainerStr)
  567. case valueTypeArray:
  568. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  569. return
  570. // clen = d.readContainerLen(msgpackContainerList)
  571. // // ensure everything after is one byte each
  572. // for i := 0; i < clen; i++ {
  573. // d.readNextBd()
  574. // if d.bd == mpNil {
  575. // bs = append(bs, 0)
  576. // } else if d.bd == mpUint8 {
  577. // bs = append(bs, d.r.readn1())
  578. // } else {
  579. // d.d.errorf("cannot read non-byte into a byte array")
  580. // return
  581. // }
  582. // }
  583. // d.bdRead = false
  584. // return bs
  585. default:
  586. d.d.errorf("invalid container type: expecting bin|str|array, got: 0x%x", uint8(vt))
  587. return
  588. }
  589. // these are (bin|str)(8|16|32)
  590. // println("DecodeBytes: clen: ", clen)
  591. d.bdRead = false
  592. // bytes may be nil, so handle it. if nil, clen=-1.
  593. if clen < 0 {
  594. return nil
  595. }
  596. if zerocopy {
  597. if d.br {
  598. return d.r.readx(clen)
  599. } else if len(bs) == 0 {
  600. bs = d.b[:]
  601. }
  602. }
  603. return decByteSlice(d.r, clen, d.d.h.MaxInitLen, bs)
  604. }
  605. func (d *msgpackDecDriver) DecodeString() (s string) {
  606. return string(d.DecodeBytes(d.b[:], true))
  607. }
  608. func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) {
  609. return d.DecodeBytes(d.b[:], true)
  610. }
  611. func (d *msgpackDecDriver) readNextBd() {
  612. d.bd = d.r.readn1()
  613. d.bdRead = true
  614. }
  615. func (d *msgpackDecDriver) uncacheRead() {
  616. if d.bdRead {
  617. d.r.unreadn1()
  618. d.bdRead = false
  619. }
  620. }
  621. func (d *msgpackDecDriver) ContainerType() (vt valueType) {
  622. if !d.bdRead {
  623. d.readNextBd()
  624. }
  625. bd := d.bd
  626. if bd == mpNil {
  627. return valueTypeNil
  628. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 ||
  629. (!d.h.RawToString &&
  630. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax))) {
  631. return valueTypeBytes
  632. } else if d.h.RawToString &&
  633. (bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax)) {
  634. return valueTypeString
  635. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  636. return valueTypeArray
  637. } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  638. return valueTypeMap
  639. }
  640. // else {
  641. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  642. // }
  643. return valueTypeUnset
  644. }
  645. func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) {
  646. if !d.bdRead {
  647. d.readNextBd()
  648. }
  649. if d.bd == mpNil {
  650. d.bdRead = false
  651. return true
  652. }
  653. return
  654. }
  655. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  656. bd := d.bd
  657. if bd == mpNil {
  658. clen = -1 // to represent nil
  659. } else if bd == ct.b8 {
  660. clen = int(d.r.readn1())
  661. } else if bd == ct.b16 {
  662. clen = int(bigen.Uint16(d.r.readx(2)))
  663. } else if bd == ct.b32 {
  664. clen = int(bigen.Uint32(d.r.readx(4)))
  665. } else if (ct.bFixMin & bd) == ct.bFixMin {
  666. clen = int(ct.bFixMin ^ bd)
  667. } else {
  668. d.d.errorf("readContainerLen: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
  669. return
  670. }
  671. d.bdRead = false
  672. return
  673. }
  674. func (d *msgpackDecDriver) ReadMapStart() int {
  675. if !d.bdRead {
  676. d.readNextBd()
  677. }
  678. return d.readContainerLen(msgpackContainerMap)
  679. }
  680. func (d *msgpackDecDriver) ReadArrayStart() int {
  681. if !d.bdRead {
  682. d.readNextBd()
  683. }
  684. return d.readContainerLen(msgpackContainerList)
  685. }
  686. func (d *msgpackDecDriver) readExtLen() (clen int) {
  687. switch d.bd {
  688. case mpNil:
  689. clen = -1 // to represent nil
  690. case mpFixExt1:
  691. clen = 1
  692. case mpFixExt2:
  693. clen = 2
  694. case mpFixExt4:
  695. clen = 4
  696. case mpFixExt8:
  697. clen = 8
  698. case mpFixExt16:
  699. clen = 16
  700. case mpExt8:
  701. clen = int(d.r.readn1())
  702. case mpExt16:
  703. clen = int(bigen.Uint16(d.r.readx(2)))
  704. case mpExt32:
  705. clen = int(bigen.Uint32(d.r.readx(4)))
  706. default:
  707. d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
  708. return
  709. }
  710. return
  711. }
  712. func (d *msgpackDecDriver) DecodeTime() (t time.Time) {
  713. // decode time from string bytes or ext
  714. if !d.bdRead {
  715. d.readNextBd()
  716. }
  717. if d.bd == mpNil {
  718. d.bdRead = false
  719. return
  720. }
  721. var clen int
  722. switch d.ContainerType() {
  723. case valueTypeBytes, valueTypeString:
  724. clen = d.readContainerLen(msgpackContainerStr)
  725. default:
  726. // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1
  727. d.bdRead = false
  728. b2 := d.r.readn1()
  729. if d.bd == mpFixExt4 && b2 == mpTimeExtTagU {
  730. clen = 4
  731. } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU {
  732. clen = 8
  733. } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU {
  734. clen = 12
  735. } else {
  736. d.d.errorf("invalid sequence of bytes for decoding time as an extension: got 0x%x, 0x%x", d.bd, b2)
  737. return
  738. }
  739. }
  740. return d.decodeTime(clen)
  741. }
  742. func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) {
  743. // bs = d.r.readx(clen)
  744. d.bdRead = false
  745. switch clen {
  746. case 4:
  747. t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC()
  748. case 8:
  749. tv := bigen.Uint64(d.r.readx(8))
  750. t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC()
  751. case 12:
  752. nsec := bigen.Uint32(d.r.readx(4))
  753. sec := bigen.Uint64(d.r.readx(8))
  754. t = time.Unix(int64(sec), int64(nsec)).UTC()
  755. default:
  756. d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen)
  757. return
  758. }
  759. return
  760. }
  761. func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  762. if xtag > 0xff {
  763. d.d.errorf("decodeExt: tag must be <= 0xff; got: %v", xtag)
  764. return
  765. }
  766. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  767. realxtag = uint64(realxtag1)
  768. if ext == nil {
  769. re := rv.(*RawExt)
  770. re.Tag = realxtag
  771. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  772. } else {
  773. ext.ReadExt(rv, xbs)
  774. }
  775. return
  776. }
  777. func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  778. if !d.bdRead {
  779. d.readNextBd()
  780. }
  781. xbd := d.bd
  782. if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 {
  783. xbs = d.DecodeBytes(nil, true)
  784. } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 ||
  785. (xbd >= mpFixStrMin && xbd <= mpFixStrMax) {
  786. xbs = d.DecodeStringAsBytes()
  787. } else {
  788. clen := d.readExtLen()
  789. xtag = d.r.readn1()
  790. if verifyTag && xtag != tag {
  791. d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", xtag, tag)
  792. return
  793. }
  794. xbs = d.r.readx(clen)
  795. }
  796. d.bdRead = false
  797. return
  798. }
  799. //--------------------------------------------------
  800. //MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
  801. type MsgpackHandle struct {
  802. BasicHandle
  803. // RawToString controls how raw bytes are decoded into a nil interface{}.
  804. RawToString bool
  805. // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum.
  806. NoFixedNum bool
  807. // WriteExt flag supports encoding configured extensions with extension tags.
  808. // It also controls whether other elements of the new spec are encoded (ie Str8).
  809. //
  810. // With WriteExt=false, configured extensions are serialized as raw bytes
  811. // and Str8 is not encoded.
  812. //
  813. // A stream can still be decoded into a typed value, provided an appropriate value
  814. // is provided, but the type cannot be inferred from the stream. If no appropriate
  815. // type is provided (e.g. decoding into a nil interface{}), you get back
  816. // a []byte or string based on the setting of RawToString.
  817. WriteExt bool
  818. binaryEncodingType
  819. noElemSeparators
  820. }
  821. // Name returns the name of the handle: msgpack
  822. func (h *MsgpackHandle) Name() string { return "msgpack" }
  823. // SetBytesExt sets an extension
  824. func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  825. return h.SetExt(rt, tag, &setExtWrapper{b: ext})
  826. }
  827. func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver {
  828. return &msgpackEncDriver{e: e, w: e.w, h: h}
  829. }
  830. func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver {
  831. return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  832. }
  833. func (e *msgpackEncDriver) reset() {
  834. e.w = e.e.w
  835. }
  836. func (d *msgpackDecDriver) reset() {
  837. d.r, d.br = d.d.r, d.d.bytes
  838. d.bd, d.bdRead = 0, false
  839. }
  840. //--------------------------------------------------
  841. type msgpackSpecRpcCodec struct {
  842. rpcCodec
  843. }
  844. // /////////////// Spec RPC Codec ///////////////////
  845. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  846. // WriteRequest can write to both a Go service, and other services that do
  847. // not abide by the 1 argument rule of a Go service.
  848. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  849. var bodyArr []interface{}
  850. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  851. bodyArr = ([]interface{})(m)
  852. } else {
  853. bodyArr = []interface{}{body}
  854. }
  855. r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
  856. return c.write(r2, nil, false)
  857. }
  858. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  859. var moe interface{}
  860. if r.Error != "" {
  861. moe = r.Error
  862. }
  863. if moe != nil && body != nil {
  864. body = nil
  865. }
  866. r2 := []interface{}{1, uint32(r.Seq), moe, body}
  867. return c.write(r2, nil, false)
  868. }
  869. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  870. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  871. }
  872. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  873. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  874. }
  875. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  876. if body == nil { // read and discard
  877. return c.read(nil)
  878. }
  879. bodyArr := []interface{}{body}
  880. return c.read(&bodyArr)
  881. }
  882. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  883. if c.isClosed() {
  884. return io.EOF
  885. }
  886. // We read the response header by hand
  887. // so that the body can be decoded on its own from the stream at a later time.
  888. const fia byte = 0x94 //four item array descriptor value
  889. // Not sure why the panic of EOF is swallowed above.
  890. // if bs1 := c.dec.r.readn1(); bs1 != fia {
  891. // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
  892. // return
  893. // }
  894. var ba [1]byte
  895. var n int
  896. for {
  897. n, err = c.r.Read(ba[:])
  898. if err != nil {
  899. return
  900. }
  901. if n == 1 {
  902. break
  903. }
  904. }
  905. var b = ba[0]
  906. if b != fia {
  907. err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, b)
  908. } else {
  909. err = c.read(&b)
  910. if err == nil {
  911. if b != expectTypeByte {
  912. err = fmt.Errorf("Unexpected byte descriptor in header. Expecting %v. Received %v", expectTypeByte, b)
  913. } else {
  914. err = c.read(msgid)
  915. if err == nil {
  916. err = c.read(methodOrError)
  917. }
  918. }
  919. }
  920. }
  921. return
  922. }
  923. //--------------------------------------------------
  924. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  925. // as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  926. type msgpackSpecRpc struct{}
  927. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  928. // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
  929. //
  930. // See GoRpc documentation, for information on buffering for better performance.
  931. var MsgpackSpecRpc msgpackSpecRpc
  932. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  933. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  934. }
  935. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  936. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  937. }
  938. var _ decDriver = (*msgpackDecDriver)(nil)
  939. var _ encDriver = (*msgpackEncDriver)(nil)