github.com/onflow/flow-go@v0.33.17/network/codec/cbor/encoder.go (about)

     1  // (c) 2019 Dapper Labs - ALL RIGHTS RESERVED
     2  
     3  package cbor
     4  
     5  import (
     6  	"bytes"
     7  	"fmt"
     8  
     9  	"github.com/fxamacker/cbor/v2"
    10  
    11  	cborcodec "github.com/onflow/flow-go/model/encoding/cbor"
    12  	"github.com/onflow/flow-go/network/codec"
    13  	_ "github.com/onflow/flow-go/utils/binstat"
    14  )
    15  
    16  // Encoder is an encoder to write serialized CBOR to a writer.
    17  type Encoder struct {
    18  	enc *cbor.Encoder
    19  }
    20  
    21  // Encode will convert the given message into CBOR and write it to the
    22  // underlying encoder, followed by a new line.
    23  func (e *Encoder) Encode(v interface{}) error {
    24  	// encode the value
    25  	code, what, err := codec.MessageCodeFromInterface(v)
    26  	if err != nil {
    27  		return fmt.Errorf("could not determine envelope code string: %w", err)
    28  	}
    29  
    30  	// encode the payload
    31  	//bs1 := binstat.EnterTime(fmt.Sprintf("%s%s%s:%d", binstat.BinNet, ":strm<1(cbor)", what, code)) // e.g. ~3net::strm<1(cbor)CodeEntityRequest:23
    32  	var data bytes.Buffer
    33  	_ = data.WriteByte(code.Uint8())
    34  	encoder := cborcodec.EncMode.NewEncoder(&data)
    35  	err = encoder.Encode(v)
    36  	//binstat.LeaveVal(bs1, int64(data.Len()))
    37  	if err != nil {
    38  		return fmt.Errorf("could not encode cbor payload with message code %d aka %s: %w", code, what, err) // e.g. 2, "CodeBlockProposal", <CBOR error>
    39  	}
    40  
    41  	// encode / append the envelope code and write to stream
    42  	//bs2 := binstat.EnterTime(binstat.BinNet+":strm<2(cbor)envelope2payload2iowriter")
    43  	dataBytes := data.Bytes()
    44  	err = e.enc.Encode(dataBytes)
    45  	//binstat.LeaveVal(bs2, int64(data.Len()))
    46  	if err != nil {
    47  		return fmt.Errorf("could not encode to stream: %w", err)
    48  	}
    49  
    50  	return nil
    51  }