msgpack.go 29 KB

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