msgpack.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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.RawToString {
  481. n.v = valueTypeString
  482. n.s = string(d.DecodeBytes(d.d.b[:], true))
  483. } else {
  484. n.v = valueTypeBytes
  485. n.l = d.DecodeBytes(nil, false)
  486. }
  487. case bd == mpBin8, bd == mpBin16, bd == mpBin32:
  488. n.v = valueTypeBytes
  489. n.l = d.DecodeBytes(nil, false)
  490. case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
  491. n.v = valueTypeArray
  492. decodeFurther = true
  493. case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
  494. n.v = valueTypeMap
  495. decodeFurther = true
  496. case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
  497. n.v = valueTypeExt
  498. clen := d.readExtLen()
  499. n.u = uint64(d.r.readn1())
  500. if n.u == uint64(mpTimeExtTagU) {
  501. n.v = valueTypeTime
  502. n.t = d.decodeTime(clen)
  503. } else if d.br {
  504. n.l = d.r.readx(uint(clen))
  505. } else {
  506. n.l = decByteSlice(d.r, clen, d.d.h.MaxInitLen, d.d.b[:])
  507. }
  508. default:
  509. d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd))
  510. }
  511. }
  512. if !decodeFurther {
  513. d.bdRead = false
  514. }
  515. if n.v == valueTypeUint && d.h.SignedInteger {
  516. n.v = valueTypeInt
  517. n.i = int64(n.u)
  518. }
  519. }
  520. // int can be decoded from msgpack type: intXXX or uintXXX
  521. func (d *msgpackDecDriver) DecodeInt64() (i int64) {
  522. if !d.bdRead {
  523. d.readNextBd()
  524. }
  525. switch d.bd {
  526. case mpUint8:
  527. i = int64(uint64(d.r.readn1()))
  528. case mpUint16:
  529. i = int64(uint64(bigen.Uint16(d.r.readx(2))))
  530. case mpUint32:
  531. i = int64(uint64(bigen.Uint32(d.r.readx(4))))
  532. case mpUint64:
  533. i = int64(bigen.Uint64(d.r.readx(8)))
  534. case mpInt8:
  535. i = int64(int8(d.r.readn1()))
  536. case mpInt16:
  537. i = int64(int16(bigen.Uint16(d.r.readx(2))))
  538. case mpInt32:
  539. i = int64(int32(bigen.Uint32(d.r.readx(4))))
  540. case mpInt64:
  541. i = int64(bigen.Uint64(d.r.readx(8)))
  542. default:
  543. switch {
  544. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  545. i = int64(int8(d.bd))
  546. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  547. i = int64(int8(d.bd))
  548. default:
  549. d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  550. return
  551. }
  552. }
  553. d.bdRead = false
  554. return
  555. }
  556. // uint can be decoded from msgpack type: intXXX or uintXXX
  557. func (d *msgpackDecDriver) DecodeUint64() (ui uint64) {
  558. if !d.bdRead {
  559. d.readNextBd()
  560. }
  561. switch d.bd {
  562. case mpUint8:
  563. ui = uint64(d.r.readn1())
  564. case mpUint16:
  565. ui = uint64(bigen.Uint16(d.r.readx(2)))
  566. case mpUint32:
  567. ui = uint64(bigen.Uint32(d.r.readx(4)))
  568. case mpUint64:
  569. ui = bigen.Uint64(d.r.readx(8))
  570. case mpInt8:
  571. if i := int64(int8(d.r.readn1())); i >= 0 {
  572. ui = uint64(i)
  573. } else {
  574. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  575. return
  576. }
  577. case mpInt16:
  578. if i := int64(int16(bigen.Uint16(d.r.readx(2)))); i >= 0 {
  579. ui = uint64(i)
  580. } else {
  581. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  582. return
  583. }
  584. case mpInt32:
  585. if i := int64(int32(bigen.Uint32(d.r.readx(4)))); i >= 0 {
  586. ui = uint64(i)
  587. } else {
  588. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  589. return
  590. }
  591. case mpInt64:
  592. if i := int64(bigen.Uint64(d.r.readx(8))); i >= 0 {
  593. ui = uint64(i)
  594. } else {
  595. d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
  596. return
  597. }
  598. default:
  599. switch {
  600. case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
  601. ui = uint64(d.bd)
  602. case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
  603. d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd))
  604. return
  605. default:
  606. d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  607. return
  608. }
  609. }
  610. d.bdRead = false
  611. return
  612. }
  613. // float can either be decoded from msgpack type: float, double or intX
  614. func (d *msgpackDecDriver) DecodeFloat64() (f float64) {
  615. if !d.bdRead {
  616. d.readNextBd()
  617. }
  618. if d.bd == mpFloat {
  619. f = float64(math.Float32frombits(bigen.Uint32(d.r.readx(4))))
  620. } else if d.bd == mpDouble {
  621. f = math.Float64frombits(bigen.Uint64(d.r.readx(8)))
  622. } else {
  623. f = float64(d.DecodeInt64())
  624. }
  625. d.bdRead = false
  626. return
  627. }
  628. // bool can be decoded from bool, fixnum 0 or 1.
  629. func (d *msgpackDecDriver) DecodeBool() (b bool) {
  630. if !d.bdRead {
  631. d.readNextBd()
  632. }
  633. if d.bd == mpFalse || d.bd == 0 {
  634. // b = false
  635. } else if d.bd == mpTrue || d.bd == 1 {
  636. b = true
  637. } else {
  638. d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
  639. return
  640. }
  641. d.bdRead = false
  642. return
  643. }
  644. func (d *msgpackDecDriver) DecodeBytes(bs []byte, zerocopy bool) (bsOut []byte) {
  645. if !d.bdRead {
  646. d.readNextBd()
  647. }
  648. bd := d.bd
  649. var clen int
  650. if bd == mpNil {
  651. d.bdRead = false
  652. return
  653. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  654. clen = d.readContainerLen(msgpackContainerBin) // binary
  655. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  656. clen = d.readContainerLen(msgpackContainerStr) // string/raw
  657. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  658. // check if an "array" of uint8's
  659. if zerocopy && len(bs) == 0 {
  660. bs = d.d.b[:]
  661. }
  662. bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
  663. return
  664. } else {
  665. d.d.errorf("invalid byte descriptor for decoding bytes, got: 0x%x", d.bd)
  666. return
  667. }
  668. d.bdRead = false
  669. if zerocopy {
  670. if d.br {
  671. return d.r.readx(uint(clen))
  672. } else if len(bs) == 0 {
  673. bs = d.d.b[:]
  674. }
  675. }
  676. return decByteSlice(d.r, clen, d.h.MaxInitLen, bs)
  677. }
  678. func (d *msgpackDecDriver) DecodeString() (s string) {
  679. return string(d.DecodeBytes(d.d.b[:], true))
  680. }
  681. func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) {
  682. return d.DecodeBytes(d.d.b[:], true)
  683. }
  684. func (d *msgpackDecDriver) readNextBd() {
  685. d.bd = d.r.readn1()
  686. d.bdRead = true
  687. }
  688. func (d *msgpackDecDriver) uncacheRead() {
  689. if d.bdRead {
  690. d.r.unreadn1()
  691. d.bdRead = false
  692. }
  693. }
  694. func (d *msgpackDecDriver) ContainerType() (vt valueType) {
  695. if !d.bdRead {
  696. d.readNextBd()
  697. }
  698. bd := d.bd
  699. // if bd == mpNil {
  700. // // nil
  701. // } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  702. // // binary
  703. // } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  704. // // string/raw
  705. // } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  706. // // array
  707. // } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  708. // // map
  709. // }
  710. if bd == mpNil {
  711. return valueTypeNil
  712. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  713. return valueTypeBytes
  714. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  715. if d.h.RawToString {
  716. return valueTypeString
  717. }
  718. return valueTypeBytes
  719. } else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
  720. return valueTypeArray
  721. } else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
  722. return valueTypeMap
  723. }
  724. // else {
  725. // d.d.errorf("isContainerType: unsupported parameter: %v", vt)
  726. // }
  727. return valueTypeUnset
  728. }
  729. func (d *msgpackDecDriver) TryDecodeAsNil() (v bool) {
  730. if !d.bdRead {
  731. d.readNextBd()
  732. }
  733. if d.bd == mpNil {
  734. d.bdRead = false
  735. return true
  736. }
  737. return
  738. }
  739. func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
  740. bd := d.bd
  741. if bd == mpNil {
  742. clen = -1 // to represent nil
  743. } else if bd == ct.b8 {
  744. clen = int(d.r.readn1())
  745. } else if bd == ct.b16 {
  746. clen = int(bigen.Uint16(d.r.readx(2)))
  747. } else if bd == ct.b32 {
  748. clen = int(bigen.Uint32(d.r.readx(4)))
  749. } else if (ct.bFixMin & bd) == ct.bFixMin {
  750. clen = int(ct.bFixMin ^ bd)
  751. } else {
  752. d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
  753. return
  754. }
  755. d.bdRead = false
  756. return
  757. }
  758. func (d *msgpackDecDriver) ReadMapStart() int {
  759. if !d.bdRead {
  760. d.readNextBd()
  761. }
  762. return d.readContainerLen(msgpackContainerMap)
  763. }
  764. func (d *msgpackDecDriver) ReadArrayStart() int {
  765. if !d.bdRead {
  766. d.readNextBd()
  767. }
  768. return d.readContainerLen(msgpackContainerList)
  769. }
  770. func (d *msgpackDecDriver) readExtLen() (clen int) {
  771. switch d.bd {
  772. case mpNil:
  773. clen = -1 // to represent nil
  774. case mpFixExt1:
  775. clen = 1
  776. case mpFixExt2:
  777. clen = 2
  778. case mpFixExt4:
  779. clen = 4
  780. case mpFixExt8:
  781. clen = 8
  782. case mpFixExt16:
  783. clen = 16
  784. case mpExt8:
  785. clen = int(d.r.readn1())
  786. case mpExt16:
  787. clen = int(bigen.Uint16(d.r.readx(2)))
  788. case mpExt32:
  789. clen = int(bigen.Uint32(d.r.readx(4)))
  790. default:
  791. d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
  792. return
  793. }
  794. return
  795. }
  796. func (d *msgpackDecDriver) DecodeTime() (t time.Time) {
  797. // decode time from string bytes or ext
  798. if !d.bdRead {
  799. d.readNextBd()
  800. }
  801. bd := d.bd
  802. var clen int
  803. if bd == mpNil {
  804. d.bdRead = false
  805. return
  806. } else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
  807. clen = d.readContainerLen(msgpackContainerBin) // binary
  808. } else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 || (bd >= mpFixStrMin && bd <= mpFixStrMax) {
  809. clen = d.readContainerLen(msgpackContainerStr) // string/raw
  810. } else {
  811. // expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1
  812. d.bdRead = false
  813. b2 := d.r.readn1()
  814. if d.bd == mpFixExt4 && b2 == mpTimeExtTagU {
  815. clen = 4
  816. } else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU {
  817. clen = 8
  818. } else if d.bd == mpExt8 && b2 == 12 && d.r.readn1() == mpTimeExtTagU {
  819. clen = 12
  820. } else {
  821. d.d.errorf("invalid stream for decoding time as extension: got 0x%x, 0x%x", d.bd, b2)
  822. return
  823. }
  824. }
  825. return d.decodeTime(clen)
  826. }
  827. func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) {
  828. // bs = d.r.readx(clen)
  829. d.bdRead = false
  830. switch clen {
  831. case 4:
  832. t = time.Unix(int64(bigen.Uint32(d.r.readx(4))), 0).UTC()
  833. case 8:
  834. tv := bigen.Uint64(d.r.readx(8))
  835. t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC()
  836. case 12:
  837. nsec := bigen.Uint32(d.r.readx(4))
  838. sec := bigen.Uint64(d.r.readx(8))
  839. t = time.Unix(int64(sec), int64(nsec)).UTC()
  840. default:
  841. d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen)
  842. return
  843. }
  844. return
  845. }
  846. func (d *msgpackDecDriver) DecodeExt(rv interface{}, xtag uint64, ext Ext) (realxtag uint64) {
  847. if xtag > 0xff {
  848. d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
  849. return
  850. }
  851. realxtag1, xbs := d.decodeExtV(ext != nil, uint8(xtag))
  852. realxtag = uint64(realxtag1)
  853. if ext == nil {
  854. re := rv.(*RawExt)
  855. re.Tag = realxtag
  856. re.Data = detachZeroCopyBytes(d.br, re.Data, 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. // RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
  893. // By default, they are decoded as []byte,
  894. // but can be decoded as string (if configured).
  895. RawToString bool
  896. // NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum.
  897. NoFixedNum bool
  898. // WriteExt controls whether the new spec is honored.
  899. //
  900. // With WriteExt=true, we can encode configured extensions with extension tags
  901. // and encode string/[]byte/extensions in a way compatible with the new spec
  902. // but incompatible with the old spec.
  903. //
  904. // For compatibility with the old spec, set WriteExt=false.
  905. //
  906. // With WriteExt=false:
  907. // configured extensions are serialized as raw bytes (not msgpack extensions).
  908. // reserved byte descriptors like Str8 and those enabling the new msgpack Binary type
  909. // are not encoded.
  910. WriteExt bool
  911. // PositiveIntUnsigned says to encode positive integers as unsigned.
  912. PositiveIntUnsigned bool
  913. binaryEncodingType
  914. noElemSeparators
  915. // _ [1]uint64 // padding
  916. }
  917. // Name returns the name of the handle: msgpack
  918. func (h *MsgpackHandle) Name() string { return "msgpack" }
  919. // SetBytesExt sets an extension
  920. func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
  921. return h.SetExt(rt, tag, &extWrapper{ext, interfaceExtFailer{}})
  922. }
  923. func (h *MsgpackHandle) newEncDriver(e *Encoder) encDriver {
  924. return &msgpackEncDriver{e: e, w: e.w, h: h}
  925. }
  926. func (h *MsgpackHandle) newDecDriver(d *Decoder) decDriver {
  927. return &msgpackDecDriver{d: d, h: h, r: d.r, br: d.bytes}
  928. }
  929. func (e *msgpackEncDriver) reset() {
  930. e.w = e.e.w
  931. }
  932. func (d *msgpackDecDriver) reset() {
  933. d.r, d.br = d.d.r, d.d.bytes
  934. d.bd, d.bdRead = 0, false
  935. }
  936. //--------------------------------------------------
  937. type msgpackSpecRpcCodec struct {
  938. rpcCodec
  939. }
  940. // /////////////// Spec RPC Codec ///////////////////
  941. func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
  942. // WriteRequest can write to both a Go service, and other services that do
  943. // not abide by the 1 argument rule of a Go service.
  944. // We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
  945. var bodyArr []interface{}
  946. if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
  947. bodyArr = ([]interface{})(m)
  948. } else {
  949. bodyArr = []interface{}{body}
  950. }
  951. r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
  952. return c.write(r2, nil, false)
  953. }
  954. func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
  955. var moe interface{}
  956. if r.Error != "" {
  957. moe = r.Error
  958. }
  959. if moe != nil && body != nil {
  960. body = nil
  961. }
  962. r2 := []interface{}{1, uint32(r.Seq), moe, body}
  963. return c.write(r2, nil, false)
  964. }
  965. func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
  966. return c.parseCustomHeader(1, &r.Seq, &r.Error)
  967. }
  968. func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
  969. return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
  970. }
  971. func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
  972. if body == nil { // read and discard
  973. return c.read(nil)
  974. }
  975. bodyArr := []interface{}{body}
  976. return c.read(&bodyArr)
  977. }
  978. func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
  979. if cls := c.cls.load(); cls.closed {
  980. return io.EOF
  981. }
  982. // We read the response header by hand
  983. // so that the body can be decoded on its own from the stream at a later time.
  984. const fia byte = 0x94 //four item array descriptor value
  985. // Not sure why the panic of EOF is swallowed above.
  986. // if bs1 := c.dec.r.readn1(); bs1 != fia {
  987. // err = fmt.Errorf("Unexpected value for array descriptor: Expecting %v. Received %v", fia, bs1)
  988. // return
  989. // }
  990. var ba [1]byte
  991. var n int
  992. for {
  993. n, err = c.r.Read(ba[:])
  994. if err != nil {
  995. return
  996. }
  997. if n == 1 {
  998. break
  999. }
  1000. }
  1001. var b = ba[0]
  1002. if b != fia {
  1003. err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b))
  1004. } else {
  1005. err = c.read(&b)
  1006. if err == nil {
  1007. if b != expectTypeByte {
  1008. err = fmt.Errorf("%s - expecting %v but got %x/%s",
  1009. msgBadDesc, expectTypeByte, b, mpdesc(b))
  1010. } else {
  1011. err = c.read(msgid)
  1012. if err == nil {
  1013. err = c.read(methodOrError)
  1014. }
  1015. }
  1016. }
  1017. }
  1018. return
  1019. }
  1020. //--------------------------------------------------
  1021. // msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
  1022. // as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
  1023. type msgpackSpecRpc struct{}
  1024. // MsgpackSpecRpc implements Rpc using the communication protocol defined in
  1025. // the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
  1026. //
  1027. // See GoRpc documentation, for information on buffering for better performance.
  1028. var MsgpackSpecRpc msgpackSpecRpc
  1029. func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
  1030. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1031. }
  1032. func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
  1033. return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
  1034. }
  1035. var _ decDriver = (*msgpackDecDriver)(nil)
  1036. var _ encDriver = (*msgpackEncDriver)(nil)