OSDN Git Service

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