github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/proto/binary/binary.go (about) 1 package binary 2 3 import ( 4 "encoding/binary" 5 "errors" 6 "io" 7 "math" 8 "sync" 9 "unicode/utf8" 10 "unsafe" 11 12 "github.com/cloudwego/dynamicgo/internal/primitive" 13 "github.com/cloudwego/dynamicgo/internal/rt" 14 "github.com/cloudwego/dynamicgo/meta" 15 "github.com/cloudwego/dynamicgo/proto" 16 "github.com/cloudwego/dynamicgo/proto/protowire" 17 ) 18 19 // memory resize factor 20 const ( 21 defaultBufferSize = 4096 22 growBufferFactor = 1 23 defaultListSize = 5 24 speculativeLength = 1 // prefixed bytes length when write complex fields 25 ) 26 27 var ( 28 errDismatchPrimitive = meta.NewError(meta.ErrDismatchType, "dismatch primitive types", nil) 29 errInvalidDataSize = meta.NewError(meta.ErrInvalidParam, "invalid data size", nil) // not used 30 errInvalidTag = meta.NewError(meta.ErrInvalidParam, "invalid tag in ReadMessageBegin", nil) 31 errInvalidFieldNumber = meta.NewError(meta.ErrInvalidParam, "invalid field number", nil) 32 errExceedDepthLimit = meta.NewError(meta.ErrStackOverflow, "exceed depth limit", nil) // not used 33 errInvalidDataType = meta.NewError(meta.ErrRead, "invalid data type", nil) 34 errUnknonwField = meta.NewError(meta.ErrUnknownField, "unknown field", nil) 35 errUnsupportedType = meta.NewError(meta.ErrUnsupportedType, "unsupported type", nil) 36 errNotImplemented = meta.NewError(meta.ErrNotImplemented, "not implemted type", nil) // not used 37 ErrConvert = meta.NewError(meta.ErrConvert, "convert type error", nil) 38 errDecodeField = meta.NewError(meta.ErrRead, "invalid field data", nil) 39 ) 40 41 // We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices. 42 var emptyBuf [0]byte 43 44 // Serizalize data to byte array and reuse the memory 45 type BinaryProtocol struct { 46 Buf []byte 47 Read int 48 } 49 50 var ( 51 bpPool = sync.Pool{ 52 New: func() interface{} { 53 return &BinaryProtocol{ 54 Buf: make([]byte, 0, defaultBufferSize), 55 } 56 }, 57 } 58 ) 59 60 func (p *BinaryProtocol) malloc(size int) ([]byte, error) { 61 if size <= 0 { 62 panic(errors.New("invalid size")) 63 } 64 65 l := len(p.Buf) 66 c := cap(p.Buf) 67 d := l + size 68 69 if d > c { 70 c += c >> growBufferFactor 71 if d > c { 72 c = d * 2 73 } 74 buf := rt.Growslice(byteType, *(*rt.GoSlice)(unsafe.Pointer(&p.Buf)), c) 75 p.Buf = *(*[]byte)(unsafe.Pointer(&buf)) 76 } 77 p.Buf = (p.Buf)[:d] 78 79 return (p.Buf)[l:d], nil 80 } 81 82 // next ... 83 func (p *BinaryProtocol) next(size int) ([]byte, error) { 84 if size <= 0 { 85 panic(errors.New("invalid size")) 86 } 87 88 l := len(p.Buf) 89 d := p.Read + size 90 if d > l { 91 return nil, io.EOF 92 } 93 94 ret := (p.Buf)[p.Read:d] 95 p.Read = d 96 return ret, nil 97 } 98 99 // Reset resets the buffer and read position 100 func (p *BinaryProtocol) Reset() { 101 p.Read = 0 102 p.Buf = p.Buf[:0] 103 } 104 105 // RawBuf returns the raw buffer of the protocol 106 func (p *BinaryProtocol) RawBuf() []byte { 107 return p.Buf 108 } 109 110 // Left returns the left bytes to read 111 func (p *BinaryProtocol) Left() int { 112 return len(p.Buf) - p.Read 113 } 114 115 // BinaryProtocol Method 116 func NewBinaryProtol(buf []byte) *BinaryProtocol { 117 bp := bpPool.Get().(*BinaryProtocol) 118 bp.Buf = buf 119 return bp 120 } 121 122 func NewBinaryProtocolBuffer() *BinaryProtocol { 123 bp := bpPool.Get().(*BinaryProtocol) 124 return bp 125 } 126 127 func FreeBinaryProtocol(bp *BinaryProtocol) { 128 bp.Reset() 129 bpPool.Put(bp) 130 } 131 132 func (p *BinaryProtocol) Recycle() { 133 p.Reset() 134 bpPool.Put(p) 135 } 136 137 // Append Tag 138 func (p *BinaryProtocol) AppendTag(num proto.FieldNumber, typ proto.WireType) error { 139 tag := uint64(num)<<3 | uint64(typ&7) 140 if num > proto.MaxValidNumber || num < proto.MinValidNumber { 141 return errInvalidFieldNumber 142 } 143 p.Buf = protowire.BinaryEncoder{}.EncodeUint64(p.Buf, tag) 144 return nil 145 } 146 147 // Append Tag With FieldDescriptor by kind, you must use kind to write tag, because the typedesc when list has no tag 148 func (p *BinaryProtocol) AppendTagByKind(number proto.FieldNumber, kind proto.ProtoKind) error { 149 return p.AppendTag(number, proto.Kind2Wire[kind]) 150 } 151 152 // ConsumeTag parses b as a varint-encoded tag, reporting its length. 153 func (p *BinaryProtocol) ConsumeTag() (proto.FieldNumber, proto.WireType, int, error) { 154 v, n := protowire.ConsumeVarint((p.Buf)[p.Read:]) 155 if n < 0 { 156 return 0, 0, n, errInvalidTag 157 } 158 _, err := p.next(n) 159 if v>>3 > uint64(math.MaxInt32) { 160 return -1, 0, n, errUnknonwField 161 } 162 num, typ := proto.FieldNumber(v>>3), proto.WireType(v&7) 163 if num < proto.MinValidNumber { 164 return 0, 0, n, errInvalidFieldNumber 165 } 166 return num, typ, n, err 167 } 168 169 // ConsumeChildTag parses b as a varint-encoded tag, don't move p.Read 170 func (p *BinaryProtocol) ConsumeTagWithoutMove() (proto.FieldNumber, proto.WireType, int, error) { 171 v, n := protowire.ConsumeVarint((p.Buf)[p.Read:]) 172 if n < 0 { 173 return 0, 0, n, errInvalidTag 174 } 175 if v>>3 > uint64(math.MaxInt32) { 176 return -1, 0, n, errUnknonwField 177 } 178 num, typ := proto.FieldNumber(v>>3), proto.WireType(v&7) 179 if num < proto.MinValidNumber { 180 return 0, 0, n, errInvalidFieldNumber 181 } 182 return num, typ, n, nil 183 } 184 185 // When encoding length-prefixed fields, we speculatively set aside some number of bytes 186 // for the length, encode the data, and then encode the length (shifting the data if necessary 187 // to make room). 188 func AppendSpeculativeLength(b []byte) ([]byte, int) { 189 pos := len(b) 190 b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) // the max length is 4 191 return b, pos 192 } 193 194 func FinishSpeculativeLength(b []byte, pos int) []byte { 195 mlen := len(b) - pos - speculativeLength 196 msiz := protowire.SizeVarint(uint64(mlen)) 197 if msiz != speculativeLength { 198 if cap(b) >= pos+msiz+mlen { 199 b = b[:pos+msiz+mlen] 200 } else { 201 newSlice := make([]byte, pos+msiz+mlen) 202 copy(newSlice, b) 203 b = newSlice 204 } 205 copy(b[pos+msiz:], b[pos+speculativeLength:]) 206 } 207 protowire.AppendVarint(b[:pos], uint64(mlen)) 208 return b 209 } 210 211 /** 212 * Write methods 213 */ 214 215 // WriteBool 216 func (p *BinaryProtocol) WriteBool(value bool) error { 217 if value { 218 return p.WriteUint64(uint64(1)) 219 } else { 220 return p.WriteUint64(uint64(0)) 221 } 222 } 223 224 // WriteInt32 225 func (p *BinaryProtocol) WriteInt32(value int32) error { 226 p.Buf = protowire.BinaryEncoder{}.EncodeInt32(p.Buf, value) 227 return nil 228 } 229 230 // WriteSint32 231 func (p *BinaryProtocol) WriteSint32(value int32) error { 232 p.Buf = protowire.BinaryEncoder{}.EncodeSint32(p.Buf, value) 233 return nil 234 } 235 236 // WriteUint32 237 func (p *BinaryProtocol) WriteUint32(value uint32) error { 238 p.Buf = protowire.BinaryEncoder{}.EncodeUint32(p.Buf, value) 239 return nil 240 } 241 242 // Writefixed32 243 func (p *BinaryProtocol) WriteFixed32(value int32) error { 244 v, err := p.malloc(4) 245 if err != nil { 246 return err 247 } 248 binary.LittleEndian.PutUint32(v, uint32(value)) 249 return err 250 } 251 252 // WriteSfixed32 253 func (p *BinaryProtocol) WriteSfixed32(value int32) error { 254 v, err := p.malloc(4) 255 if err != nil { 256 return err 257 } 258 binary.LittleEndian.PutUint32(v, uint32(value)) 259 return err 260 } 261 262 // WriteInt64 263 func (p *BinaryProtocol) WriteInt64(value int64) error { 264 p.Buf = protowire.BinaryEncoder{}.EncodeInt64(p.Buf, value) 265 return nil 266 } 267 268 // WriteSint64 269 func (p *BinaryProtocol) WriteSint64(value int64) error { 270 p.Buf = protowire.BinaryEncoder{}.EncodeSint64(p.Buf, value) 271 return nil 272 } 273 274 // WriteUint64 275 func (p *BinaryProtocol) WriteUint64(value uint64) error { 276 p.Buf = protowire.BinaryEncoder{}.EncodeUint64(p.Buf, value) 277 return nil 278 } 279 280 // Writefixed64 281 func (p *BinaryProtocol) WriteFixed64(value uint64) error { 282 v, err := p.malloc(8) 283 if err != nil { 284 return err 285 } 286 binary.LittleEndian.PutUint64(v, value) 287 return err 288 } 289 290 // WriteSfixed64 291 func (p *BinaryProtocol) WriteSfixed64(value int64) error { 292 v, err := p.malloc(8) 293 if err != nil { 294 return err 295 } 296 binary.LittleEndian.PutUint64(v, uint64(value)) 297 return err 298 } 299 300 // WriteFloat 301 func (p *BinaryProtocol) WriteFloat(value float32) error { 302 v, err := p.malloc(4) 303 if err != nil { 304 return err 305 } 306 binary.LittleEndian.PutUint32(v, math.Float32bits(float32(value))) 307 return err 308 } 309 310 // WriteDouble 311 func (p *BinaryProtocol) WriteDouble(value float64) error { 312 v, err := p.malloc(8) 313 if err != nil { 314 return err 315 } 316 binary.LittleEndian.PutUint64(v, math.Float64bits(value)) 317 return err 318 } 319 320 // WriteString 321 func (p *BinaryProtocol) WriteString(value string) error { 322 if !utf8.ValidString(value) { 323 return meta.NewError(meta.ErrInvalidParam, value, nil) 324 } 325 p.Buf = protowire.BinaryEncoder{}.EncodeString(p.Buf, value) 326 return nil 327 } 328 329 // WriteBytes 330 func (p *BinaryProtocol) WriteBytes(value []byte) error { 331 p.Buf = protowire.BinaryEncoder{}.EncodeBytes(p.Buf, value) 332 return nil 333 } 334 335 // WriteEnum 336 func (p *BinaryProtocol) WriteEnum(value proto.EnumNumber) error { 337 p.Buf = protowire.BinaryEncoder{}.EncodeInt64(p.Buf, int64(value)) 338 return nil 339 } 340 341 /* 342 * WriteList 343 * packed format:[tag][length][value value value value....] 344 * unpacked format:[tag][(length)][value][tag][(length)][value][tag][(length)][value].... 345 * accpet val type: []interface{} 346 */ 347 func (p *BinaryProtocol) WriteList(desc *proto.TypeDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error { 348 vs, ok := val.([]interface{}) 349 if !ok { 350 return errDismatchPrimitive 351 } 352 fieldId := desc.BaseId() 353 NeedMessageLen := true 354 // packed List bytes format: [tag][length][(L)V][value][value]... 355 if desc.IsPacked() && len(vs) > 0 { 356 p.AppendTag(fieldId, proto.BytesType) 357 var pos int 358 p.Buf, pos = AppendSpeculativeLength(p.Buf) 359 for _, v := range vs { 360 if err := p.WriteBaseTypeWithDesc(desc.Elem(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil { 361 return err 362 } 363 } 364 p.Buf = FinishSpeculativeLength(p.Buf, pos) 365 return nil 366 } 367 368 // unpacked List bytes format: [T(L)V][T(L)V]... 369 for _, v := range vs { 370 // share the same field number for Tag 371 if err := p.AppendTag(fieldId, proto.BytesType); err != nil { 372 return err 373 } 374 375 if err := p.WriteBaseTypeWithDesc(desc.Elem(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil { 376 return err 377 } 378 } 379 return nil 380 } 381 382 /* 383 * WriteMap 384 * Map bytes format: [Pairtag][Pairlength][keyTag(L)V][valueTag(L)V] [Pairtag][Pairlength][T(L)V][T(L)V]... 385 * Pairtag = MapFieldnumber << 3 | wiretype, wiertype = proto.BytesType 386 * accpet val type: map[string]interface{} or map[int]interface{} or map[interface{}]interface{} 387 */ 388 func (p *BinaryProtocol) WriteMap(desc *proto.TypeDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error { 389 baseId := desc.BaseId() 390 MapKey := desc.Key() 391 MapValue := desc.Elem() 392 // check val is map[string]interface{} or map[int]interface{} or map[interface{}]interface{} 393 var vs map[string]interface{} 394 var vs2 map[int]interface{} 395 var vs3 map[interface{}]interface{} 396 var ok bool 397 398 if vs, ok = val.(map[string]interface{}); !ok { 399 if vs2, ok = val.(map[int]interface{}); !ok { 400 if vs3, ok = val.(map[interface{}]interface{}); !ok { 401 return errDismatchPrimitive 402 } 403 } 404 } 405 NeedMessageLen := true 406 if vs != nil { 407 for k, v := range vs { 408 p.AppendTag(baseId, proto.BytesType) 409 var pos int 410 p.Buf, pos = AppendSpeculativeLength(p.Buf) 411 p.AppendTag(1, MapKey.WireType()) 412 p.WriteString(k) 413 p.AppendTag(2, MapValue.WireType()) 414 p.WriteBaseTypeWithDesc(MapValue, v, cast, NeedMessageLen, disallowUnknown, useFieldName) 415 p.Buf = FinishSpeculativeLength(p.Buf, pos) 416 } 417 } else if vs2 != nil { 418 for k, v := range vs2 { 419 p.AppendTag(baseId, proto.BytesType) 420 var pos int 421 p.Buf, pos = AppendSpeculativeLength(p.Buf) 422 p.AppendTag(1, MapKey.WireType()) 423 // notice: may have problem, when k is sfixed64/fixed64 or sfixed32/fixed32 there is no need to use varint 424 // we had better add more code to judge the type of k if write fast 425 // p.WriteInt64(int64(k)) 426 p.WriteBaseTypeWithDesc(MapKey, k, NeedMessageLen, cast, disallowUnknown, useFieldName) // the gerneral way 427 p.AppendTag(2, MapValue.WireType()) 428 p.WriteBaseTypeWithDesc(MapValue, v, NeedMessageLen, cast, disallowUnknown, useFieldName) 429 p.Buf = FinishSpeculativeLength(p.Buf, pos) 430 } 431 } else { 432 for k, v := range vs3 { 433 p.AppendTag(baseId, proto.BytesType) 434 var pos int 435 p.Buf, pos = AppendSpeculativeLength(p.Buf) 436 p.AppendTag(1, MapKey.WireType()) 437 p.WriteBaseTypeWithDesc(MapKey, k, NeedMessageLen, cast, disallowUnknown, useFieldName) // the gerneral way 438 p.AppendTag(2, MapValue.WireType()) 439 p.WriteBaseTypeWithDesc(MapValue, v, NeedMessageLen, cast, disallowUnknown, useFieldName) 440 p.Buf = FinishSpeculativeLength(p.Buf, pos) 441 } 442 } 443 444 return nil 445 } 446 447 /* 448 * Write Message 449 * accpet val type: map[string]interface{} or map[proto.FieldNumber]interface{} 450 * message fields format: [fieldTag(L)V][fieldTag(L)V]... 451 */ 452 func (p *BinaryProtocol) WriteMessageFields(desc *proto.MessageDescriptor, val interface{}, cast bool, disallowUnknown bool, useFieldName bool) error { 453 NeedMessageLen := true 454 if useFieldName { 455 for name, v := range val.(map[string]interface{}) { 456 f := desc.ByName(name) 457 if f == nil { 458 if disallowUnknown { 459 return errUnknonwField 460 } 461 // unknown field will skip when writing 462 continue 463 } 464 if !f.IsMap() && !f.IsList() { 465 if err := p.AppendTag(f.Number(), proto.Kind2Wire[f.Kind()]); err != nil { 466 return meta.NewError(meta.ErrWrite, "append field tag failed", nil) 467 } 468 } 469 470 if err := p.WriteAnyWithDesc(f.Type(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil { 471 return err 472 } 473 } 474 } else { 475 for fieldNumber, v := range val.(map[proto.FieldNumber]interface{}) { 476 f := desc.ByNumber(fieldNumber) 477 if f == nil { 478 if disallowUnknown { 479 return errUnknonwField 480 } 481 continue 482 } 483 484 if !f.IsMap() && !f.IsList() { 485 if err := p.AppendTag(f.Number(), proto.Kind2Wire[f.Kind()]); err != nil { 486 return meta.NewError(meta.ErrWrite, "append field tag failed", nil) 487 } 488 } 489 490 if err := p.WriteAnyWithDesc(f.Type(), v, NeedMessageLen, cast, disallowUnknown, useFieldName); err != nil { 491 return err 492 } 493 } 494 } 495 return nil 496 } 497 498 // WriteBaseType Fields with FieldDescriptor format: (L)V 499 func (p *BinaryProtocol) WriteBaseTypeWithDesc(desc *proto.TypeDescriptor, val interface{}, NeedMessageLen bool, cast bool, disallowUnknown bool, useFieldName bool) error { 500 switch desc.Type() { 501 case proto.BOOL: 502 v, ok := val.(bool) 503 if !ok { 504 if !cast { 505 return errDismatchPrimitive 506 } else { 507 var err error 508 v, err = primitive.ToBool(val) 509 if err != nil { 510 return meta.NewError(meta.ErrConvert, "", err) 511 } 512 } 513 } 514 p.WriteBool(v) 515 case proto.ENUM: 516 v, ok := val.(proto.EnumNumber) 517 if !ok { 518 return meta.NewError(meta.ErrConvert, "convert enum error", nil) 519 } 520 p.WriteEnum(v) 521 case proto.INT32: 522 v, ok := val.(int32) 523 if !ok { 524 if !cast { 525 return errDismatchPrimitive 526 } else { 527 var err error 528 vv, err := primitive.ToInt64(val) 529 if err != nil { 530 return meta.NewError(meta.ErrConvert, "", err) 531 } 532 v = int32(vv) 533 } 534 } 535 p.WriteInt32(v) 536 case proto.SINT32: 537 v, ok := val.(int32) 538 if !ok { 539 if !cast { 540 return errDismatchPrimitive 541 } else { 542 var err error 543 vv, err := primitive.ToInt64(val) 544 if err != nil { 545 return meta.NewError(meta.ErrConvert, "", err) 546 } 547 v = int32(vv) 548 } 549 } 550 p.WriteSint32(v) 551 case proto.UINT32: 552 v, ok := val.(uint32) 553 if !ok { 554 if !cast { 555 return errDismatchPrimitive 556 } else { 557 var err error 558 vv, err := primitive.ToInt64(val) 559 if err != nil { 560 return meta.NewError(meta.ErrConvert, "", err) 561 } 562 v = uint32(vv) 563 } 564 } 565 p.WriteUint32(v) 566 case proto.INT64: 567 v, ok := val.(int64) 568 if !ok { 569 if !cast { 570 return errDismatchPrimitive 571 } else { 572 var err error 573 v, err = primitive.ToInt64(val) 574 if err != nil { 575 return meta.NewError(meta.ErrConvert, "", err) 576 } 577 } 578 } 579 p.WriteInt64(v) 580 case proto.SINT64: 581 v, ok := val.(int64) 582 if !ok { 583 if !cast { 584 return errDismatchPrimitive 585 } else { 586 var err error 587 v, err = primitive.ToInt64(val) 588 if err != nil { 589 return meta.NewError(meta.ErrConvert, "", err) 590 } 591 } 592 } 593 p.WriteSint64(v) 594 case proto.UINT64: 595 v, ok := val.(uint64) 596 if !ok { 597 if !cast { 598 return errDismatchPrimitive 599 } else { 600 var err error 601 vv, err := primitive.ToInt64(val) 602 if err != nil { 603 return meta.NewError(meta.ErrConvert, "", err) 604 } 605 v = uint64(vv) 606 } 607 } 608 p.WriteUint64(v) 609 case proto.SFIX32: 610 v, ok := val.(int32) 611 if !ok { 612 if !cast { 613 return errDismatchPrimitive 614 } else { 615 var err error 616 vv, err := primitive.ToInt64(val) 617 if err != nil { 618 return meta.NewError(meta.ErrConvert, "", err) 619 } 620 v = int32(vv) 621 } 622 } 623 p.WriteSfixed32(v) 624 case proto.FIX32: 625 v, ok := val.(int32) 626 if !ok { 627 if !cast { 628 return errDismatchPrimitive 629 } else { 630 var err error 631 vv, err := primitive.ToInt64(val) 632 if err != nil { 633 return meta.NewError(meta.ErrConvert, "", err) 634 } 635 v = int32(vv) 636 } 637 } 638 p.WriteFixed32(v) 639 case proto.FLOAT: 640 v, ok := val.(float32) 641 if !ok { 642 if !cast { 643 return errDismatchPrimitive 644 } else { 645 var err error 646 vfloat64, err := primitive.ToFloat64(val) 647 v = float32(vfloat64) 648 if err != nil { 649 return meta.NewError(meta.ErrConvert, "", err) 650 } 651 } 652 } 653 p.WriteFloat(v) 654 case proto.SFIX64: 655 v, ok := val.(int64) 656 if !ok { 657 if !cast { 658 return errDismatchPrimitive 659 } else { 660 var err error 661 v, err = primitive.ToInt64(val) 662 if err != nil { 663 return meta.NewError(meta.ErrConvert, "", err) 664 } 665 } 666 } 667 p.WriteSfixed64(v) 668 case proto.FIX64: 669 v, ok := val.(int64) 670 if !ok { 671 if !cast { 672 return errDismatchPrimitive 673 } else { 674 var err error 675 v, err = primitive.ToInt64(val) 676 if err != nil { 677 return meta.NewError(meta.ErrConvert, "", err) 678 } 679 } 680 } 681 p.WriteSfixed64(v) 682 case proto.DOUBLE: 683 v, ok := val.(float64) 684 if !ok { 685 if !cast { 686 return errDismatchPrimitive 687 } else { 688 var err error 689 v, err = primitive.ToFloat64(val) 690 if err != nil { 691 return meta.NewError(meta.ErrConvert, "", err) 692 } 693 } 694 } 695 p.WriteDouble(v) 696 case proto.STRING: 697 v, ok := val.(string) 698 if !ok { 699 if !cast { 700 return errDismatchPrimitive 701 } else { 702 var err error 703 v, err = primitive.ToString(val) 704 if err != nil { 705 return meta.NewError(meta.ErrConvert, "", err) 706 } 707 } 708 } 709 p.WriteString(v) 710 case proto.BYTE: 711 v, ok := val.([]byte) 712 if !ok { 713 return meta.NewError(meta.ErrConvert, "write bytes kind error", nil) 714 } 715 p.WriteBytes(v) 716 case proto.MESSAGE: 717 var ok bool 718 var pos int 719 // prefix message length 720 if NeedMessageLen { 721 p.Buf, pos = AppendSpeculativeLength(p.Buf) 722 } 723 724 if useFieldName { 725 val, ok = val.(map[string]interface{}) 726 } else { 727 val, ok = val.(map[proto.FieldNumber]interface{}) 728 } 729 if !ok { 730 return errDismatchPrimitive 731 } 732 msg := desc.Message() 733 if err := p.WriteMessageFields(msg, val, cast, disallowUnknown, useFieldName); err != nil { 734 return err 735 } 736 // write message length 737 if NeedMessageLen { 738 p.Buf = FinishSpeculativeLength(p.Buf, pos) 739 } 740 default: 741 return errUnsupportedType 742 } 743 return nil 744 } 745 746 // WriteAnyWithDesc explain desc and val and write them into buffer 747 // - LIST will be converted from []interface{} 748 // - MAP will be converted from map[string]interface{} or map[int]interface{} or map[interface{}]interface{} 749 // - MESSAGE will be converted from map[FieldNumber]interface{} or map[string]interface{} 750 func (p *BinaryProtocol) WriteAnyWithDesc(desc *proto.TypeDescriptor, val interface{}, NeedMessageLen bool, cast bool, disallowUnknown bool, useFieldName bool) error { 751 switch { 752 case desc.IsList(): 753 return p.WriteList(desc, val, cast, disallowUnknown, useFieldName) 754 case desc.IsMap(): 755 return p.WriteMap(desc, val, cast, disallowUnknown, useFieldName) 756 default: 757 return p.WriteBaseTypeWithDesc(desc, val, NeedMessageLen, cast, disallowUnknown, useFieldName) 758 } 759 } 760 761 /** 762 * Read methods 763 */ 764 765 // ReadByte 766 func (p *BinaryProtocol) ReadByte() (value byte, err error) { 767 buf, err := p.next(1) 768 if err != nil { 769 return value, err 770 } 771 return byte(buf[0]), err 772 } 773 774 // ReadBool 775 func (p *BinaryProtocol) ReadBool() (bool, error) { 776 v, n := protowire.BinaryDecoder{}.DecodeBool((p.Buf)[p.Read:]) 777 if n < 0 { 778 return false, errDecodeField 779 } 780 _, err := p.next(n) 781 return v, err 782 } 783 784 // ReadInt containing INT32, SINT32, SFIX32, INT64, SINT64, SFIX64, UINT32, UINT64 785 func (p *BinaryProtocol) ReadInt(t proto.Type) (value int, err error) { 786 switch t { 787 case proto.INT32: 788 n, err := p.ReadInt32() 789 return int(n), err 790 case proto.SINT32: 791 n, err := p.ReadSint32() 792 return int(n), err 793 case proto.SFIX32: 794 n, err := p.ReadSfixed32() 795 return int(n), err 796 case proto.INT64: 797 n, err := p.ReadInt64() 798 return int(n), err 799 case proto.SINT64: 800 n, err := p.ReadSint64() 801 return int(n), err 802 case proto.SFIX64: 803 n, err := p.ReadSfixed64() 804 return int(n), err 805 case proto.UINT32: 806 n, err := p.ReadUint32() 807 return int(n), err 808 case proto.UINT64: 809 n, err := p.ReadUint64() 810 return int(n), err 811 default: 812 return 0, errInvalidDataType 813 } 814 } 815 816 // ReadI32 817 func (p *BinaryProtocol) ReadInt32() (int32, error) { 818 value, n := protowire.BinaryDecoder{}.DecodeInt32((p.Buf)[p.Read:]) 819 if n < 0 { 820 return value, errDecodeField 821 } 822 _, err := p.next(n) 823 return value, err 824 } 825 826 // ReadSint32 827 func (p *BinaryProtocol) ReadSint32() (int32, error) { 828 value, n := protowire.BinaryDecoder{}.DecodeSint32((p.Buf)[p.Read:]) 829 if n < 0 { 830 return value, errDecodeField 831 } 832 _, err := p.next(n) 833 return value, err 834 } 835 836 // ReadUint32 837 func (p *BinaryProtocol) ReadUint32() (uint32, error) { 838 value, n := protowire.BinaryDecoder{}.DecodeUint32((p.Buf)[p.Read:]) 839 if n < 0 { 840 return value, errDecodeField 841 } 842 _, err := p.next(n) 843 return value, err 844 } 845 846 // ReadI64 847 func (p *BinaryProtocol) ReadInt64() (int64, error) { 848 value, n := protowire.BinaryDecoder{}.DecodeInt64((p.Buf)[p.Read:]) 849 if n < 0 { 850 return value, errDecodeField 851 } 852 _, err := p.next(n) 853 return value, err 854 } 855 856 // ReadSint64 857 func (p *BinaryProtocol) ReadSint64() (int64, error) { 858 value, n := protowire.BinaryDecoder{}.DecodeSint64((p.Buf)[p.Read:]) 859 if n < 0 { 860 return value, errDecodeField 861 } 862 _, err := p.next(n) 863 return value, err 864 } 865 866 // ReadUint64 867 func (p *BinaryProtocol) ReadUint64() (uint64, error) { 868 value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:]) 869 if n < 0 { 870 return value, errDecodeField 871 } 872 _, err := p.next(n) 873 return value, err 874 } 875 876 // ReadVarint 877 func (p *BinaryProtocol) ReadVarint() (uint64, error) { 878 value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:]) 879 if n < 0 { 880 return value, errDecodeField 881 } 882 _, err := p.next(n) 883 return value, err 884 } 885 886 // ReadFixed32 887 func (p *BinaryProtocol) ReadFixed32() (int32, error) { 888 value, n := protowire.BinaryDecoder{}.DecodeFixed32((p.Buf)[p.Read:]) 889 if n < 0 { 890 return int32(value), errDecodeField 891 } 892 _, err := p.next(n) 893 return int32(value), err 894 } 895 896 // ReadSFixed32 897 func (p *BinaryProtocol) ReadSfixed32() (int32, error) { 898 value, n := protowire.BinaryDecoder{}.DecodeFixed32((p.Buf)[p.Read:]) 899 if n < 0 { 900 return int32(value), errDecodeField 901 } 902 _, err := p.next(n) 903 return int32(value), err 904 } 905 906 // ReadFloat 907 func (p *BinaryProtocol) ReadFloat() (float32, error) { 908 value, n := protowire.BinaryDecoder{}.DecodeFloat32((p.Buf)[p.Read:]) 909 if n < 0 { 910 return value, errDecodeField 911 } 912 _, err := p.next(n) 913 return value, err 914 } 915 916 // ReadFixed64 917 func (p *BinaryProtocol) ReadFixed64() (int64, error) { 918 value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:]) 919 if n < 0 { 920 return int64(value), errDecodeField 921 } 922 _, err := p.next(n) 923 return int64(value), err 924 } 925 926 // ReadSFixed64 927 func (p *BinaryProtocol) ReadSfixed64() (int64, error) { 928 value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:]) 929 if n < 0 { 930 return int64(value), errDecodeField 931 } 932 _, err := p.next(n) 933 return int64(value), err 934 } 935 936 // ReadDouble 937 func (p *BinaryProtocol) ReadDouble() (float64, error) { 938 value, n := protowire.BinaryDecoder{}.DecodeFixed64((p.Buf)[p.Read:]) 939 if n < 0 { 940 return math.Float64frombits(value), errDecodeField 941 } 942 _, err := p.next(n) 943 return math.Float64frombits(value), err 944 } 945 946 // ReadBytes return bytesData and the sum length of L、V in TLV 947 func (p *BinaryProtocol) ReadBytes() ([]byte, error) { 948 value, n, all := protowire.BinaryDecoder{}.DecodeBytes((p.Buf)[p.Read:]) 949 if n < 0 { 950 return emptyBuf[:], errDecodeField 951 } 952 _, err := p.next(all) 953 return value, err 954 } 955 956 // ReadLength return dataLength, and move pointer in the begin of data 957 func (p *BinaryProtocol) ReadLength() (int, error) { 958 value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:]) 959 if n < 0 { 960 return 0, errDecodeField 961 } 962 _, err := p.next(n) 963 return int(value), err 964 } 965 966 // ReadString 967 func (p *BinaryProtocol) ReadString(copy bool) (value string, err error) { 968 bytes, n, all := protowire.BinaryDecoder{}.DecodeBytes((p.Buf)[p.Read:]) 969 if n < 0 { 970 return "", errDecodeField 971 } 972 if copy { 973 value = string(bytes) 974 } else { 975 v := (*rt.GoString)(unsafe.Pointer(&value)) 976 v.Ptr = rt.IndexPtr(*(*unsafe.Pointer)(unsafe.Pointer(&p.Buf)), byteTypeSize, p.Read+n) 977 v.Len = int(all - n) 978 } 979 _, err = p.next(all) 980 return 981 } 982 983 // ReadEnum 984 func (p *BinaryProtocol) ReadEnum() (proto.EnumNumber, error) { 985 value, n := protowire.BinaryDecoder{}.DecodeUint64((p.Buf)[p.Read:]) 986 if n < 0 { 987 return 0, errDecodeField 988 } 989 _, err := p.next(n) 990 return proto.EnumNumber(value), err 991 } 992 993 // ReadList 994 func (p *BinaryProtocol) ReadList(desc *proto.TypeDescriptor, copyString bool, disallowUnknown bool, useFieldName bool) ([]interface{}, error) { 995 hasMessageLen := true 996 elemetdesc := desc.Elem() 997 // Read ListTag 998 fieldNumber, _, _, listTagErr := p.ConsumeTag() 999 if listTagErr != nil { 1000 return nil, meta.NewError(meta.ErrRead, "ConsumeTag failed", nil) 1001 } 1002 list := make([]interface{}, 0, defaultListSize) 1003 // packed list 1004 if desc.IsPacked() { 1005 // read length 1006 length, err := p.ReadLength() 1007 if err != nil { 1008 return nil, err 1009 } 1010 // read list 1011 start := p.Read 1012 for p.Read < start+length { 1013 v, err := p.ReadBaseTypeWithDesc(elemetdesc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1014 if err != nil { 1015 return nil, err 1016 } 1017 list = append(list, v) 1018 } 1019 } else { 1020 // unpacked list 1021 v, err := p.ReadBaseTypeWithDesc(elemetdesc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1022 if err != nil { 1023 return nil, err 1024 } 1025 list = append(list, v) 1026 1027 for p.Read < len(p.Buf) { 1028 // don't move p.Read and judge whether readList completely 1029 elementFieldNumber, _, tagLen, err := p.ConsumeTagWithoutMove() 1030 if err != nil { 1031 return nil, err 1032 } 1033 if elementFieldNumber != fieldNumber { 1034 break 1035 } 1036 1037 if _, moveTagErr := p.next(tagLen); moveTagErr != nil { 1038 return nil, moveTagErr 1039 } 1040 1041 v, err := p.ReadBaseTypeWithDesc(elemetdesc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1042 if err != nil { 1043 return nil, err 1044 } 1045 list = append(list, v) 1046 } 1047 } 1048 return list, nil 1049 } 1050 1051 func (p *BinaryProtocol) ReadPair(keyDesc *proto.TypeDescriptor, valueDesc *proto.TypeDescriptor, copyString bool, disallowUnknown bool, useFieldName bool) (interface{}, interface{}, error) { 1052 hasMessageLen := true 1053 if _, _, _, err := p.ConsumeTag(); err != nil { 1054 return nil, nil, err 1055 } 1056 1057 key, err := p.ReadBaseTypeWithDesc(keyDesc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1058 if err != nil { 1059 return nil, nil, err 1060 } 1061 1062 if _, _, _, err := p.ConsumeTag(); err != nil { 1063 return nil, nil, err 1064 } 1065 value, err := p.ReadBaseTypeWithDesc(valueDesc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1066 if err != nil { 1067 return nil, nil, err 1068 } 1069 return key, value, nil 1070 } 1071 1072 // ReadMap 1073 func (p *BinaryProtocol) ReadMap(desc *proto.TypeDescriptor, copyString bool, disallowUnknown bool, useFieldName bool) (map[interface{}]interface{}, error) { 1074 // read first kv pair tag 1075 fieldNumber, mapWireType, _, mapTagErr := p.ConsumeTag() 1076 if mapTagErr != nil { 1077 return nil, meta.NewError(meta.ErrRead, "ConsumeTag failed", nil) 1078 } 1079 1080 if mapWireType != proto.BytesType { 1081 return nil, meta.NewError(meta.ErrRead, "mapWireType is not BytesType", nil) 1082 } 1083 1084 map_kv := make(map[interface{}]interface{}) 1085 keyDesc := desc.Key() 1086 valueDesc := desc.Elem() 1087 1088 // read first pair length 1089 if _, lengthErr := p.ReadLength(); lengthErr != nil { 1090 return nil, lengthErr 1091 } 1092 // read first Pair 1093 key, value, pairReadErr := p.ReadPair(keyDesc, valueDesc, copyString, disallowUnknown, useFieldName) 1094 if pairReadErr != nil { 1095 return nil, pairReadErr 1096 } 1097 // add first pair 1098 map_kv[key] = value 1099 1100 // check remain pairs 1101 for p.Read < len(p.Buf) { 1102 pairNumber, _, tagLen, pairTagErr := p.ConsumeTagWithoutMove() 1103 if pairTagErr != nil { 1104 return nil, pairTagErr 1105 } 1106 if pairNumber != fieldNumber { 1107 break 1108 } 1109 1110 if _, moveTagErr := p.next(tagLen); moveTagErr != nil { 1111 return nil, moveTagErr 1112 } 1113 1114 if _, pairLenErr := p.ReadLength(); pairLenErr != nil { 1115 return nil, pairLenErr 1116 } 1117 key, value, pairReadErr := p.ReadPair(keyDesc, valueDesc, copyString, disallowUnknown, useFieldName) 1118 if pairReadErr != nil { 1119 return nil, pairReadErr 1120 } 1121 map_kv[key] = value 1122 } 1123 1124 return map_kv, nil 1125 } 1126 1127 // ReadAnyWithDesc read any type by desc and val, the first Tag is parsed outside when use ReadBaseTypeWithDesc 1128 // - LIST/SET will be converted to []interface{} 1129 // - MAP will be converted to map[string]interface{} or map[int]interface{} or map[interface{}]interface{} 1130 // - MESSAGE will be converted to map[proto.FieldNumber]interface{} or map[string]interface{} 1131 func (p *BinaryProtocol) ReadAnyWithDesc(desc *proto.TypeDescriptor, hasMessageLen bool ,copyString bool, disallowUnknown bool, useFieldName bool) (interface{}, error) { 1132 switch { 1133 case desc.IsList(): 1134 return p.ReadList(desc, copyString, disallowUnknown, useFieldName) 1135 case desc.IsMap(): 1136 return p.ReadMap(desc, copyString, disallowUnknown, useFieldName) 1137 default: 1138 return p.ReadBaseTypeWithDesc(desc, hasMessageLen, copyString, disallowUnknown, useFieldName) 1139 } 1140 } 1141 1142 // ReadBaseType with desc, not thread safe 1143 func (p *BinaryProtocol) ReadBaseTypeWithDesc(desc *proto.TypeDescriptor, hasMessageLen bool, copyString bool, disallowUnknown bool, useFieldName bool) (interface{}, error) { 1144 switch desc.Type() { 1145 case proto.BOOL: 1146 v, e := p.ReadBool() 1147 return v, e 1148 case proto.ENUM: 1149 v, e := p.ReadEnum() 1150 return v, e 1151 case proto.INT32: 1152 v, e := p.ReadInt32() 1153 return v, e 1154 case proto.SINT32: 1155 v, e := p.ReadSint32() 1156 return v, e 1157 case proto.UINT32: 1158 v, e := p.ReadUint32() 1159 return v, e 1160 case proto.FIX32: 1161 v, e := p.ReadFixed32() 1162 return v, e 1163 case proto.SFIX32: 1164 v, e := p.ReadSfixed32() 1165 return v, e 1166 case proto.INT64: 1167 v, e := p.ReadInt64() 1168 return v, e 1169 case proto.SINT64: 1170 v, e := p.ReadInt64() 1171 return v, e 1172 case proto.UINT64: 1173 v, e := p.ReadUint64() 1174 return v, e 1175 case proto.FIX64: 1176 v, e := p.ReadFixed64() 1177 return v, e 1178 case proto.SFIX64: 1179 v, e := p.ReadSfixed64() 1180 return v, e 1181 case proto.FLOAT: 1182 v, e := p.ReadFloat() 1183 return v, e 1184 case proto.DOUBLE: 1185 v, e := p.ReadDouble() 1186 return v, e 1187 case proto.STRING: 1188 v, e := p.ReadString(copyString) 1189 return v, e 1190 case proto.BYTE: 1191 v, e := p.ReadBytes() 1192 return v, e 1193 case proto.MESSAGE: 1194 messageLength := len(p.Buf) - p.Read 1195 if hasMessageLen { 1196 length, messageLengthErr := p.ReadLength() 1197 if messageLengthErr != nil { 1198 return nil, messageLengthErr 1199 } 1200 if length == 0 { 1201 return nil, nil 1202 } 1203 messageLength = length 1204 } 1205 1206 fd := *desc 1207 msg := fd.Message() 1208 var retFieldID map[proto.FieldNumber]interface{} 1209 var retString map[string]interface{} 1210 if useFieldName { 1211 retString = make(map[string]interface{}, msg.FieldsCount()) 1212 } else { 1213 retFieldID = make(map[proto.FieldNumber]interface{}, msg.FieldsCount()) 1214 } 1215 // read repeat until sumLength equals MessageLength 1216 start := p.Read 1217 for p.Read < start+messageLength { 1218 fieldNumber, wireType, tagLen, fieldTagErr := p.ConsumeTagWithoutMove() 1219 if fieldTagErr != nil { 1220 return nil, fieldTagErr 1221 } 1222 field := msg.ByNumber(fieldNumber) 1223 if field == nil { 1224 if disallowUnknown { 1225 return nil, errUnknonwField 1226 } 1227 // skip unknown field TLV 1228 if _, moveTagErr := p.next(tagLen); moveTagErr != nil { 1229 return nil, moveTagErr 1230 } 1231 p.Skip(wireType, false) 1232 continue 1233 } 1234 if !field.IsList() && !field.IsMap() { 1235 p.next(tagLen) 1236 } 1237 // sub message has message length, must be true 1238 hasMsgLen := true 1239 v, fieldErr := p.ReadAnyWithDesc(field.Type(), hasMsgLen, copyString, disallowUnknown, useFieldName) 1240 if fieldErr != nil { 1241 return nil, fieldErr 1242 } 1243 if useFieldName { 1244 retString[string(field.Name())] = v 1245 } else { 1246 retFieldID[field.Number()] = v 1247 } 1248 } 1249 if useFieldName { 1250 return retString, nil 1251 } else { 1252 return retFieldID, nil 1253 } 1254 default: 1255 return nil, errInvalidDataType 1256 } 1257 }