msgpack.go 28 KB

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