msgpack.go 29 KB

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