github.com/koko1123/flow-go-1@v0.29.6/network/codec/cbor/decoder.go (about)

     1  // (c) 2019 Dapper Labs - ALL RIGHTS RESERVED
     2  
     3  package cbor
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"github.com/fxamacker/cbor/v2"
     9  
    10  	"github.com/koko1123/flow-go-1/network/codec"
    11  	_ "github.com/koko1123/flow-go-1/utils/binstat"
    12  )
    13  
    14  // Decoder implements a stream decoder for CBOR.
    15  type Decoder struct {
    16  	dec *cbor.Decoder
    17  }
    18  
    19  // Decode will decode the next CBOR value from the stream.
    20  // Expected error returns during normal operations:
    21  //   - codec.ErrInvalidEncoding if message encoding is invalid.
    22  //   - codec.ErrUnknownMsgCode if message code byte does not match any of the configured message codes.
    23  //   - codec.ErrMsgUnmarshal if the codec fails to unmarshal the data to the message type denoted by the message code.
    24  func (d *Decoder) Decode() (interface{}, error) {
    25  
    26  	// read from stream and extract code
    27  	var data []byte
    28  	//bs1 := binstat.EnterTime(binstat.BinNet + ":strm>1(cbor)iowriter2payload2envelope")
    29  	err := d.dec.Decode(&data)
    30  	//binstat.LeaveVal(bs1, int64(len(data)))
    31  	if err != nil {
    32  		return nil, codec.NewInvalidEncodingErr(err)
    33  	}
    34  
    35  	if len(data) == 0 {
    36  		return nil, codec.NewInvalidEncodingErr(fmt.Errorf("empty data"))
    37  	}
    38  
    39  	msgInterface, what, err := codec.InterfaceFromMessageCode(data[0])
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	// unmarshal the payload
    45  	//bs2 := binstat.EnterTimeVal(fmt.Sprintf("%s%s%s:%d", binstat.BinNet, ":strm>2(cbor)", what, code), int64(len(data))) // e.g. ~3net:strm>2(cbor)CodeEntityRequest:23
    46  	err = defaultDecMode.Unmarshal(data[1:], msgInterface) // all but first byte
    47  	//binstat.Leave(bs2)
    48  	if err != nil {
    49  		return nil, codec.NewMsgUnmarshalErr(data[0], what, err)
    50  	}
    51  
    52  	return msgInterface, nil
    53  }