msgpack.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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, _ *Encoder) {
  295. bs := ext.WriteExt(v)
  296. if bs == nil {
  297. e.EncodeNil()
  298. return
  299. }
  300. if e.h.WriteExt {
  301. e.encodeExtPreamble(uint8(xtag), len(bs))
  302. e.w.writeb(bs)
  303. } else {
  304. e.EncodeStringBytesRaw(bs)
  305. }
  306. }
  307. func (e *msgpackEncDriver) EncodeRawExt(re *RawExt, _ *Encoder) {
  308. e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
  309. e.w.writeb(re.Data)
  310. }
  311. func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
  312. if l == 1 {
  313. e.w.writen2(mpFixExt1, xtag)
  314. } else if l == 2 {
  315. e.w.writen2(mpFixExt2, xtag)
  316. } else if l == 4 {
  317. e.w.writen2(mpFixExt4, xtag)
  318. } else if l == 8 {
  319. e.w.writen2(mpFixExt8, xtag)
  320. } else if l == 16 {
  321. e.w.writen2(mpFixExt16, xtag)
  322. } else if l < 256 {
  323. e.w.writen2(mpExt8, byte(l))
  324. e.w.writen1(xtag)
  325. } else if l < 65536 {
  326. e.w.writen1(mpExt16)
  327. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  328. e.w.writen1(xtag)
  329. } else {
  330. e.w.writen1(mpExt32)
  331. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  332. e.w.writen1(xtag)
  333. }
  334. }
  335. func (e *msgpackEncDriver) WriteArrayStart(length int) {
  336. e.writeContainerLen(msgpackContainerList, length)
  337. }
  338. func (e *msgpackEncDriver) WriteMapStart(length int) {
  339. e.writeContainerLen(msgpackContainerMap, length)
  340. }
  341. func (e *msgpackEncDriver) EncodeString(c charEncoding, s string) {
  342. slen := len(s)
  343. if c == cRAW && e.h.WriteExt {
  344. e.writeContainerLen(msgpackContainerBin, slen)
  345. } else {
  346. e.writeContainerLen(msgpackContainerRawLegacy, slen)
  347. }
  348. if slen > 0 {
  349. e.w.writestr(s)
  350. }
  351. }
  352. func (e *msgpackEncDriver) EncodeStringEnc(c charEncoding, s string) {
  353. slen := len(s)
  354. e.writeContainerLen(msgpackContainerStr, slen)
  355. if slen > 0 {
  356. e.w.writestr(s)
  357. }
  358. }
  359. func (e *msgpackEncDriver) EncodeStringBytes(c charEncoding, bs []byte) {
  360. if bs == nil {
  361. e.EncodeNil()
  362. return
  363. }
  364. slen := len(bs)
  365. if c == cRAW && e.h.WriteExt {
  366. e.writeContainerLen(msgpackContainerBin, slen)
  367. } else {
  368. e.writeContainerLen(msgpackContainerRawLegacy, slen)
  369. }
  370. if slen > 0 {
  371. e.w.writeb(bs)
  372. }
  373. }
  374. func (e *msgpackEncDriver) EncodeStringBytesRaw(bs []byte) {
  375. if bs == nil {
  376. e.EncodeNil()
  377. return
  378. }
  379. slen := len(bs)
  380. if e.h.WriteExt {
  381. e.writeContainerLen(msgpackContainerBin, slen)
  382. } else {
  383. e.writeContainerLen(msgpackContainerRawLegacy, slen)
  384. }
  385. if slen > 0 {
  386. e.w.writeb(bs)
  387. }
  388. }
  389. func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
  390. if ct.fixCutoff > 0 && l < int(ct.fixCutoff) {
  391. e.w.writen1(ct.bFixMin | byte(l))
  392. } else if ct.b8 > 0 && l < 256 {
  393. e.w.writen2(ct.b8, uint8(l))
  394. } else if l < 65536 {
  395. e.w.writen1(ct.b16)
  396. bigenHelper{e.x[:2], e.w}.writeUint16(uint16(l))
  397. } else {
  398. e.w.writen1(ct.b32)
  399. bigenHelper{e.x[:4], e.w}.writeUint32(uint32(l))
  400. }
  401. }
  402. //---------------------------------------------
  403. type msgpackDecDriver struct {
  404. d *Decoder
  405. r *decReaderSwitch
  406. h *MsgpackHandle
  407. // b [scratchByteArrayLen]byte
  408. bd byte
  409. bdRead bool
  410. br bool // bytes reader
  411. noBuiltInTypes
  412. // noStreamingCodec
  413. // decNoSeparator
  414. decDriverNoopContainerReader
  415. // _ [3]uint64 // padding
  416. }
  417. // Note: This returns either a primitive (int, bool, etc) for non-containers,
  418. // or a containerType, or a specific type denoting nil or extension.
  419. // It is called when a nil interface{} is passed, leaving it up to the DecDriver
  420. // to introspect the stream and decide how best to decode.
  421. // It deciphers the value by looking at the stream first.
  422. func (d *msgpackDecDriver) DecodeNaked() {
  423. if !d.bdRead {
  424. d.readNextBd()
  425. }
  426. bd := d.bd
  427. n := d.d.naked()
  428. var decodeFurther bool
  429. switch bd {
  430. case mpNil:
  431. n.v = valueTypeNil
  432. d.bdRead = false
  433. case mpFalse:
  434. n.v = valueTypeBool
  435. n.b = false
  436. case mpTrue:
  437. n.v = valueTypeBool
  438. n.b = true
  439. case mpFloat:
  440. n.v = valueTypeFloat
  441. n.f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  442. case mpDouble:
  443. n.v = valueTypeFloat
  444. n.f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  445. case mpUint8:
  446. n.v = valueTypeUint
  447. n.u = uint64(d.r.readn1())
  448. case mpUint16:
  449. n.v = valueTypeUint
  450. n.u = uint64(bigen.Uint16(d.r.readx(2)))
  451. case mpUint32:
  452. n.v = valueTypeUint
  453. n.u = uint64(bigen.Uint32(d.r.readx(4)))
  454. case mpUint64:
  455. n.v = valueTypeUint
  456. n.u = uint64(bigen.Uint64(d.r.readx(8)))
  457. case mpInt8:
  458. n.v = valueTypeInt
  459. n.i = int64(int8(d.r.readn1()))
  460. case mpInt16:
  461. n.v = valueTypeInt
  462. n.i = int64(int16(bigen.Uint16(d.r.readx(2))))
  463. case mpInt32:
  464. n.v = valueTypeInt
  465. n.i = int64(int32(bigen.Uint32(d.r.readx(4))))
  466. case mpInt64:
  467. n.v = valueTypeInt
  468. n.i = int64(int64(bigen.Uint64(d.r.readx(8))))
  469. default:
  470. switch {
  471. case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
  472. // positive fixnum (always signed)
  473. n.v = valueTypeInt
  474. n.i = int64(int8(bd))
  475. case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
  476. // negative fixnum
  477. n.v = valueTypeInt
  478. n.i = int64(int8(bd))
  479. case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
  480. if d.h.WriteExt {
  481. n.v = valueTypeString
  482. n.s = d.DecodeString()
  483. } else {
  484. n.v = valueTypeBytes
  485. n.l = d.DecodeBytes(nil, false)
  486. }
  487. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  488. decNakedReadRawBytes(d, d.d, n, d.h.RawToString)
  489. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  490. n.v = valueTypeArray
  491. decodeFurther = true
  492. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  493. n.v = valueTypeMap
  494. decodeFurther = true
  495. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  496. n.v = valueTypeExt
  497. clen := d.readExtLen()
  498. n.u = uint64(d.r.readn1())
  499. if n.u == uint64(mpTimeExtTagU) {
  500. n.v = valueTypeTime
  501. n.t = d.decodeTime(clen)
  502. } else if d.br {
  503. n.l = d.r.readx(uint(clen))
  504. } else {
  505. n.l = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:])
  506. }
  507. default:
  508. d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd))
  509. }
  510. }
  511. if !decodeFurther {
  512. d.bdRead = false
  513. }
  514. if n.v == valueTypeUint && d.h.SignedInteger {
  515. n.v = valueTypeInt
  516. n.i = int64(n.u)
  517. }
  518. }
  519. // int can be decoded from msgpack type: intXXX or uintXXX
  520. func (d *msgpackDecDriver) DecodeInt64() (i int64) {
  521. if !d.bdRead {
  522. d.readNextBd()
  523. }
  524. switch d.bd {
  525. case mpUint8:
  526. i = int64(uint64(d.r.readn1()))
  527. case mpUint16:
  528. i = int64(uint64(bigen.Uint16(d.r.readx(2))))
  529. case mpUint32:
  530. i = int64(uint64(bigen.Uint32(d.r.readx(4))))
  531. case mpUint64:
  532. i = int64(bigen.Uint64(d.r.readx(8)))
  533. case mpInt8:
  534. i = int64(int8(d.r.readn1()))
  535. case mpInt16:
  536. i = int64(int16(bigen.Uint16(d.r.readx(2))))
  537. case mpInt32:
  538. i = int64(int32(bigen.Uint32(d.r.readx(4))))
  539. case mpInt64:
  540. i = int64(bigen.Uint64(d.r.readx(8)))
  541. default:
  542. switch {
  543. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  544. i = int64(int8(d.bd))
  545. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  546. i = int64(int8(d.bd))
  547. default:
  548. d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  549. return
  550. }
  551. }
  552. d.bdRead = false
  553. return
  554. }
  555. // uint can be decoded from msgpack type: intXXX or uintXXX
  556. func (d *msgpackDecDriver) DecodeUint64() (ui uint64) {
  557. if !d.bdRead {
  558. d.readNextBd()
  559. }
  560. switch d.bd {
  561. case mpUint8:
  562. ui = uint64(d.r.readn1())
  563. case mpUint16:
  564. ui = uint64(bigen.Uint16(d.r.readx(2)))
  565. case mpUint32:
  566. ui = uint64(bigen.Uint32(d.r.readx(4)))
  567. case mpUint64:
  568. ui = bigen.Uint64(d.r.readx(8))
  569. case mpInt8:
  570. if i := int64(int8(d.r.readn1())); i >= 0 {
  571. ui = uint64(i)
  572. } else {
  573. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  574. return
  575. }
  576. case mpInt16:
  577. if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 {
  578. ui = uint64(i)
  579. } else {
  580. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  581. return
  582. }
  583. case mpInt32:
  584. if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 {
  585. ui = uint64(i)
  586. } else {
  587. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  588. return
  589. }
  590. case mpInt64:
  591. if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 {
  592. ui = uint64(i)
  593. } else {
  594. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  595. return
  596. }
  597. default:
  598. switch {
  599. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  600. ui = uint64(d.bd)
  601. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  602. d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd))
  603. return
  604. default:
  605. d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  606. return
  607. }
  608. }
  609. d.bdRead = false
  610. return
  611. }
  612. // float can either be decoded from msgpack type: float, double or intX
  613. func (d *msgpackDecDriver) DecodeFloat64() (f float64) {
  614. if !d.bdRead {
  615. d.readNextBd()
  616. }
  617. if d.bd == mpFloat {
  618. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  619. } else if d.bd == mpDouble {
  620. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  621. } else {
  622. f = float64(d.DecodeInt64())
  623. }
  624. d.bdRead = false
  625. return
  626. }
  627. // bool can be decoded from bool, fixnum 0 or 1.
  628. func (d *msgpackDecDriver) DecodeBool() (b bool) {
  629. if !d.bdRead {
  630. d.readNextBd()
  631. }
  632. if d.bd == mpFalse || d.bd == 0 {
  633. // b = false
  634. } else if d.bd == mpTrue || d.bd == 1 {
  635. b = true
  636. } else {
  637. d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  638. return
  639. }
  640. d.bdRead = false
  641. return
  642. }
  643. func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  644. if !d.bdRead {
  645. d.readNextBd()
  646. }
  647. bd := d.bd
  648. var clen int
  649. if bd == mpNil {
  650. d.bdRead = false
  651. return
  652. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  653. clen = d.readContainerLen(msgpackContainerBin) // binary
  654. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  655. clen = d.readContainerLen(msgpackContainerStr) // string/raw
  656. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  657. // check if an "array" of uint8's
  658. if zerocopy && len(bs) == 0 {
  659. bs = d.d.b[:]
  660. }
  661. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  662. return
  663. } else {
  664. d.d.errorf("invalid byte descriptor for decoding bytes, got: 0x%x", d.bd)
  665. return
  666. }
  667. d.bdRead = false
  668. if zerocopy {
  669. if d.br {
  670. return d.r.readx(uint(clen))
  671. } else if len(bs) == 0 {
  672. bs = d.d.b[:]
  673. }
  674. }
  675. return decByteSlice(d.r, clen, d.h.MaxInitLen, bs)
  676. }
  677. func (d *msgpackDecDriver) DecodeString() (s string) {
  678. return string(d.DecodeBytes(d.d.b[:], true))
  679. }
  680. func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) {
  681. return d.DecodeBytes(d.d.b[:], true)
  682. }
  683. func (d *msgpackDecDriver) readNextBd() {
  684. d.bd = d.r.readn1()
  685. d.bdRead = true
  686. }
  687. func (d *msgpackDecDriver) uncacheRead() {
  688. if d.bdRead {
  689. d.r.unreadn1()
  690. d.bdRead = false
  691. }
  692. }
  693. func (d *msgpackDecDriver) ContainerType() (vt valueType) {
  694. if !d.bdRead {
  695. d.readNextBd()
  696. }
  697. bd := d.bd
  698. // if bd == mpNil {
  699. // // nil
  700. // } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  701. // // binary
  702. // } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  703. // // string/raw
  704. // } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  705. // // array
  706. // } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  707. // // map
  708. // }
  709. if bd == mpNil {
  710. return valueTypeNil
  711. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  712. return valueTypeBytes
  713. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  714. if d.h.WriteExt { // UTF-8 string (new spec)
  715. return valueTypeString
  716. }
  717. return valueTypeBytes // raw (old spec)
  718. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  719. return valueTypeArray
  720. } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  721. return valueTypeMap
  722. }
  723. // else {
  724. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  725. // }
  726. return valueTypeUnset
  727. }
  728. func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) {
  729. if !d.bdRead {
  730. d.readNextBd()
  731. }
  732. if d.bd == mpNil {
  733. d.bdRead = false
  734. return true
  735. }
  736. return
  737. }
  738. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  739. bd := d.bd
  740. if bd == mpNil {
  741. clen = -1 // to represent nil
  742. } else if bd == ct.b8 {
  743. clen = int(d.r.readn1())
  744. } else if bd == ct.b16 {
  745. clen = int(bigen.Uint16(d.r.readx(2)))
  746. } else if bd == ct.b32 {
  747. clen = int(bigen.Uint32(d.r.readx(4)))
  748. } else if (ct.bFixMin & bd) == ct.bFixMin {
  749. clen = int(ct.bFixMin ^ bd)
  750. } else {
  751. d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
  752. return
  753. }
  754. d.bdRead = false
  755. return
  756. }
  757. func (d *msgpackDecDriver) ReadMapStart() int {
  758. if !d.bdRead {
  759. d.readNextBd()
  760. }
  761. return d.readContainerLen(msgpackContainerMap)
  762. }
  763. func (d *msgpackDecDriver) ReadArrayStart() int {
  764. if !d.bdRead {
  765. d.readNextBd()
  766. }
  767. return d.readContainerLen(msgpackContainerList)
  768. }
  769. func (d *msgpackDecDriver) readExtLen() (clen int) {
  770. switch d.bd {
  771. case mpNil:
  772. clen = -1 // to represent nil
  773. case mpFixExt1:
  774. clen = 1
  775. case mpFixExt2:
  776. clen = 2
  777. case mpFixExt4:
  778. clen = 4
  779. case mpFixExt8:
  780. clen = 8
  781. case mpFixExt16:
  782. clen = 16
  783. case mpExt8:
  784. clen = int(d.r.readn1())
  785. case mpExt16:
  786. clen = int(bigen.Uint16(d.r.readx(2)))
  787. case mpExt32:
  788. clen = int(bigen.Uint32(d.r.readx(4)))
  789. default:
  790. d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
  791. return
  792. }
  793. return
  794. }
  795. func (d *msgpackDecDriver) DecodeTime() (t time.Time) {
  796. // decode time from string bytes or ext
  797. if !d.bdRead {
  798. d.readNextBd()
  799. }
  800. bd := d.bd
  801. var clen int
  802. if bd == mpNil {
  803. d.bdRead = false
  804. return
  805. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  806. clen = d.readContainerLen(msgpackContainerBin) // binary
  807. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  808. clen = d.readContainerLen(msgpackContainerStr) // string/raw
  809. } else {
  810. // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1
  811. d.bdRead = false
  812. b2 := d.r.readn1()
  813. if d.bd == mpFixExt4 && b2 == mpTimeExtTagU {
  814. clen = 4
  815. } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU {
  816. clen = 8
  817. } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU {
  818. clen = 12
  819. } else {
  820. d.d.errorf("invalid stream for decoding time as extension: got 0x%x, 0x%x", d.bd, b2)
  821. return
  822. }
  823. }
  824. return d.decodeTime(clen)
  825. }
  826. func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) {
  827. // bs = d.r.readx(clen)
  828. d.bdRead = false
  829. switch clen {
  830. case 4:
  831. t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC()
  832. case 8:
  833. tv := bigen.Uint64(d.r.readx(8))
  834. t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC()
  835. case 12:
  836. nsec := bigen.Uint32(d.r.readx(4))
  837. sec := bigen.Uint64(d.r.readx(8))
  838. t = time.Unix(int64(sec), int64(nsec)).UTC()
  839. default:
  840. d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen)
  841. return
  842. }
  843. return
  844. }
  845. func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  846. if xtag > 0xff {
  847. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  848. return
  849. }
  850. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  851. realxtag = uint64(realxtag1)
  852. if ext == nil {
  853. re := rv.(*RawExt)
  854. re.Tag = realxtag
  855. re.Data = detachZeroCopyBytes(d.br, re.Data, xbs)
  856. } else {
  857. ext.ReadExt(rv, xbs)
  858. }
  859. return
  860. }
  861. func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xtag byte, xbs []byte) {
  862. if !d.bdRead {
  863. d.readNextBd()
  864. }
  865. xbd := d.bd
  866. if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 {
  867. xbs = d.DecodeBytes(nil, true)
  868. } else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 ||
  869. (xbd >= mpFixStrMin && xbd <= mpFixStrMax) {
  870. xbs = d.DecodeStringAsBytes()
  871. } else {
  872. clen := d.readExtLen()
  873. xtag = d.r.readn1()
  874. if verifyTag && xtag != tag {
  875. d.d.errorf("wrong extension tag - got %b, expecting %v", xtag, tag)
  876. return
  877. }
  878. if d.br {
  879. xbs = d.r.readx(uint(clen))
  880. } else {
  881. xbs = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:])
  882. }
  883. }
  884. d.bdRead = false
  885. return
  886. }
  887. //--------------------------------------------------
  888. //MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
  889. type MsgpackHandle struct {
  890. BasicHandle
  891. // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum.
  892. NoFixedNum bool
  893. // WriteExt controls whether the new spec is honored.
  894. //
  895. // With WriteExt=true, we can encode configured extensions with extension tags
  896. // and encode string/[]byte/extensions in a way compatible with the new spec
  897. // but incompatible with the old spec.
  898. //
  899. // For compatibility with the old spec, set WriteExt=false.
  900. //
  901. // With WriteExt=false:
  902. // configured extensions are serialized as raw bytes (not msgpack extensions).
  903. // reserved byte descriptors like Str8 and those enabling the new msgpack Binary type
  904. // are not encoded.
  905. WriteExt bool
  906. // PositiveIntUnsigned says to encode positive integers as unsigned.
  907. PositiveIntUnsigned bool
  908. binaryEncodingType
  909. noElemSeparators
  910. // _ [1]uint64 // padding
  911. }
  912. // Name returns the name of the handle: msgpack
  913. func (h *MsgpackHandle) Name() string { return "msgpack" }
  914. // SetBytesExt sets an extension
  915. func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  916. return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
  917. }
  918. func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver {
  919. return &msgpackEncDriver{e: e, w: e.w, h: h}
  920. }
  921. func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver {
  922. return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  923. }
  924. func (e *msgpackEncDriver) reset() {
  925. e.w = e.e.w
  926. }
  927. func (d *msgpackDecDriver) reset() {
  928. d.r, d.br = d.d.r, d.d.bytes
  929. d.bd, d.bdRead = 0, false
  930. }
  931. //--------------------------------------------------
  932. type msgpackSpecRpcCodec struct {
  933. rpcCodec
  934. }
  935. // /////////////// Spec RPC Codec ///////////////////
  936. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  937. // WriteRequest can write to both a Go service, and other services that do
  938. // not abide by the 1 argument rule of a Go service.
  939. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  940. var bodyArr []interface{}
  941. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  942. bodyArr = ([]interface{})(m)
  943. } else {
  944. bodyArr = []interface{}{body}
  945. }
  946. r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
  947. return c.write(r2, nil, false)
  948. }
  949. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  950. var moe interface{}
  951. if r.Error != "" {
  952. moe = r.Error
  953. }
  954. if moe != nil && body != nil {
  955. body = nil
  956. }
  957. r2 := []interface{}{1, uint32(r.Seq), moe, body}
  958. return c.write(r2, nil, false)
  959. }
  960. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  961. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  962. }
  963. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  964. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  965. }
  966. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  967. if body == nil { // read and discard
  968. return c.read(nil)
  969. }
  970. bodyArr := []interface{}{body}
  971. return c.read(&bodyArr)
  972. }
  973. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  974. if cls := c.cls.load(); cls.closed {
  975. return io.EOF
  976. }
  977. // We read the response header by hand
  978. // so that the body can be decoded on its own from the stream at a later time.
  979. const fia byte = 0x94 //four item array descriptor value
  980. // Not sure why the panic of EOF is swallowed above.
  981. // if bs1 := c.dec.r.readn1(); bs1 != fia {
  982. // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
  983. // return
  984. // }
  985. var ba [1]byte
  986. var n int
  987. for {
  988. n, err = c.r.Read(ba[:])
  989. if err != nil {
  990. return
  991. }
  992. if n == 1 {
  993. break
  994. }
  995. }
  996. var b = ba[0]
  997. if b != fia {
  998. err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b))
  999. } else {
  1000. err = c.read(&b)
  1001. if err == nil {
  1002. if b != expectTypeByte {
  1003. err = fmt.Errorf("%s - expecting %v but got %x/%s",
  1004. msgBadDesc, expectTypeByte, b, mpdesc(b))
  1005. } else {
  1006. err = c.read(msgid)
  1007. if err == nil {
  1008. err = c.read(methodOrError)
  1009. }
  1010. }
  1011. }
  1012. }
  1013. return
  1014. }
  1015. //--------------------------------------------------
  1016. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  1017. // as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  1018. type msgpackSpecRpc struct{}
  1019. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  1020. // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
  1021. //
  1022. // See GoRpc documentation, for information on buffering for better performance.
  1023. var MsgpackSpecRpc msgpackSpecRpc
  1024. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  1025. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1026. }
  1027. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  1028. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1029. }
  1030. var _ decDriver = (*msgpackDecDriver)(nil)
  1031. var _ encDriver = (*msgpackEncDriver)(nil)