msgpack.go 28 KB

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