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