msgpack.go 27 KB

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